From steve at pearwood.info Tue Nov 1 00:10:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Nov 2011 10:10:05 +1100 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: <4EAF2ACD.4030005@pearwood.info> Alan Gauld wrote: > On 31/10/11 20:22, Peter Otten wrote: >> Alan Gauld wrote: >> >>> if choice.lower() not in ('prs'): # NB use a single string >> >> That's not a good idea. If a user accidentally enters PR (for example) >> your >> version will mistake that for a valid choice. > > Good point, although you could test the first character only... > > if choice[0].lower() not in ('prs'): # NB use a single string Why would you do that? If the user is supposed to enter a single letter, why would you accept (for example) "screw you hippy, I hate this game!" as the valid response "s"? -- Steven From steve at pearwood.info Tue Nov 1 00:30:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Nov 2011 10:30:40 +1100 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAED63C.90603@gmail.com> References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: <4EAF2FA0.6080101@pearwood.info> Joel Montes de Oca wrote: > When the user enters an invalid letter, FUNCTION B calls FUNCTION A. > FUNCTION A returns choice to FUNCTION B. FUNCTION B does nothing with > the return, FUNCTION MAIN gets nothing to returned to it, thus choice is > NONE. > > FUN MAIN > | > | > |__ FUN A > | > | > |_ FUN B > > This is how I understand it. So if I want this to work, I need FUN B to > give something back to FUN A so that FUN A will have something to give > back to FUN MAIN but that doesn't feel right. But that's exactly right. Think of people at a dinner table. Fred turns to Barney and says "Pass me the salt please." Barney can't reach the salt, so he turns to Wilma and asks the same thing. Wilma hands Barney the salt. Now Barney has to actually hand the salt to Fred or else Fred doesn't get anything. So if you care about getting a value back from something, and passing it on elsewhere, you MUST use return. > Is there a way to say GO TO FUN A instead of calling the function? No. That's what a function call is: it's a safe goto. (Technically, it's more like GOSUB if you remember your BASIC.) -- Steven From ckava1 at msn.com Tue Nov 1 02:02:46 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Mon, 31 Oct 2011 21:02:46 -0400 Subject: [Tutor] Help Message-ID: This code is from the book 'Invent your own computer games with Python' 2nd edition. Great book so far. . . My question comes on the 2nd game (dragon game). Just a simple little program that lets you choose to enter 'cave one' or 'cave two' by using the random module, radnom.randint. If you choose the 'wrong' cave, you get a message saying 'sorry you've been eaten'. Choose the correct cave and you get a message that 'you get the treasure. Pretty simple. . However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}. Here's the description of this line the author gives: "Here we check if the integer of the cave we chose ('1' or '2') is equal to the cave randomly selected to have the friendly dragon" My question is, we saved the integer of the cave we chose in the variable {cave}in line 15, not {chosenCave}. So, what the heck am I missing?? How is the {chosenCave} variable now holding the choice I made in the {cave} variable?? Keep in mind I'm a beginner, but geez, I should understand this easily! I'm very frustrated right now, I should easily know this. But, I don't, lol. Thanks in advance for any help!! Code below: dragon.py This code can be downloaded from http://inventwithpython.com/dragon.py If you get errors after typing this code in, compare it to the book's code with the online diff tool at http://inventwithpython.com/diff or email the author at al at inventwithpython.com 1. import random 2. import time 3. 4. def displayIntro(): 5. print('You are on a planet full of dragons. In front of you,') 6. print('you see two caves. In one cave, the dragon is friendly') 7. print('and will share his treasure with you. The other dragon') 8. print('is greedy and hungry, and will eat you on sight.') 9. print() 10. 11. def chooseCave(): 12. cave = '' 13. while cave != '1' and cave != '2': 14. print('Which cave will you go into? (1 or 2)') 15. cave = input() 16. 17. return cave 18. 19. def checkCave(chosenCave): 20. print('You approach the cave...') 21. time.sleep(2) 22. print('It is dark and spooky...') 23. time.sleep(2) 24. print('A large dragon jumps out in front of you! He opens his jaws and...') 25. print() 26. time.sleep(2) 27. 28. friendlyCave = random.randint(1, 2) 29. 30. if chosenCave == str(friendlyCave): 31. print('Gives you his treasure!') 32. else: 33. print('Gobbles you down in one bite!') 34. 35. playAgain = 'yes' 36. while playAgain == 'yes' or playAgain == 'y': 37. 38. displayIntro() 58 39. 40. caveNumber = chooseCave() 41. 42. checkCave(caveNumber) 43. 44. print('Do you want to play again? (yes or no)') From steve at pearwood.info Tue Nov 1 02:33:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Nov 2011 12:33:44 +1100 Subject: [Tutor] Simple Question On A Method (in subclass) In-Reply-To: References: <4EA4939A.2070602@davea.name> <4EA66A3E.6010701@davea.name> Message-ID: <4EAF4C78.3090606@pearwood.info> Marc Tompkins wrote: > It can be a little hard to wrap your head around how Python handles > variables/objects; in other languages you create a variable and assign a > value to it, while in Python you create an object and assign a name to it - > the name can change while the object remains unchanged. Here's a very > simplified demo of what Dave is talking about: [...] > It's extremely logical, but almost entirely backward from the way most other > languages do things. Possibly it's because Guido is Dutch. Fortunately, that is untrue. I'm not sure where the myth that "Python is different from other languages" comes from. I suppose it is true only so far as *every* language is different from any other language (otherwise they would be the same language!). But Python is not so different from other common languages. In particular, I don't know of any language where assignment means aliasing. Take the example Marc gave earlier: t = 'this' s = 'that' group = [t, s] print group # => "['this', 'that'] s = 'the other' print group # => "['this', 'that'] I don't know of any language where the second item of group would now equal 'the other'. Pascal certainly isn't one: program example (input, output); var t,s: String(10); group: array[1..2] of String(10); begin t:='this'; s:='that'; group[1]:=t; group[2]:=s; writeln(group[1], ' ', group[2]); s:='the other'; writeln(group[1], ' ', group[2]); end. Running that program gives the equivalent output to Python: this that this that PHP is the same. Using the PHP interactive shell: php > $t = 'this'; php > $s = 'that'; php > $group[0] = $t; php > $group[1] = $s; php > print_r($group); Array ( [0] => this [1] => that ) php > $t = 'the other'; php > print_r($group); Array ( [0] => this [1] => that ) This myth of Python being radically different from other languages is especially mysterious since many of the most popular and common modern languages use *exactly* the same name binding execution model as Python, e.g. Java and Ruby. (In the case of Java, that only applies to boxed objects, and not unboxed low-level ints and similar. If this means nothing to you, feel fortunate.) -- Steven From steve at pearwood.info Tue Nov 1 02:55:47 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 01 Nov 2011 12:55:47 +1100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <4EAF51A3.1090407@pearwood.info> Chris Kavanagh wrote: > However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}. > Here's the description of this line the author gives: > > "Here we check if the integer of the cave we chose ('1' or '2') is equal > to the cave > randomly selected to have the friendly dragon" > > My question is, we saved the integer of the cave we chose in the > variable {cave}in line 15, not {chosenCave}. So, what the heck am I > missing?? How is the {chosenCave} variable now holding the choice I made > in the {cave} variable?? Unfortunately, the indentation of your code is completely mangled for me, which makes it difficult to be sure which parts of the code are inside functions and which are not. So I will be forced to guess. I can tell that line 15 is inside the function chooseCave(), and so the variable "cave" is a local variable. Local variables only exist inside the function that creates them. In this case, the chooseCave() function returns the value of "cave" to the caller. That is, at the end of your code, you call the functions you earlier created: caveNumber = chooseCave() checkCave(caveNumber) These two lines cause the following to happen: The function chooseCave() gets called. Execution shifts into the function chooseCave: 1 you are asked for a cave number 2 your response is stored temporarily in the local variable "cave" 3 and then returned to the caller At this point, Python clears up the local variables, reclaiming their memory ready for next time they are needed, and stores your response in the global (top level) variable "caveNumber". Next, you call the checkCave function with "caveNumber" as an argument. This gets passed to the checkCave function, which sees it under the local variable name "chosenCave". *Inside* the checkCave function, the value which is known *outside* as "caveNumber" is known as "chosenCave". And so inside the function, the line: if chosenCave== str(friendlyCave) works and the chosen cave number (known as "caveNumber" on the outside and "chosenCave" on the inside) is compared to the friendly cave. This might seem a bit confusing at first, but stick with it, it will soon become completely natural. Having different names for the same value in different contexts is a good thing. It's a bit like how the same person might be called: Mr President Barrack Obama Mr Obama Barrack Dad Son POTUS Bazza depending on who is referring to him and under what circumstances. (That last one might only be in Australia...) The important thing to remember is this: *Outside* of a function, all variables are *global*. You can't have two global variables called "x" at the same time: x = 1 x = 2 The second line replaces the value of x with a new value. *Inside* a function, all variable assignments are *local*. (You can change that with the "global" keyword, but you shouldn't.) A bit like going to Los Angeles, what happens inside a function stays inside the function. Local variable "x" doesn't interfere with global variable "x", or with local "x" of any other function. The only way to get the value of local "x" out and pass it to another function is with the return statement. I hope this helps. -- Steven From joelmontes01 at gmail.com Tue Nov 1 03:45:37 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Mon, 31 Oct 2011 22:45:37 -0400 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EAF2ACD.4030005@pearwood.info> References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> <4EAF2ACD.4030005@pearwood.info> Message-ID: <4EAF5D51.3000300@gmail.com> On 10/31/2011 07:10 PM, Steven D'Aprano wrote: > Alan Gauld wrote: >> On 31/10/11 20:22, Peter Otten wrote: >>> Alan Gauld wrote: >>> >>>> if choice.lower() not in ('prs'): # NB use a single string >>> >>> That's not a good idea. If a user accidentally enters PR (for >>> example) your >>> version will mistake that for a valid choice. >> >> Good point, although you could test the first character only... >> >> if choice[0].lower() not in ('prs'): # NB use a single string > > Why would you do that? If the user is supposed to enter a single > letter, why would you accept (for example) "screw you hippy, I hate > this game!" as the valid response "s"? > > > I agree, I am not sure that I see the benefit of using a single string. If anything, it makes it a bit harder to read by someone other than the person who wrote it. if choice.lower() in ('p', 'r','s'): I think the code above is a lot clearer. -- -Joel M. From ckava1 at msn.com Tue Nov 1 04:07:13 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Mon, 31 Oct 2011 23:07:13 -0400 Subject: [Tutor] Help In-Reply-To: <4EAF51A3.1090407@pearwood.info> References: <4EAF51A3.1090407@pearwood.info> Message-ID: Yes Steven, that solved my question(s). It also cleared up what was to be my next question! Thanks so much. You might not realize how grateful I am to be able to have you & others on the list answer my questions. Just trust me when I say, I am grateful. And I apologize for the code being mangled on your end. I'm not sure why this happened, but you were correct in your assumptions. . . One thing I'm curious about. If the code is read by the Interpreter or Compiler from the top down, why in this case, does it not get confused (cause an error) when it hits line 30, if it doesn't yet know that {caveNumber=chooseCave()} and checkCave(caveNumber)}?? It seems to me in my limited experience, those last two lines should've come before line 30. It seems as though it would've made more sense to somehow put them before. In other languages, ala C++, don't global variables have to be declared at the 'top' of the code?? On 10/31/2011 9:55 PM, Steven D'Aprano wrote: > Chris Kavanagh wrote: > >> However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}. >> Here's the description of this line the author gives: >> >> "Here we check if the integer of the cave we chose ('1' or '2') is >> equal to the cave >> randomly selected to have the friendly dragon" >> >> My question is, we saved the integer of the cave we chose in the >> variable {cave}in line 15, not {chosenCave}. So, what the heck am I >> missing?? How is the {chosenCave} variable now holding the choice I >> made in the {cave} variable?? > > Unfortunately, the indentation of your code is completely mangled for > me, which makes it difficult to be sure which parts of the code are > inside functions and which are not. So I will be forced to guess. > > I can tell that line 15 is inside the function chooseCave(), and so the > variable "cave" is a local variable. Local variables only exist inside > the function that creates them. In this case, the chooseCave() function > returns the value of "cave" to the caller. > > That is, at the end of your code, you call the functions you earlier > created: > > caveNumber = chooseCave() > checkCave(caveNumber) > > > These two lines cause the following to happen: > > The function chooseCave() gets called. Execution shifts into the > function chooseCave: > > 1 you are asked for a cave number > 2 your response is stored temporarily in the local variable "cave" > 3 and then returned to the caller > > At this point, Python clears up the local variables, reclaiming their > memory ready for next time they are needed, and stores your response in > the global (top level) variable "caveNumber". > > Next, you call the checkCave function with "caveNumber" as an argument. > This gets passed to the checkCave function, which sees it under the > local variable name "chosenCave". *Inside* the checkCave function, the > value which is known *outside* as "caveNumber" is known as "chosenCave". > And so inside the function, the line: > > if chosenCave== str(friendlyCave) > > works and the chosen cave number (known as "caveNumber" on the outside > and "chosenCave" on the inside) is compared to the friendly cave. > > This might seem a bit confusing at first, but stick with it, it will > soon become completely natural. > > Having different names for the same value in different contexts is a > good thing. It's a bit like how the same person might be called: > > Mr President > Barrack Obama > Mr Obama > Barrack > Dad > Son > POTUS > Bazza > > depending on who is referring to him and under what circumstances. (That > last one might only be in Australia...) > > The important thing to remember is this: > > > *Outside* of a function, all variables are *global*. You can't have two > global variables called "x" at the same time: > > x = 1 > x = 2 > > The second line replaces the value of x with a new value. > > *Inside* a function, all variable assignments are *local*. (You can > change that with the "global" keyword, but you shouldn't.) A bit like > going to Los Angeles, what happens inside a function stays inside the > function. Local variable "x" doesn't interfere with global variable "x", > or with local "x" of any other function. The only way to get the value > of local "x" out and pass it to another function is with the return > statement. > > > I hope this helps. > > > From ckava1 at msn.com Tue Nov 1 05:10:35 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Tue, 1 Nov 2011 00:10:35 -0400 Subject: [Tutor] Help In-Reply-To: References: <4EAF51A3.1090407@pearwood.info> Message-ID: I'm going to thank Steven once again, and answer my own question in the 2nd paragraph directly below (Steven hasn't had a chance to respond yet). I just learned that the Function definitions are not read by the interpreter UNTIL they are called. I was reading them and assuming they were executed from the top down. Obviously I was getting somewhat confused because of this. This 'dragon' program makes much more sense to me now that I understand that. . .Thanks again Steven & everyone!!! Happy Halloween!!! On 10/31/2011 11:07 PM, Chris Kavanagh wrote: > Yes Steven, that solved my question(s). It also cleared up what was to > be my next question! Thanks so much. You might not realize how grateful > I am to be able to have you & others on the list answer my questions. > Just trust me when I say, I am grateful. And I apologize for the code > being mangled on your end. I'm not sure why this happened, but you were > correct in your assumptions. . . > > One thing I'm curious about. If the code is read by the Interpreter or > Compiler from the top down, why in this case, does it not get confused > (cause an error) when it hits line 30, if it doesn't yet know that > {caveNumber=chooseCave()} and checkCave(caveNumber)}?? It seems to me in > my limited experience, those last two lines should've come before line > 30. It seems as though it would've made more sense to somehow put them > before. In other languages, ala C++, don't global variables have to be > declared at the 'top' of the code?? > > On 10/31/2011 9:55 PM, Steven D'Aprano wrote: >> Chris Kavanagh wrote: >> >>> However, I'm confused on Line 30 {if chosenCave== str(friendlyCave)}. >>> Here's the description of this line the author gives: >>> >>> "Here we check if the integer of the cave we chose ('1' or '2') is >>> equal to the cave >>> randomly selected to have the friendly dragon" >>> >>> My question is, we saved the integer of the cave we chose in the >>> variable {cave}in line 15, not {chosenCave}. So, what the heck am I >>> missing?? How is the {chosenCave} variable now holding the choice I >>> made in the {cave} variable?? >> >> Unfortunately, the indentation of your code is completely mangled for >> me, which makes it difficult to be sure which parts of the code are >> inside functions and which are not. So I will be forced to guess. >> >> I can tell that line 15 is inside the function chooseCave(), and so the >> variable "cave" is a local variable. Local variables only exist inside >> the function that creates them. In this case, the chooseCave() function >> returns the value of "cave" to the caller. >> >> That is, at the end of your code, you call the functions you earlier >> created: >> >> caveNumber = chooseCave() >> checkCave(caveNumber) >> >> >> These two lines cause the following to happen: >> >> The function chooseCave() gets called. Execution shifts into the >> function chooseCave: >> >> 1 you are asked for a cave number >> 2 your response is stored temporarily in the local variable "cave" >> 3 and then returned to the caller >> >> At this point, Python clears up the local variables, reclaiming their >> memory ready for next time they are needed, and stores your response in >> the global (top level) variable "caveNumber". >> >> Next, you call the checkCave function with "caveNumber" as an argument. >> This gets passed to the checkCave function, which sees it under the >> local variable name "chosenCave". *Inside* the checkCave function, the >> value which is known *outside* as "caveNumber" is known as "chosenCave". >> And so inside the function, the line: >> >> if chosenCave== str(friendlyCave) >> >> works and the chosen cave number (known as "caveNumber" on the outside >> and "chosenCave" on the inside) is compared to the friendly cave. >> >> This might seem a bit confusing at first, but stick with it, it will >> soon become completely natural. >> >> Having different names for the same value in different contexts is a >> good thing. It's a bit like how the same person might be called: >> >> Mr President >> Barrack Obama >> Mr Obama >> Barrack >> Dad >> Son >> POTUS >> Bazza >> >> depending on who is referring to him and under what circumstances. (That >> last one might only be in Australia...) >> >> The important thing to remember is this: >> >> >> *Outside* of a function, all variables are *global*. You can't have two >> global variables called "x" at the same time: >> >> x = 1 >> x = 2 >> >> The second line replaces the value of x with a new value. >> >> *Inside* a function, all variable assignments are *local*. (You can >> change that with the "global" keyword, but you shouldn't.) A bit like >> going to Los Angeles, what happens inside a function stays inside the >> function. Local variable "x" doesn't interfere with global variable "x", >> or with local "x" of any other function. The only way to get the value >> of local "x" out and pass it to another function is with the return >> statement. >> >> >> I hope this helps. >> >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From rinu.matrix at gmail.com Tue Nov 1 06:31:25 2011 From: rinu.matrix at gmail.com (Rinu Boney) Date: Tue, 1 Nov 2011 11:01:25 +0530 Subject: [Tutor] Pickle Class Instances Message-ID: This Is My Program : class book: def __init__(self,bno=100,bname='Book'): self.book_number=bno self.book_name=bname def enter_book(self): self.book_number=input("Enter Book No : ") self.book_name=input("Enter Book Name : ") def display_book(self): print('Book No : ',self.book_number) print('Book Name : ',self.book_name) b1 = book() b=book() def add_book(b): fo=open('books.dat','wb') pickle.dump(b,fo) fo.close() def display_books(): global b1 fi=open('books.dat','rb') b1=pickle.load(fi) b1.display_book() fi.close() The Display After Unpickling Shows only the last Class Instance. How To Display All The Data In The File ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rinu.matrix at gmail.com Tue Nov 1 06:38:23 2011 From: rinu.matrix at gmail.com (Rinu Boney) Date: Tue, 1 Nov 2011 11:08:23 +0530 Subject: [Tutor] Pickling Class Instances Message-ID: I have a class 'book' and function for input and display of the class members then there are 2 functions for pickling and unpickling class instances from and to a file. after unpickling , then displaying it shows only the last class instance stored in the file! what can be the possible problems? -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Tue Nov 1 07:53:04 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Tue, 01 Nov 2011 07:53:04 +0100 Subject: [Tutor] Pickle Class Instances In-Reply-To: References: Message-ID: <4EAF9750.7090607@gmx.net> On 2011-11-01 06:31, Rinu Boney wrote: > def add_book(b): > fo=open('books.dat','wb') > pickle.dump(b,fo) > fo.close() > > The Display After Unpickling Shows only the last Class Instance. > How To Display All The Data In The File ? You haven't shown us the complete program (how to you call "add_book" and "display_books"?) but I guess that you call "add_book" with one instance (if not, you can ignore the rest). In that case there is no more data in the file. In your "add_book" function you open the file "books.at" and just save one instance. The next time you call the function with another instance you overwrite the former, because opening the same file with the parameter "w" (or in your case "wb") deletes any already existing content. What you probably want is to put all the instances into a list and save this list. When you later read the file, you'll get the list back and you can iterate over it for displaying. Bye, Andreas From __peter__ at web.de Tue Nov 1 10:46:20 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Nov 2011 10:46:20 +0100 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: Alan Gauld wrote: > On 31/10/11 20:22, Peter Otten wrote: >> Alan Gauld wrote: >> >>> if choice.lower() not in ('prs'): # NB use a single string >> >> That's not a good idea. If a user accidentally enters PR (for example) >> your version will mistake that for a valid choice. > > Good point, although you could test the first character only... > > if choice[0].lower() not in ('prs'): # NB use a single string What Steven says, plus you may run into an IndexError if choice is the empty string. If you absolutely want to test against a single string you have to check the length first. From rhettnaxel at gmail.com Tue Nov 1 12:31:07 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Tue, 1 Nov 2011 07:31:07 -0400 Subject: [Tutor] GNU Emacs and Python In-Reply-To: <20111031193142.GF9335@akwebsoft.com> References: <20111031193142.GF9335@akwebsoft.com> Message-ID: <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> On Oct 31, 2011, at 15:31, Tim Johnson wrote: > * Rinu Boney [111031 07:03]: >> I Use Windows.I Already Know C/C++ which makes python syntax seem very easy. >> Maybe Setting Up Emacs With Python Will Make Me Productive. >> I Have Eclipse With PyDev. >> Why Is There Not A Pythonic Emacs? > Rinu, by this time I believe that Alan has addressed your question > above. He has also (wisely) provided caveats regarding the > difficulty of learning emacs itself. > > I'll take a reverse of Alan's comments, not to contradict him, but > to give a possible different perspective: > > If you learn to use emacs with python, you will essentially be > learning *two* programming languages: Python _and_ elisp, which is > the internal programming language of emacs. Emacs is essentially > an elisp interpreter. There may be advantages to learning two > languages simultaneously. > > This will take time. A lot of time. Do you have the time? Will you > be compensated for the time? :) having two additional programming > languages "under your belt" may be considered compensation. > > In case you do not know this: Emacs has the ability to run the > python or language-your-choice interpreter asynchronous within the > editor, in it's own window. There could be great advantages to > this. I have in the past, written elisp code that allows me two > write code in one window and have it evaluated in the 'python > window' or 'language-of-your-choice window'. > > I'll reiterate what I said earlier, I no longer use emacs, but > have great respect for it. I use vim linked against the python > binary so that I can use python code to enhance my (hand-rolled) > "IDE". I much prefer python code to elisp code. > > I hope my comments are of some help. I'm sure that you have been > well informed as to what you would be getting youself into. :) > regards > -- > Tim Rinu, I use emacs. I use Python and C++. I'm also a university student. Last semester I learned python 2.7 using IDLE, and continued with IDLE while I searched for alternatives over the summer. I didn't find what I was looking for. Say, just a few weeks ago I started my C++ course and switched to emacs since the professor was using it. I tried it, read the easy to understand documentation, and I am so productive, jubilant, and satisfied with GNU Emacs. It's extensible beyond immediate comprehension; like a sunflower it starts as a seed, sprouts leaves, etc; I'm elaborating the infinite usability of emacs. There is a learning curve. One may find a learning curve with everything in existence, whereas I repudiate one discouraging another for the aforementioned. Those who desire the power of emacs seek it. Tim, do you use GNU Emacs? From what literature I've encountered including a wikipedia page I believe there is a satiric starwars-like cold-war feud between users of vi and emacs. I'm neutral and won't judge an entity or patronize one for their use of free will. I'm happy. Forgive me if I appear too anything. Good Day. Alexander Etter From d at davea.name Tue Nov 1 13:35:33 2011 From: d at davea.name (Dave Angel) Date: Tue, 01 Nov 2011 08:35:33 -0400 Subject: [Tutor] Help In-Reply-To: References: <4EAF51A3.1090407@pearwood.info> Message-ID: <4EAFE795.2010602@davea.name> (Pleas put your reply after the part you're quoting. What you did is called top-posting, and makes reading the messages very confusing) On 11/01/2011 12:10 AM, Chris Kavanagh wrote: > I'm going to thank Steven once again, and answer my own question in > the 2nd paragraph directly below (Steven hasn't had a chance to > respond yet). > > I just learned that the Function definitions are not read by the > interpreter UNTIL they are called. I was reading them and assuming > they were executed from the top down. Obviously I was getting somewhat > confused because of this. This 'dragon' program makes much more sense > to me now that I understand that. . .Thanks again Steven & everyone!!! > Happy Halloween!!! > That's not correct either. The interpreter definitely reads the file from top down. But sometimes the effect of the code in this phase is to build some structures for later use. For example the def keyword says that the line and some following ones are to be compiled into an object form representing a function. Default arguments are exececuted at this time, but none of the rest. it's compiled into a function object, and saved in the current namespace (typically the global one) for later use. Then when the interpreter encounters a function call, it looks up the name, and if it's "callable" (as a function object is), it gets its parameters filled in and gets used. Then when that function returns, the interpreter continues interpreting till the end of file. But notice that when you are executing inside a function, you may encounter references to the same or other functions. At this point they do need to have been compiled into callable objects. So while the order of the function definitions doesn't matter for calls made from the end of the file, you can get into trouble if some function is called which tries to call another one not yet compiled. To avoid this possibility, the standard paradigm is to put all top-level code at the end of file (and inside an if __name__ == "__main__" clause) . > On 10/31/2011 11:07 PM, Chris Kavanagh wrote: >> Yes Steven, that solved my question(s). It also cleared up what was to >> be my next question! Thanks so much. You might not realize how grateful >> I am to be able to have you & others on the list answer my questions. >> Just trust me when I say, I am grateful. And I apologize for the code >> being mangled on your end. I'm not sure why this happened, but you were >> correct in your assumptions. . . >> >> One thing I'm curious about. If the code is read by the Interpreter or >> Compiler from the top down, why in this case, does it not get confused >> (cause an error) when it hits line 30, if it doesn't yet know that >> {caveNumber=chooseCave()} and checkCave(caveNumber)}?? It seems to me in >> my limited experience, those last two lines should've come before line >> 30. It seems as though it would've made more sense to somehow put them >> before. In other languages, ala C++, don't global variables have to be >> declared at the 'top' of the code?? >> The main reason that C and C++ require declarations before use is that different kinds of variables take differing spaces, and the compiler figures out the memory layout before generating the code. The compiler would have to be much more complex if it didn't have those restrictions. In python, symbols ( colloquailly called "variables") don' t have any type, and can refer to different kinds of objects at different times. -- DaveA From jbr5393 at gmail.com Tue Nov 1 14:48:03 2011 From: jbr5393 at gmail.com (Jefferson Ragot) Date: Tue, 1 Nov 2011 21:48:03 +0800 Subject: [Tutor] A question about sys.argv Message-ID: In a Vista command prompt if I typed this: >>> python somescript.py filename Will sys.argv[1] return a valid path or just the filename? If it just returns the filename, is there a simple way to get the path? -- Jefferson B. Ragot -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Nov 1 14:55:18 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 1 Nov 2011 09:55:18 -0400 Subject: [Tutor] A question about sys.argv In-Reply-To: References: Message-ID: On Tue, Nov 1, 2011 at 9:48 AM, Jefferson Ragot wrote: > In a Vista command prompt if I typed this: > > >>> python somescript.py filename > > Will sys.argv[1] return a valid path or just the filename? > If it just returns the filename, is there a simple way to get the path? > > -- > Jefferson B. Ragot > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > sysargv[1] returns the text following your script. You can find the current working directory with this: http://docs.python.org/library/os.html#os.getcwd -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Nov 1 15:05:28 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 1 Nov 2011 15:05:28 +0100 Subject: [Tutor] A question about sys.argv In-Reply-To: References: Message-ID: On Tue, Nov 1, 2011 at 2:48 PM, Jefferson Ragot wrote: > In a Vista command prompt if I typed this: > > ??????? >>> python? somescript.py? filename > > Will sys.argv[1] return a valid path or just the filename? > If it just returns the filename, is there a simple way to get the path? > sys.argv contains exactly what you typed in on the command line. Nothing more, nothing less. It doesn't care whether what you typed is actually a filename or a plain number or some string, it just passes the commands as they are. You can use the os.path.abspath() function on your argument, that will probably do what you want. HTH, Hugo From lina.lastname at gmail.com Tue Nov 1 15:11:14 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 1 Nov 2011 22:11:14 +0800 Subject: [Tutor] improve the code Message-ID: Hi, The following code (luckily) partial achieved what I wanted, but I still have few questions: #!/usr/bin/python3 import os.path INFILEEXT=".txt" OUTFILEEXT=".new" DICTIONARYFILE="dictionary.pdb" orig_dictionary={} new_dictionary={} abetaABresidues={} def processonefiledata(infilename): with open(infilename,"r") as f: for line in f: parts=line.strip().split() orig_dictionary[parts[0]]=parts[1] def build_abetadictionary(infilename,olddict): with open(infilename,"r") as f: for line in f: parts=line.strip().split() if parts[0] != "85CUR" and (parts[0] not in abetaABresidues.keys()): abetaABresidues[parts[0]]=0 for residues, numbers in abetaABresidues.items(): if residues in olddict.keys(): new_dictionary[residues]=olddict[residues] else: new_dictionary[residues]=0 with open(base+OUTFILEEXT,"w") as f: for residues, numbers in new_dictionary.items(): print(residues,numbers,file=f) ## Q1: How can I sort the results, like the effect of | sort -g from something like: 84ALA 12 : : 83ILE 28 : : to : 83ILE 28 84ALA 12 : if __name__=="__main__": for filename in os.listdir("."): base, ext =os.path.splitext(filename) if ext == INFILEEXT: print(filename) processonefiledata(filename) build_abetadictionary(DICTIONARYFILE,orig_dictionary) Thanks for any comments or suggestions you may give. The relevant testing file are attached below links: https://docs.google.com/open?id=0B93SVRfpVVg3YjdhNjlmYTAtMTdkYy00ZTNjLThkOWEtOGMyNTM1YTBiMmU4 https://docs.google.com/open?id=0B93SVRfpVVg3OWNiZmUwODktMDU4Ny00ZDUyLWExYzQtM2E2ZmY5NGJhNzgz https://docs.google.com/open?id=0B93SVRfpVVg3MTBmNTM3M2UtYjdiMC00N2UwLWE1YTQtNmU3OGQzOGYwNDc3 Best regards, From ljmamoreira at gmail.com Tue Nov 1 15:19:26 2011 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Tue, 1 Nov 2011 14:19:26 +0000 Subject: [Tutor] A question about sys.argv In-Reply-To: References: Message-ID: <201111011419.26301.ljmamoreira@gmail.com> HiOn Tuesday, November 01, 2011 01:55:18 PM Joel Goldstick wrote: > On Tue, Nov 1, 2011 at 9:48 AM, Jefferson Ragot wrote: > > In a Vista command prompt if I typed this: > > >>> python somescript.py filename > > > > Will sys.argv[1] return a valid path or just the filename? > > If it just returns the filename, is there a simple way to get the path? > > Here's the contents of my somescript.py: --------------------------------- import sys for index,arg in enumerate(sys.argv): print index, arg ----------------------------------- Here is its output: mu:python$ python somescript.py match.py 0 somescript.py 1 match.py mu:python$ python somescript.py somescript.py stripaccents.py 0 somescript.py 1 somescript.py 2 stripaccents.py mu:python$ python somescript.py Hello, how do you do? 0 somescript.py 1 Hello, 2 how 3 do 4 you 5 do? mu:python$ python somescript.py /home/amoreira/public_html/index.php 0 somescript.py 1 /home/amoreira/public_html/index.php mu:python$ python somescript.py /unexistent/directory/unexistent_file.txt 0 somescript.py 1 /unexistent/directory/unexistent_file.txt So, sys.argv has nothing to do with files or paths, it just stores whatever you write in the command line. I don't have a vista system on wich to try things, but I'm pretty sure it's the same. > sysargv[1] returns the text following your script. > > You can find the current working directory with this: > > http://docs.python.org/library/os.html#os.getcwd No. sys.argv[1:] (note the colon) does return (not quite "return", since it's not a function call but ok) the text following your script. sys.argv[1] only "returns" the *first* word after your script (in the invocation command) Cheers Ze Amoreira -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Nov 1 15:23:39 2011 From: d at davea.name (Dave Angel) Date: Tue, 01 Nov 2011 10:23:39 -0400 Subject: [Tutor] A question about sys.argv In-Reply-To: References: Message-ID: <4EB000EB.7030604@davea.name> On 11/01/2011 10:05 AM, Hugo Arts wrote: > On Tue, Nov 1, 2011 at 2:48 PM, Jefferson Ragot wrote: >> In a Vista command prompt if I typed this: >> >> >>> python somescript.py filename >> >> Will sys.argv[1] return a valid path or just the filename? >> If it just returns the filename, is there a simple way to get the path? >> > sys.argv contains exactly what you typed in on the command line. > Nothing more, nothing less. It doesn't care whether what you typed is > actually a filename or a plain number or some string, it just passes > the commands as they are. > > You can use the os.path.abspath() function on your argument, that will > probably do what you want. > > HTH, > Hugo That's very helpful, but let me add a caveat: The operating system shell may modify that command line before handing it to Python. i don't believe that happens in Vista, however. Watch out for quotes and such, they may be eaten by the c runtime. And if you were on Linux, a filename with wildcards could get expanded into several argv[] items. -- DaveA From d at davea.name Tue Nov 1 15:28:03 2011 From: d at davea.name (Dave Angel) Date: Tue, 01 Nov 2011 10:28:03 -0400 Subject: [Tutor] A question about sys.argv In-Reply-To: <201111011419.26301.ljmamoreira@gmail.com> References: <201111011419.26301.ljmamoreira@gmail.com> Message-ID: <4EB001F3.4070006@davea.name> On 11/01/2011 10:19 AM, Jose Amoreira wrote: > HiOn Tuesday, November 01, 2011 01:55:18 PM Joel Goldstick wrote: >> On Tue, Nov 1, 2011 at 9:48 AM, Jefferson Ragot wrote: >>> In a Vista command prompt if I typed this: >>> >>> python somescript.py filename >>> >>> Will sys.argv[1] return a valid path or just the filename? >>> If it just returns the filename, is there a simple way to get the path? >>> > Here's the contents of my somescript.py: > --------------------------------- > import sys > for index,arg in enumerate(sys.argv): > print index, arg > ----------------------------------- > > Here is its output: > > mu:python$ python somescript.py match.py > 0 somescript.py > 1 match.py > > mu:python$ python somescript.py somescript.py stripaccents.py > 0 somescript.py > 1 somescript.py > 2 stripaccents.py > > mu:python$ python somescript.py Hello, how do you do? > 0 somescript.py > 1 Hello, > 2 how > 3 do > 4 you > 5 do? > > mu:python$ python somescript.py /home/amoreira/public_html/index.php > 0 somescript.py > 1 /home/amoreira/public_html/index.php > > mu:python$ python somescript.py /unexistent/directory/unexistent_file.txt > 0 somescript.py > 1 /unexistent/directory/unexistent_file.txt > > So, sys.argv has nothing to do with files or paths, it just stores whatever > you write in the command line. I don't have a vista system on wich to try > things, but I'm pretty sure it's the same. > >> sysargv[1] returns the text following your script. >> >> You can find the current working directory with this: >> >> http://docs.python.org/library/os.html#os.getcwd > No. sys.argv[1:] (note the colon) does return (not quite "return", since it's > not a function call but ok) the text following your script. sys.argv[1] only > "returns" the *first* word after your script (in the invocation command) > > Cheers > Ze Amoreira > More precisely, sys.argv[1:] yields a list whose items are the words on the command line. it does not reproduce the command line as a single string. -- DaveA From d at davea.name Tue Nov 1 15:33:30 2011 From: d at davea.name (Dave Angel) Date: Tue, 01 Nov 2011 10:33:30 -0400 Subject: [Tutor] improve the code In-Reply-To: References: Message-ID: <4EB0033A.9030500@davea.name> On 11/01/2011 10:11 AM, lina wrote: > Hi, > > The following code (luckily) partial achieved what I wanted, but I > still have few questions: > > > #!/usr/bin/python3 > > import os.path > > INFILEEXT=".txt" > OUTFILEEXT=".new" > DICTIONARYFILE="dictionary.pdb" > orig_dictionary={} > new_dictionary={} > abetaABresidues={} > > def processonefiledata(infilename): > with open(infilename,"r") as f: > for line in f: > parts=line.strip().split() > orig_dictionary[parts[0]]=parts[1] > > > def build_abetadictionary(infilename,olddict): > with open(infilename,"r") as f: > for line in f: > parts=line.strip().split() > if parts[0] != "85CUR" and (parts[0] not in abetaABresidues.keys()): > abetaABresidues[parts[0]]=0 > for residues, numbers in abetaABresidues.items(): > if residues in olddict.keys(): > new_dictionary[residues]=olddict[residues] > else: > new_dictionary[residues]=0 > with open(base+OUTFILEEXT,"w") as f: > for residues, numbers in new_dictionary.items(): > print(residues,numbers,file=f) > ## Q1: How can I sort the results, like the effect of | sort -g > > from something like: > 84ALA 12 > : > : > 83ILE 28 > : > : > > to > : > 83ILE 28 > 84ALA 12 > : Just use the sort() method of the list object. In particular, items() returns an unordered list, so it's ready to be sorted. for residues, numbers in new_dictionary.items().sort(): That will sort such that residues are in sorted order. -- DaveA From rinu.matrix at gmail.com Tue Nov 1 15:38:59 2011 From: rinu.matrix at gmail.com (Rinu Boney) Date: Tue, 1 Nov 2011 20:08:59 +0530 Subject: [Tutor] Tutor Digest, Vol 93, Issue 4 In-Reply-To: References: Message-ID: Alexander Etter , can u help me setup the emacs as python ide - like code refactoring and stuff? can i get to you by email? Thanks. > > Rinu, I use emacs. I use Python and C++. I'm also a university student. > Last semester I learned python 2.7 using IDLE, and continued with IDLE > while I searched for alternatives over the summer. I didn't find what I was > looking for. Say, just a few weeks ago I started my C++ course and switched > to emacs since the professor was using it. I tried it, read the easy to > understand documentation, and I am so productive, jubilant, and satisfied > with GNU Emacs. It's extensible beyond immediate comprehension; like a > sunflower it starts as a seed, sprouts leaves, etc; I'm elaborating the > infinite usability of emacs. > > There is a learning curve. One may find a learning curve with everything > in existence, whereas I repudiate one discouraging another for the > aforementioned. > Those who desire the power of emacs seek it. > Tim, do you use GNU Emacs? > >From what literature I've encountered including a wikipedia page I > believe there is a satiric starwars-like cold-war feud between users of vi > and emacs. > I'm neutral and won't judge an entity or patronize one for their use of > free will. > I'm happy. Forgive me if I appear too anything. > Good Day. > Alexander Etter > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Nov 1 16:11:01 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 1 Nov 2011 23:11:01 +0800 Subject: [Tutor] improve the code In-Reply-To: <4EB0033A.9030500@davea.name> References: <4EB0033A.9030500@davea.name> Message-ID: On Tue, Nov 1, 2011 at 10:33 PM, Dave Angel wrote: > On 11/01/2011 10:11 AM, lina wrote: >> >> Hi, >> >> The following code (luckily) partial achieved what I wanted, but I >> still have few questions: >> >> >> #!/usr/bin/python3 >> >> import os.path >> >> INFILEEXT=".txt" >> OUTFILEEXT=".new" >> DICTIONARYFILE="dictionary.pdb" >> orig_dictionary={} >> new_dictionary={} >> abetaABresidues={} >> >> def processonefiledata(infilename): >> ? ? with open(infilename,"r") as f: >> ? ? ? ? for line in f: >> ? ? ? ? ? ? parts=line.strip().split() >> ? ? ? ? ? ? orig_dictionary[parts[0]]=parts[1] >> >> >> def build_abetadictionary(infilename,olddict): >> ? ? with open(infilename,"r") as f: >> ? ? ? ? for line in f: >> ? ? ? ? ? ? parts=line.strip().split() >> ? ? ? ? ? ? if parts[0] != "85CUR" and (parts[0] not in >> abetaABresidues.keys()): >> ? ? ? ? ? ? ? ? abetaABresidues[parts[0]]=0 >> ? ? ? ? for residues, numbers in abetaABresidues.items(): >> ? ? ? ? ? ? if residues in olddict.keys(): >> ? ? ? ? ? ? ? ? new_dictionary[residues]=olddict[residues] >> ? ? ? ? ? ? else: >> ? ? ? ? ? ? ? ? new_dictionary[residues]=0 >> ? ? ? ? with open(base+OUTFILEEXT,"w") as f: >> ? ? ? ? ? ? for residues, numbers in new_dictionary.items(): >> ? ? ? ? ? ? ? ? print(residues,numbers,file=f) >> ## Q1: How can I sort the results, like the effect of | sort -g >> >> from something like: >> 84ALA 12 >> : >> : >> 83ILE 28 >> : >> : >> >> to >> : >> 83ILE 28 >> 84ALA 12 >> : > > Just use the sort() method of the list object. ?In particular, items() > returns an unordered list, so it's ready to be sorted. > > ? ? ? ? ? ?for residues, numbers in new_dictionary.items().sort(): > > That will sort such that residues are in sorted order. Thanks, but still something went wrong here, Traceback (most recent call last): File "fill-gap.py", line 41, in build_abetadictionary(DICTIONARYFILE,orig_dictionary) File "fill-gap.py", line 31, in build_abetadictionary for residues, numbers in new_dictionary.items().sort(): AttributeError: 'dict_items' object has no attribute 'sort' I have another concerns, is it possible to append the output file content as a sing one, such as a.new is A 1 B 3 b.new is A 3 B 5 I wish the final one like: A 1 3 B 3 5 I will think about it. Thanks, > -- > > DaveA > > From __peter__ at web.de Tue Nov 1 16:28:26 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Nov 2011 16:28:26 +0100 Subject: [Tutor] improve the code References: <4EB0033A.9030500@davea.name> Message-ID: lina wrote: > On Tue, Nov 1, 2011 at 10:33 PM, Dave Angel wrote: >> On 11/01/2011 10:11 AM, lina wrote: >> Just use the sort() method of the list object. In particular, items() >> returns an unordered list, so it's ready to be sorted. >> >> for residues, numbers in new_dictionary.items().sort(): >> >> That will sort such that residues are in sorted order. > > Thanks, but still something went wrong here, > > Traceback (most recent call last): > File "fill-gap.py", line 41, in > build_abetadictionary(DICTIONARYFILE,orig_dictionary) > File "fill-gap.py", line 31, in build_abetadictionary > for residues, numbers in new_dictionary.items().sort(): > AttributeError: 'dict_items' object has no attribute 'sort' Dave didn't realize that you are using Python 3 where items() no longer returns a list. You need to change new_dictionary.items().sort() to sorted(new_dictionary.items()) as sorted() will accept an arbitrary iterable. > I have another concerns, > is it possible to append the output file content as a sing one, > such as a.new is > A 1 > B 3 > > b.new is > A 3 > B 5 > > I wish the final one like: > > A 1 3 > B 3 5 > > I will think about it. Thanks, Sorry, I can't make sense of that. From mayoadams at gmail.com Tue Nov 1 16:34:07 2011 From: mayoadams at gmail.com (Mayo Adams) Date: Tue, 1 Nov 2011 11:34:07 -0400 Subject: [Tutor] beginner question Message-ID: When writing a simple for loop like so: for x in f where f is the name of a file object, how does Python "know" to interpret the variable x as a line of text, rather than,say, an individual character in the file? Does it automatically treat text files as sequences of lines? -- Mayo Adams 287 Erwin Rd. Chapel Hill, NC 27514 (919)-968-7889 mayoadams at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Nov 1 16:35:20 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 1 Nov 2011 23:35:20 +0800 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> Message-ID: On Tue, Nov 1, 2011 at 11:28 PM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >> On Tue, Nov 1, 2011 at 10:33 PM, Dave Angel wrote: >>> On 11/01/2011 10:11 AM, lina wrote: > >>> Just use the sort() method of the list object. ?In particular, items() >>> returns an unordered list, so it's ready to be sorted. >>> >>> for residues, numbers in new_dictionary.items().sort(): >>> >>> That will sort such that residues are in sorted order. >> >> Thanks, but still something went wrong here, >> >> Traceback (most recent call last): >> ? File "fill-gap.py", line 41, in >> ? ? build_abetadictionary(DICTIONARYFILE,orig_dictionary) >> ? File "fill-gap.py", line 31, in build_abetadictionary >> ? ? for residues, numbers in new_dictionary.items().sort(): >> AttributeError: 'dict_items' object has no attribute 'sort' > > Dave didn't realize that you are using Python 3 where items() no longer > returns a list. You need to change > > new_dictionary.items().sort() > > to > > sorted(new_dictionary.items()) Thanks, it works, but there is still a minor question, can I sort based on the general numerical value? namely not: : : 83ILE 1 84ALA 2 8SER 0 9GLY 0 : : rather 8 9 ...83 84, Thanks, > > as sorted() will accept an arbitrary iterable. > >> I have another concerns, >> is it possible to append the output file content as a sing one, >> such as a.new is >> A 1 >> B 3 >> >> b.new is >> A 3 >> B 5 >> >> I wish the final one like: >> >> A 1 3 >> B 3 5 >> >> I will think about it. Thanks, > > Sorry, I can't make sense of that. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at alchemy.com Tue Nov 1 16:41:23 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 01 Nov 2011 08:41:23 -0700 Subject: [Tutor] beginner question In-Reply-To: References: Message-ID: <4EB01323.1060402@alchemy.com> On 01-Nov-11 08:34, Mayo Adams wrote: > When writing a simple for loop like so: > > for x in f > > where f is the name of a file object, how does Python "know" to interpret > the variable x as a line of text, rather than,say, an individual > character in the file? Does it automatically > treat text files as sequences of lines? Every object defines what its behavior will be when asked to do something. In this case, file objects know that they are capable of iterating over a list of their contents by being used in a "for x in f" loop construct. The file object knows to respond to that by yielding up a line from the file for every iteration. You could, theoretically, write a variation of the file object class which iterated over characters, or logical blocks (records of some sort) within files, and so forth. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From d at davea.name Tue Nov 1 16:56:28 2011 From: d at davea.name (Dave Angel) Date: Tue, 01 Nov 2011 11:56:28 -0400 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> Message-ID: <4EB016AC.6010302@davea.name> On 11/01/2011 11:11 AM, lina wrote: > On Tue, Nov 1, 2011 at 10:33 PM, Dave Angel wrote: >> On 11/01/2011 10:11 AM, lina wrote: >>> >>> Hi, >>> >>> The following code (luckily) partial achieved what I wanted, but I >>> still have few questions: >>> >>> >>> #!/usr/bin/python3 >>> >>> import os.path >>> >>> INFILEEXT=".txt" >>> OUTFILEEXT=".new" >>> DICTIONARYFILE="dictionary.pdb" >>> orig_dictionary={} >>> new_dictionary={} >>> abetaABresidues={} >>> >>> def processonefiledata(infilename): >>> with open(infilename,"r") as f: >>> for line in f: >>> parts=line.strip().split() >>> orig_dictionary[parts[0]]=parts[1] >>> >>> >>> def build_abetadictionary(infilename,olddict): >>> with open(infilename,"r") as f: >>> for line in f: >>> parts=line.strip().split() >>> if parts[0] != "85CUR" and (parts[0] not in >>> abetaABresidues.keys()): >>> abetaABresidues[parts[0]]=0 >>> for residues, numbers in abetaABresidues.items(): >>> if residues in olddict.keys(): >>> new_dictionary[residues]=olddict[residues] >>> else: >>> new_dictionary[residues]=0 >>> with open(base+OUTFILEEXT,"w") as f: >>> for residues, numbers in new_dictionary.items(): >>> print(residues,numbers,file=f) >>> ## Q1: How can I sort the results, like the effect of | sort -g >>> >>> from something like: >>> 84ALA 12 >>> : >>> : >>> 83ILE 28 >>> : >>> : >>> >>> to >>> : >>> 83ILE 28 >>> 84ALA 12 >>> : >> >> Just use the sort() method of the list object. In particular, items() >> returns an unordered list, so it's ready to be sorted. >> >> for residues, numbers in new_dictionary.items().sort(): >> >> That will sort such that residues are in sorted order. > > Thanks, but still something went wrong here, > > Traceback (most recent call last): > File "fill-gap.py", line 41, in > build_abetadictionary(DICTIONARYFILE,orig_dictionary) > File "fill-gap.py", line 31, in build_abetadictionary > for residues, numbers in new_dictionary.items().sort(): > AttributeError: 'dict_items' object has no attribute 'sort' > Peter fixed that one. Actually my code wasn't even right in Python 2.x, as the sort() method sorts in place, and doesn't return a value. His code will work in both 2.x and 3.x, and is thus a much better answer. I frequently confuse the sort method and the sorted function, and judging from this list, so do many others. I'm pretty good at spotting that error if someone else makes it ;-) > I have another concerns, > is it possible to append the output file content as a sing one, > such as a.new is > A 1 > B 3 > > b.new is > A 3 > B 5 > > I wish the final one like: > > A 1 3 > B 3 5 > > I will think about it. Thanks, No idea how you came up with a.new or b.new. Or even what they contain. When you say a.new is "> A 1\n> B 3\n" I've got to guess you're misrepresenting it. But if you have two dictionaries that use EXACTLY the same keys, and you want to print out approximately that way, consider def printme(dict1, dict2): for key in sorted(dict1.keys()): print(key, dict1[key], dict2[key]) But notice that it won't print any value which has a key in dict2, but not in dict1. And it'll get an exception if there's a key in dict1 which is not in dict2. So what's your real problem? There are better ways to accomodate multiple sets of related data, and my answer doesn't help if there are 3, or 4, or 42 dictionaries. By the way, it's usually better to separate outputting the data from inputting. Factoring code into separate functions makes the code more flexible when requirements change. -- DaveA From d at davea.name Tue Nov 1 16:56:53 2011 From: d at davea.name (Dave Angel) Date: Tue, 01 Nov 2011 11:56:53 -0400 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> Message-ID: <4EB016C5.8010804@davea.name> On 11/01/2011 11:11 AM, lina wrote: > On Tue, Nov 1, 2011 at 10:33 PM, Dave Angel wrote: >> On 11/01/2011 10:11 AM, lina wrote: >>> >>> Hi, >>> >>> The following code (luckily) partial achieved what I wanted, but I >>> still have few questions: >>> >>> >>> #!/usr/bin/python3 >>> >>> import os.path >>> >>> INFILEEXT=".txt" >>> OUTFILEEXT=".new" >>> DICTIONARYFILE="dictionary.pdb" >>> orig_dictionary={} >>> new_dictionary={} >>> abetaABresidues={} >>> >>> def processonefiledata(infilename): >>> with open(infilename,"r") as f: >>> for line in f: >>> parts=line.strip().split() >>> orig_dictionary[parts[0]]=parts[1] >>> >>> >>> def build_abetadictionary(infilename,olddict): >>> with open(infilename,"r") as f: >>> for line in f: >>> parts=line.strip().split() >>> if parts[0] != "85CUR" and (parts[0] not in >>> abetaABresidues.keys()): >>> abetaABresidues[parts[0]]=0 >>> for residues, numbers in abetaABresidues.items(): >>> if residues in olddict.keys(): >>> new_dictionary[residues]=olddict[residues] >>> else: >>> new_dictionary[residues]=0 >>> with open(base+OUTFILEEXT,"w") as f: >>> for residues, numbers in new_dictionary.items(): >>> print(residues,numbers,file=f) >>> ## Q1: How can I sort the results, like the effect of | sort -g >>> >>> from something like: >>> 84ALA 12 >>> : >>> : >>> 83ILE 28 >>> : >>> : >>> >>> to >>> : >>> 83ILE 28 >>> 84ALA 12 >>> : >> >> Just use the sort() method of the list object. In particular, items() >> returns an unordered list, so it's ready to be sorted. >> >> for residues, numbers in new_dictionary.items().sort(): >> >> That will sort such that residues are in sorted order. > > Thanks, but still something went wrong here, > > Traceback (most recent call last): > File "fill-gap.py", line 41, in > build_abetadictionary(DICTIONARYFILE,orig_dictionary) > File "fill-gap.py", line 31, in build_abetadictionary > for residues, numbers in new_dictionary.items().sort(): > AttributeError: 'dict_items' object has no attribute 'sort' > Peter fixed that one. Actually my code wasn't even right in Python 2.x, as the sort() method sorts in place, and doesn't return a value. His code will work in both 2.x and 3.x, and is thus a much better answer. I frequently confuse the sort method and the sorted function, and judging from this list, so do many others. I'm pretty good at spotting that error if someone else makes it ;-) > I have another concerns, > is it possible to append the output file content as a sing one, > such as a.new is > A 1 > B 3 > > b.new is > A 3 > B 5 > > I wish the final one like: > > A 1 3 > B 3 5 > > I will think about it. Thanks, No idea how you came up with a.new or b.new. Or even what they contain. When you say a.new is "> A 1\n> B 3\n" I've got to guess you're misrepresenting it. But if you have two dictionaries that use EXACTLY the same keys, and you want to print out approximately that way, consider [untested] def printme(dict1, dict2): for key in sorted(dict1.keys()): print(key, dict1[key], dict2[key]) But notice that it won't print any value which has a key in dict2, but not in dict1. And it'll get an exception if there's a key in dict1 which is not in dict2. So what's your real problem? There are better ways to accomodate multiple sets of related data, and my answer doesn't help if there are 3, or 4, or 42 dictionaries. By the way, it's usually better to separate outputting the data from inputting. Factoring code into separate functions makes the code more flexible when requirements change. -- DaveA From __peter__ at web.de Tue Nov 1 17:06:22 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Nov 2011 17:06:22 +0100 Subject: [Tutor] beginner question References: <4EB01323.1060402@alchemy.com> Message-ID: Steve Willoughby wrote: > On 01-Nov-11 08:34, Mayo Adams wrote: >> When writing a simple for loop like so: >> >> for x in f >> >> where f is the name of a file object, how does Python "know" to interpret >> the variable x as a line of text, rather than,say, an individual >> character in the file? Does it automatically >> treat text files as sequences of lines? > > Every object defines what its behavior will be when asked to do > something. In this case, file objects know that they are capable of > iterating over a list of their contents by being used in a "for x in f" > loop construct. The file object knows to respond to that by yielding up > a line from the file for every iteration. > > You could, theoretically, write a variation of the file object class > which iterated over characters, or logical blocks (records of some sort) > within files, and so forth. Here's a simple example of a class derived from file that iterates over characters (bytes) instead of lines. Standard file: >>> for line in open("tmp.txt"): ... print repr(line) ... 'this\n' 'is but an\n' 'example\n' Modified file class: >>> class MyFile(file): ... def next(self): ... c = self.read(1) ... if not c: ... raise StopIteration ... return c ... >>> for c in MyFile("tmp.txt"): ... print repr(c) ... 't' 'h' 'i' 's' '\n' 'i' 's' ' ' 'b' 'u' 't' ' ' 'a' 'n' '\n' 'e' 'x' 'a' 'm' 'p' 'l' 'e' '\n' From __peter__ at web.de Tue Nov 1 17:14:28 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 01 Nov 2011 17:14:28 +0100 Subject: [Tutor] improve the code References: <4EB0033A.9030500@davea.name> Message-ID: lina wrote: >> sorted(new_dictionary.items()) > > Thanks, it works, but there is still a minor question, > > can I sort based on the general numerical value? > > namely not: > : > : > 83ILE 1 > 84ALA 2 > 8SER 0 > 9GLY 0 > : > : > > rather 8 9 ...83 84, > > Thanks, You need a custom key function for that one: >>> import re >>> def gnv(s): ... parts = re.split(r"(\d+)", s) ... parts[1::2] = map(int, parts[1::2]) ... return parts ... >>> items = [("83ILE", 1), ("84ALA", 2), ("8SER", 0), ("9GLY", 0)] >>> sorted(items, key=lambda pair: (gnv(pair[0]), pair[1])) [('8SER', 0), ('9GLY', 0), ('83ILE', 1), ('84ALA', 2)] From steve at pearwood.info Tue Nov 1 17:38:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Nov 2011 03:38:23 +1100 Subject: [Tutor] beginner question In-Reply-To: References: Message-ID: <4EB0207F.3090808@pearwood.info> Mayo Adams wrote: > When writing a simple for loop like so: > > for x in f > > where f is the name of a file object, how does Python "know" to interpret > the variable x as a line of text, rather than,say, an individual character > in the file? Does it automatically > treat text files as sequences of lines? Nice question! But the answer is a little bit complicated. The short answer is: File objects themselves are programmed to iterate line by line rather than character by character. That is a design choice made by the developers of Python, and it could have been different, but this choice was made because it is the most useful. The long answer requires explaining how for-loops work. When you say for x in THINGY: ... Python first asks THINGY to convert itself into a iterator. It does that by calling the special method THINGY.__iter__(), which is expected to return an iterator object (which may or may not be THINGY itself). If there is no __iter__ method, then Python falls back on an older sequence protocol which isn't relevant to files. If that too fails, then Python raises an error. So what's an iterator object? An iterator object must have a method called "next" (in Python 2), or "__next__" (in Python 3), which returns "the next item". The object is responsible for knowing what value to return each time next() is called. Python doesn't need to know anything about the internal details of the iterator, all it cares about is that when it calls THINGY.next() or THINGY.__next__(), the next item will be returned. All the "intelligence" is inside the object, not in Python. When there are no more items left to return, next() should raise StopIteration, which the for loop detects and treats as "loop is now finished" rather than as an error. So, the end result of all this is that Python doesn't care what THINGY is, so long as it obeys the protocol. So anyone can create new kinds of data that can be iterated over. In the case of files, somebody has already done that for you: files are built into Python. Built-in file objects, like you get from f = open("some file", "r"), obey the iterator protocol. We can run over it by hand, doing exactly what Python does in a for-loop, only less conveniently. Suppose we have a file containing "fee fi fo fum" split over four lines. Now let's iterate over it by hand. File objects are already iterators, so in Python 3 they have their own __next__ method and there's no need to call __iter__ first: >>> f = open('temp.txt', 'r') >>> f.__next__() 'fee\n' >>> f.__next__() 'fi\n' >>> f.__next__() 'fo\n' >>> f.__next__() 'fum\n' >>> f.__next__() Traceback (most recent call last): File "", line 1, in StopIteration So the file object itself keeps track of how much of the file has been read, and the Python interpreter doesn't need to know anything about files. It just needs to know that the file object is iterable. I already know this, so I took a short-cut, calling f.__next__() directly. But Python doesn't know that, it performs one extra step: it calls f.__iter__ to get an iterator object: >>> f.__iter__() <_io.TextIOWrapper name='temp.txt' encoding='UTF-8'> In this case, that iterator object is f itself, and now the Python interpreter goes on to call __next__() repeatedly. File objects are actually written in C for speed, but if they were written in pure Python, they might look something vaguely like this: class File(object): def __init__(self, name, mode='r'): self.name = name if mode == 'r': ... # open the file in Read mode elif mode == 'w': ... # open in Write mode else: # actually there are other modes too raise ValueError('bad mode') def __iter__(self): return self # I am my own iterator. def read(self, n=1): # Read n characters. All the hard work is in here. ... def readline(self): # Read a line, up to and including linefeed. buffer = [] c = self.read() buffer.append(c) while c != '' and c != '\n': c = self.read() # Read one more character. buffer.append(c) return ''.join(buffer) def __next__(self): line = self.readline() if line == '': # End of File raise StopIteration else: return line -- Steven From chare at labr.net Tue Nov 1 17:47:30 2011 From: chare at labr.net (Chris Hare) Date: Tue, 1 Nov 2011 11:47:30 -0500 Subject: [Tutor] login window using Tk Message-ID: I am working on a python Tk program which involves a login window and I am looking for some advice. Currently the code I have creates a window (Toplevel) where the login controls are and I am running that using a main loop for the window. The root window is hidden. The objective is that when the user ha successfully authenticated, the login window is closed or the main loop os exited and then the root window is shown and the main loop started for the actual application. Questions: 1. Is this the best way of doing this or is there a better way? 2. How do I exit the main loop when the user has authenticated? Thanks Chris Hare chare at labr.net http://www.labr.net Chris Hare chare at labr.net http://www.labr.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Nov 1 18:25:50 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 01 Nov 2011 10:25:50 -0700 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: <4EB02B9E.203@alchemy.com> On 01-Nov-11 09:47, Chris Hare wrote: > Questions: > 1. Is this the best way of doing this or is there a better way? > 2. How do I exit the main loop when the user has authenticated? Why stop the main loop and restart it? Typically you'd setup the app, and start the main loop running for the duration. Everything else is handled by the application's logic. For example, you'd display the login toplevel window, and when it's satisfied, it can trigger the functionality which creates (or displays the pre-created but hidden) application window and dismisses the login toplevel. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From joelmontes01 at gmail.com Tue Nov 1 18:38:04 2011 From: joelmontes01 at gmail.com (Joel M.) Date: Tue, 1 Nov 2011 13:38:04 -0400 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: I am also intrested in this topic. Chris were you thinking of using the window.hide() method? -Joel M On Nov 1, 2011 1:21 PM, "Chris Hare" wrote: > > I am working on a python Tk program which involves a login window and I am > looking for some advice. > > Currently the code I have creates a window (Toplevel) where the login > controls are and I am running that using a main loop for the window. The > root window is hidden. The objective is that when the user ha successfully > authenticated, the login window is closed or the main loop os exited and > then the root window is shown and the main loop started for the actual > application. > > Questions: > 1. Is this the best way of doing this or is there a better way? > 2. How do I exit the main loop when the user has authenticated? > > Thanks > > Chris Hare > chare at labr.net > http://www.labr.net > > > > Chris Hare > chare at labr.net > http://www.labr.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 alan.gauld at btinternet.com Tue Nov 1 18:53:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Nov 2011 17:53:02 +0000 Subject: [Tutor] Help In-Reply-To: References: <4EAF51A3.1090407@pearwood.info> Message-ID: On 01/11/11 04:10, Chris Kavanagh wrote: >> before. In other languages, ala C++, don't global variables have to be >> declared at the 'top' of the code?? No, that's just common usage. You can declare a variable anywhere in C/C++ provided it's before it is used. But that can lead to hard to read code (hunting for variable definitions to see their type, say). One place where it is common to define variables away from the top of yourcode is in a for loop: for (int i = 0;i<10;i++){ // pass } printf("%d\n", i); is valid C++(*) and defines the loop variable i inside the loop condition, then uses it after the loop. But apart from that its not that common. (*)Oops, I just tried it and got a obsolescence warning from g++ so that may have changed recently! But it worked ok with -fpermissive defined... HTH, Alan G. From alan.gauld at btinternet.com Tue Nov 1 19:02:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Nov 2011 18:02:59 +0000 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: On 01/11/11 16:47, Chris Hare wrote: > > I am working on a python Tk program which involves a login window and I > am looking for some advice. > > Currently the code I have creates a window (Toplevel) where the login > controls are and I am running that using a main loop for the window. Don't do this, it is frought with difficulties. Have a single mainloop for the program. Everything else should be driven by events. So you initialise your program including creating both the main and login windows. You show the login window. When the user logs in you validate the login and if not valid return control to the login window. If it is valid close the login window and show the main window. You then proceed to process all events for the main window. Trying to synchronize and control multiple mainloops in a GUI environment is incredibly hard to get right. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rhettnaxel at gmail.com Tue Nov 1 19:09:30 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Tue, 1 Nov 2011 14:09:30 -0400 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: On Nov 1, 2011, at 12:47, Chris Hare wrote: > > I am working on a python Tk program which involves a login window and I am looking for some advice. > > Currently the code I have creates a window (Toplevel) where the login controls are and I am running that using a main loop for the window. The root window is hidden. The objective is that when the user ha successfully authenticated, the login window is closed or the main loop os exited and then the root window is shown and the main loop started for the actual application. > > Questions: > 1. Is this the best way of doing this or is there a better way? > 2. How do I exit the main loop when the user has authenticated? > > Thanks > > Chris Hare > chare at labr.net > ____________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hi, hopefully a more experience hacker can provide clarity, but how secure does this login need to be? I dont much about python in DRAM but your login sounds like it could be easily hacked. Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 1 19:07:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Nov 2011 18:07:21 +0000 Subject: [Tutor] improve the code In-Reply-To: <4EB0033A.9030500@davea.name> References: <4EB0033A.9030500@davea.name> Message-ID: On 01/11/11 14:33, Dave Angel wrote: > Just use the sort() method of the list object. In particular, items() > returns an unordered list, so it's ready to be sorted. > > for residues, numbers in new_dictionary.items().sort(): I don't think this would work since sort works in place. You would need to use sorted() for residues, numbers in sorted(new_dictionary.items()): And sorted() also works on the Set type object that items returns... HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 1 19:14:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Nov 2011 18:14:20 +0000 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: On 01/11/11 09:46, Peter Otten wrote: > Alan Gauld wrote: >> Good point, although you could test the first character only... >> >> if choice[0].lower() not in ('prs'): # NB use a single string > > What Steven says, plus you may run into an IndexError if choice is the empty > string. If you absolutely want to test against a single string you have to > check the length first. Hmm, yeah, ok you win :-) Use the list form, even though it does involve a few more keystrokes and a lot more screen space. The extra typing to avoid the problems are not worth it! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 1 19:18:53 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Nov 2011 18:18:53 +0000 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: On 01/11/11 18:09, Alexander Etter wrote: > Hi, hopefully a more experience hacker can provide clarity, but how > secure does this login need to be? I dont much about python in DRAM but > your login sounds like it could be easily hacked. That depends entirely on how the user is authenticated. (assuming basic things like blanked password fields in the UI etc) For all we know the authentication could be against a central Single Sign On authentication server someplace. The OP didn't say. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tim at akwebsoft.com Tue Nov 1 19:23:51 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Tue, 1 Nov 2011 10:23:51 -0800 Subject: [Tutor] GNU Emacs and Python In-Reply-To: <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> References: <20111031193142.GF9335@akwebsoft.com> <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> Message-ID: <20111101182351.GB434@akwebsoft.com> * Alexander Etter [111101 03:36]: > Rinu, I use emacs. I use Python and C++. I'm also a university > student. Last semester I learned python 2.7 using IDLE, and > continued with IDLE while I searched for alternatives over the > summer. I didn't find what I was looking for. Say, just a few > weeks ago I started my C++ course and switched to emacs since the > professor was using it. I tried it, read the easy to understand > documentation, and I am so productive, jubilant, and satisfied > with GNU Emacs. It's extensible beyond immediate comprehension; > like a sunflower it starts as a seed, sprouts leaves, etc; I'm > elaborating the infinite usability of emacs. My niece graduated in Computer Science at UC Berkeley. I believe that emacs was the default programming editor in many of her classes. Elisp employs docstrings for subroutines, constants and variables. Emacs has a system of extracting those docstrings, which makes any 'plugins' self documenting. I'm sure that these features make emacs very attractive for team work, regardless of the environment whether academic or professional. > There is a learning curve. One may find a learning curve with > everything in existence, whereas I repudiate one discouraging > another for the aforementioned. Yup. Bigtime. > Those who desire the power of emacs seek it. > Tim, do you use GNU Emacs? I did use GNU emacs. I also used Xemacs, but prefered GNU Emacs. > From what literature I've encountered including a wikipedia page I > believe there is a satiric starwars-like cold-war feud between > users of vi and emacs. A feud for those who have nothing better to do. The acrimony around the 'fork' of Xemacs is greater and more serious. I believe that there are 'plugins' that can make emacs easier to use for the beginner. There are also a number of emacs 'Cheat Sheets' available, perhaps even with the distro. There is a physical Reference Card available here: http://shop.fsf.org/product/emacs-reference-cards-v-22/ I highly recommend it. cheers -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From chare at labr.net Tue Nov 1 19:57:14 2011 From: chare at labr.net (Chris Hare) Date: Tue, 1 Nov 2011 13:57:14 -0500 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: Here is a code snippet I have pulled out of the project. It is as bare bones as I can make it to get the point across. the problems I am having: 1. I would really like the window to be centered in the user's screen, but setting the geometry doesn't place it there. (that isn't included here) 2. When I click the Login button, nothing happens. I know I am missing something but it just isn't obvious what it is. 3. Finally, I would like to be able to hide the root window until the authentication is performed, but root.hide() gets me a getattr error. root.withdraw() works, but I can't get the root window back Thanks for your help. import sys from Tkinter import * import tkMessageBox import tkFont class Login: def __init__(self,parent): self.window = parent def show(instance): window = Toplevel() frame = Frame(window,bg=backColor) menubar = Menu(window) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Exit", command="sys.exit()") menubar.add_cascade(label="File", menu=filemenu) window.config(menu=menubar) programName = Label(frame, text = "test") list = Listbox(frame) list.insert( END,"test") label1 = Label(frame, text = "Organization", fg="Blue", bg=backColor) label2 = Label(frame, text = "Username", fg="Blue", bg=backColor) label3 = Label(frame, text = "Password", fg="Blue", bg=backColor) login_userid = Entry(frame,bg=outFocusColor) login_passwd = Entry(frame,bg=outFocusColor,show="*") login_userid.bind("", login_passwd.focus_set()) btnLogin = Button(frame, text="Login", command="print button pressed",highlightbackground=backColor) frame.title = "Login to application" list.focus_set() frame.grid() programName.grid(row=0, column=0,columnspan=5,sticky=W) label1.grid(row=1, column=0,columnspan=3, sticky=W) list.grid(row=1, column=6, columnspan=5, sticky=W) label2.grid(row=2, column=0,columnspan=3, sticky=W) login_userid.grid(row=2, column=6, columnspan=5,sticky=W) label3.grid(row=3, column=0,columnspan=3, sticky=W) login_passwd.grid(row=3, column=6, columnspan=5,sticky=W) btnLogin.grid(row=4, column=4, sticky=W) if __name__ == "__main__": backColor = "Gray" entryColor = "Cyan" okColor = "Green" warnColor = "Red" inFocusColor = "Cyan" outFocusColor = "White" root = Tk() root.withdraw() l = Login(root) l.show() root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Tue Nov 1 19:47:46 2011 From: chare at labr.net (Chris Hare) Date: Tue, 1 Nov 2011 13:47:46 -0500 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: Okay - that makes sense. The login window uses the show="*" for the password field and is authenticated against a database where the passwords are encrypted. I have this working in a text only environment, just struggling to get it right for the GUI Thanks Chris Hare chare at labr.net http://www.labr.net On Nov 1, 2011, at 1:02 PM, Alan Gauld wrote: > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Nov 1 20:54:20 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 1 Nov 2011 14:54:20 -0500 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: On Tue, Nov 1, 2011 at 1:57 PM, Chris Hare wrote: > Here is a code snippet I have pulled out of the project. It is as bare > bones as I can make it to get the point across. > > the problems I am having: > > 1. I would really like the window to be centered in the user's screen, > but setting the geometry doesn't place it there. (that isn't included here) > Take a look at the winfo_screenwidth/height methods. > 2. When I click the Login button, nothing happens. I know I am missing > something but it just isn't obvious what it is. > In your code you have "print button pressed" as the command - this is a string, and certainly wont do anything useful - you want to put a function here, e.g. command=self.login or something to that effect. You don't want parenthesis, or it will try to login as soon as python creates your button. > 3. Finally, I would like to be able to hide the root window until the > authentication is performed, but root.hide() gets me a getattr error. > root.withdraw() works, but I can't get the root window back > root.deiconify() is the method you're looking for here. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Nov 1 21:06:02 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 1 Nov 2011 15:06:02 -0500 Subject: [Tutor] GNU Emacs and Python In-Reply-To: <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> References: <20111031193142.GF9335@akwebsoft.com> <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> Message-ID: On Tue, Nov 1, 2011 at 6:31 AM, Alexander Etter wrote: > There is a learning curve. Yes, and for a graphical comparison of learning curves: http://jeetworks.org/files/images/emacs_learning_curves.png ;) > One may find a learning curve with everything in existence, whereas I > repudiate one discouraging another for the aforementioned. > Those who desire the power of emacs seek it. > Tim, do you use GNU Emacs? > >From what literature I've encountered including a wikipedia page I > believe there is a satiric starwars-like cold-war feud between users of vi > and emacs. > I'm neutral and won't judge an entity or patronize one for their use of > free will. I think these days a lot more people have become more pragmatic (or maybe I just hang around more levelheaded people now ;) but there are few better ways to start a flame war on IRC or USENET than ask the question which is better - vi or emacs. I "grew up" using vim, and I personally prefer modal editing - something about my brain prefers the clear distinction between writing my code and editing my code. For a while I tried emacs (mainly because I started learning Lisp, and I was working at a .NET shop and they had some horribly basic emacs shortcuts), and got lots of wrist cramps using chords for everything, even after I changed the caps key to control like it should be. My only recommendation is that you should learn emacs, vim, (or both, if you're crazy like I was ;) because you will be a *much* more productive programmer, simply because you can do things with both emacs and vim that you cannot do in more basic editors. Anyhow, just my two-bits. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Tue Nov 1 21:19:30 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Tue, 1 Nov 2011 16:19:30 -0400 Subject: [Tutor] GNU Emacs and Python In-Reply-To: References: <20111031193142.GF9335@akwebsoft.com> <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> Message-ID: <0A492B7C-2C76-44DE-9289-FCE015A18916@gmail.com> On Nov 1, 2011, at 16:06, Wayne Werner wrote: > On Tue, Nov 1, 2011 at 6:31 AM, Alexander Etter wrote: > There is a learning curve. > > Yes, and for a graphical comparison of learning curves: http://jeetworks.org/files/images/emacs_learning_curves.png > > ;) > > One may find a learning curve with everything in existence, whereas I repudiate one discouraging another for the aforementioned. > Those who desire the power of emacs seek it. > Tim, do you use GNU Emacs? > >From what literature I've encountered including a wikipedia page I believe there is a satiric starwars-like cold-war feud between users of vi and emacs. > I'm neutral and won't judge an entity or patronize one for their use of free will. > > I think these days a lot more people have become more pragmatic (or maybe I just hang around more levelheaded people now ;) but there are few better ways to start a flame war on IRC or USENET than ask the question which is better - vi or emacs. > > I "grew up" using vim, and I personally prefer modal editing - something about my brain prefers the clear distinction between writing my code and editing my code. For a while I tried emacs (mainly because I started learning Lisp, and I was working at a .NET shop and they had some horribly basic emacs shortcuts), and got lots of wrist cramps using chords for everything, even after I changed the caps key to control like it should be. > > My only recommendation is that you should learn emacs, vim, (or both, if you're crazy like I was ;) because you will be a *much* more productive programmer, simply because you can do things with both emacs and vim that you cannot do in more basic editors. > > Anyhow, just my two-bits. > -Wayne I like than .png image! It does appear vi biased though! Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Nov 1 21:24:23 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 01 Nov 2011 13:24:23 -0700 Subject: [Tutor] GNU Emacs and Python In-Reply-To: <0A492B7C-2C76-44DE-9289-FCE015A18916@gmail.com> References: <20111031193142.GF9335@akwebsoft.com> <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> <0A492B7C-2C76-44DE-9289-FCE015A18916@gmail.com> Message-ID: <4EB05577.3070500@alchemy.com> On 01-Nov-11 13:19, Alexander Etter wrote: > I like than .png image! It does appear vi biased though! Not quite, notice the initial steep climb. :) Yes, it's tongue-in-cheek, but feels about right, once you master vi (or emacs) you're able to be amazingly productive with complex operations involving text files. You think emacs is bad, though? Try TECO. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From waynejwerner at gmail.com Tue Nov 1 21:34:56 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 1 Nov 2011 15:34:56 -0500 Subject: [Tutor] GNU Emacs and Python In-Reply-To: <4EB05577.3070500@alchemy.com> References: <20111031193142.GF9335@akwebsoft.com> <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> <0A492B7C-2C76-44DE-9289-FCE015A18916@gmail.com> <4EB05577.3070500@alchemy.com> Message-ID: On Tue, Nov 1, 2011 at 3:24 PM, Steve Willoughby wrote: > On 01-Nov-11 13:19, Alexander Etter wrote: > >> I like than .png image! It does appear vi biased though! >> > > Not quite, notice the initial steep climb. :) Yes, it's tongue-in-cheek, > but feels about right, once you master vi (or emacs) you're > able to be amazingly productive with complex operations involving > text files. > > You think emacs is bad, though? Try TECO. Or better yet, ed: http://www.gnu.org/fun/jokes/ed.msg.html Interesting to note though, ed's manpage has got quite an update in the past few years to something that's actually useful (and there are several ed tutorials). I learned to use a little bit of ed, and it was fun to see where a lot of vim commands came from. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 1 21:49:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Nov 2011 20:49:14 +0000 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: On 01/11/11 18:57, Chris Hare wrote: > Here is a code snippet I have pulled out of the project. It is as bare > bones as I can make it to get the point across. I think you could have dropped a lot more to be honst - like all the menu code for a start... > 1. I would really like the window to be centered in the user's screen, > but setting the geometry doesn't place it there. (that isn't included here) OK, But thats a problem for another day. And some of these things are OS/UI dependent so you need to tell us what OS you are on. > 2. When I click the Login button, nothing happens. I know I am missing > something but it just isn't obvious what it is. You don't provide a command in the command parameter. You provide a string. When you click the button Python will try to call the string, which won't work. You should get an error message in the console -= how are you running this? Is it from a command prompt? If not you may not be seeing all the error messages Python is sending you... > 3. Finally, I would like to be able to hide the root window until the > authentication is performed, but root.hide() gets me a getattr error. > root.withdraw() works, but I can't get the root window back Really? You want the Login window to disappear even before you have authenticated the user? Thats very unusual behaviour. Usually the login window only goes away once you have been authenticated. > import sys > from Tkinter import * > import tkMessageBox > import tkFont > > class Login: > def __init__(self,parent): > self.window = parent > > def show(instance): > window = Toplevel() > frame = Frame(window,bg=backColor) > ... > label2 = Label(frame, text = "Username", fg="Blue", bg=backColor) > label3 = Label(frame, text = "Password", fg="Blue", bg=backColor) > login_userid = Entry(frame,bg=outFocusColor) > login_passwd = Entry(frame,bg=outFocusColor,show="*") > login_userid.bind("", login_passwd.focus_set()) > btnLogin = Button(frame, text="Login", command="print button > pressed",highlightbackground=backColor) you need to provide the name of a function to the command parameter - or use a lambda expression if its just a one liner > frame.grid() > label2.grid(row=2, column=0,columnspan=3, sticky=W) > login_userid.grid(row=2, column=6, columnspan=5,sticky=W) > label3.grid(row=3, column=0,columnspan=3, sticky=W) > login_passwd.grid(row=3, column=6, columnspan=5,sticky=W) > btnLogin.grid(row=4, column=4, sticky=W) > if __name__ == "__main__": > root = Tk() > root.withdraw() > l = Login(root) > l.show() > > root.mainloop() HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joelmontes01 at gmail.com Tue Nov 1 22:15:16 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Tue, 01 Nov 2011 17:15:16 -0400 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: <4EB06164.4070808@gmail.com> On 11/01/2011 02:18 PM, Alan Gauld wrote: > On 01/11/11 18:09, Alexander Etter wrote: > >> Hi, hopefully a more experience hacker can provide clarity, but how >> secure does this login need to be? I dont much about python in DRAM but >> your login sounds like it could be easily hacked. > > That depends entirely on how the user is authenticated. > (assuming basic things like blanked password fields in the UI etc) > > For all we know the authentication could be against a central > Single Sign On authentication server someplace. > The OP didn't say. > Question, once the code is compiled to a binary, can someone inject code to cause the hidden window to show, skipping the login altogether? -- -Joel M. From dadfar.narguess at gmail.com Tue Nov 1 22:47:02 2011 From: dadfar.narguess at gmail.com (Narguess Dadfar) Date: Tue, 1 Nov 2011 14:47:02 -0700 Subject: [Tutor] Problem in running script Message-ID: I want to prepare a script in python that updates the attributes of the crime incidents falling within the patrol zone. I have a point feature class of crime incidents and a polygon feature class of patrol zone. I used the getcount. method to take a count of the incidents in the current layer as the script goes the each loop, returns an integer value, and adds 1. The update cursor then updates the ?INCIDENT? field. The calculations to be performed in order to determine the incidents per square mile are: taking the Shape_area in meters and converting it to miles by dividing it by the constant provided and then dividing the number of incident by the converted shape area(in miles). The incidents per square mile will then be used to rank the priority of graffiti incidents in each zone. This was done with an? if/elif/else? statement where the first ?if? is the ?Top Priority? and the rest of the ranks follow as they meet the conditions in the consecutive statement. An update cursor is written into each of the ?if/elif/else? parts of the statement to update the ?PRIORITY ? field while the script is running through the current zone each time it loops.But I ran to problem. Please let me know what I should change. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Tue Nov 1 22:28:51 2011 From: chare at labr.net (Chris Hare) Date: Tue, 1 Nov 2011 16:28:51 -0500 Subject: [Tutor] login window using Tk In-Reply-To: References: Message-ID: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> Good feedback Alan, thanks. I wasn't using the root window to hold the login form, although I suppose I could. I guess where I am stuck is the login to control displaying the login window, and hiding it to display the actual application window once the user has authenticated. Chris Hare chare at labr.net http://www.labr.net On Nov 1, 2011, at 3:49 PM, Alan Gauld wrote: > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Nov 1 23:08:39 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 01 Nov 2011 15:08:39 -0700 Subject: [Tutor] GNU Emacs and Python In-Reply-To: <4EB05577.3070500@alchemy.com> References: <20111031193142.GF9335@akwebsoft.com> <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> <0A492B7C-2C76-44DE-9289-FCE015A18916@gmail.com> <4EB05577.3070500@alchemy.com> Message-ID: <4EB06DE7.6020004@alchemy.com> On 01-Nov-11 13:24, Steve Willoughby wrote: > On 01-Nov-11 13:19, Alexander Etter wrote: >> I like than .png image! It does appear vi biased though! > > Not quite, notice the initial steep climb. :) Yes, it's tongue-in-cheek, Oops, my mistake. If the y axis is productivity and x is time using the tool, then yes, a bit vi-biased. And that makes the Visual Studio graph make more sense as well :) -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From alan.gauld at btinternet.com Tue Nov 1 23:16:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 01 Nov 2011 22:16:47 +0000 Subject: [Tutor] GNU Emacs and Python In-Reply-To: <4EB05577.3070500@alchemy.com> References: <20111031193142.GF9335@akwebsoft.com> <12D71158-E761-470E-8A15-D0431B9FB59A@gmail.com> <0A492B7C-2C76-44DE-9289-FCE015A18916@gmail.com> <4EB05577.3070500@alchemy.com> Message-ID: On 01/11/11 20:24, Steve Willoughby wrote: > You think emacs is bad, though? Try TECO. Thats why Mr Stallman wrote emacs! :-) I once used Teco for a month, just for a dare. The best thing about it was taking a test file and typing your name into it, and seeing if you could guess what the final result would be... (For the uninitiated Teco was driven by characters on the keyboard, but it didn't bother to wait till you hit enter it would just do stuff as soon as it had enough data to operate on. A bit like vi in edit mode but without the : And every key seemed to do something!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Nov 1 23:30:55 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 02 Nov 2011 09:30:55 +1100 Subject: [Tutor] Problem in running script In-Reply-To: References: Message-ID: <4EB0731F.7080509@pearwood.info> Narguess Dadfar wrote: [...] > But I ran to problem. Please let me know what I should change. Would you like us to guess what problem you had? My guess is... you got a SyntaxError, because you forgot to put a closing bracket on the previous line. Am I close? -- Steven From hugo.yoshi at gmail.com Tue Nov 1 23:33:53 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 1 Nov 2011 23:33:53 +0100 Subject: [Tutor] Problem in running script In-Reply-To: References: Message-ID: On Tue, Nov 1, 2011 at 10:47 PM, Narguess Dadfar wrote: > I want to prepare a script in python that updates the attributes of the > crime incidents falling within the patrol zone. I have? a point feature > class of crime incidents and a polygon feature class of patrol zone. > > I used the getcount. method to take a count of the incidents in the current > layer as the script goes the each loop, returns an integer value, and adds > 1. The update cursor then updates the ?INCIDENT? field. The calculations to > be performed in order to determine the incidents per square mile are: taking > the Shape_area in meters and converting it to miles by dividing it by the > constant provided and then dividing the number of incident by the converted > shape area(in miles). The incidents per square mile will then be used to > rank the priority of graffiti incidents in each zone. This was done with an? > if/elif/else? statement where the first ?if? is the ?Top Priority? and the > rest of the ranks follow as they meet the conditions in the consecutive > statement. An update cursor is written into each of the ?if/elif/else? parts > of the statement to update the ?PRIORITY ? field while the script is running > through the current zone each time it loops.But I ran to problem. Please let > me know what I should change. > I'm sorry, but did you say you "ran to problem?" I don't mean to offend, but that's by far the worst problem description I've ever encountered. Please, include relevant code, errors given by the python interpreter, expected results, and make sure to let us know if you're doing a homework assignment. Also, consider reading "How to ask questions the smart way." It's a long read but you'll help yourself and everyone on the internet for the rest of your life by reading it: http://catb.org/~esr/faqs/smart-questions.html We can't magically access your computer and see your code. I have no idea what you should change if all I'm given is a paragraph of ambiguous, incomplete English description of your code and the words "I ran to problem." Hugo From waynejwerner at gmail.com Wed Nov 2 00:36:30 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 1 Nov 2011 18:36:30 -0500 Subject: [Tutor] login window using Tk In-Reply-To: <4EB06164.4070808@gmail.com> References: <4EB06164.4070808@gmail.com> Message-ID: On Nov 1, 2011 4:17 PM, "Joel Montes de Oca" wrote: > > On 11/01/2011 02:18 PM, Alan Gauld wrote: >> >> On 01/11/11 18:09, Alexander Etter wrote: >> >>> Hi, hopefully a more experience hacker can provide clarity, but how >>> secure does this login need to be? I dont much about python in DRAM but >>> your login sounds like it could be easily hacked. >> >> >> That depends entirely on how the user is authenticated. >> (assuming basic things like blanked password fields in the UI etc) >> >> For all we know the authentication could be against a central >> Single Sign On authentication server someplace. >> The OP didn't say. >> > > Question, once the code is compiled to a binary, can someone inject code to cause the hidden window to show, skipping the login altogether? Technically speaking, you could do that with /any/ program in any language. Good security is hard, and some things are just not worth spending that much time on. If good security were easy then photoshop wouldn't be pirated so much. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From joelmontes01 at gmail.com Wed Nov 2 00:40:52 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Tue, 01 Nov 2011 19:40:52 -0400 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall Message-ID: <4EB08384.8080508@gmail.com> I just discovered that it is a bad idea to complete uninstall Python 2.7 on Ubuntu 11.10. If you do, expect a lot of things not to work, mainly your system. haha I just reinstalled Python 2.7 and I hope things are not so bad now when I reboot. -- -Joel M. From design at justinstraube.com Wed Nov 2 01:16:24 2011 From: design at justinstraube.com (Justin Straube) Date: Tue, 01 Nov 2011 18:16:24 -0600 Subject: [Tutor] login window using Tk In-Reply-To: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> References: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> Message-ID: <4EB08BD8.80500@justinstraube.com> On 11/1/2011 3:28 PM, Chris Hare wrote: > > Good feedback Alan, thanks. > > I wasn't using the root window to hold the login form, although I > suppose I could. I guess where I am stuck is the login to control > displaying the login window, and hiding it to display the actual > application window once the user has authenticated. > > Chris Hare > chare at labr.net > http://www.labr.net Hi Chris, Have you looked into using a Frame to hold you input fields, and then using .destroy() to remove it upon successful login? This would allow you to not have to worry about hiding windows, as you can just reuse the same root window. Im just a hobbyist, so if there are reasons not to use this approach, I'd be interested in why. Justin From joelmontes01 at gmail.com Wed Nov 2 01:48:42 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Tue, 01 Nov 2011 20:48:42 -0400 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: References: <4EB08384.8080508@gmail.com> Message-ID: <4EB0936A.5050803@gmail.com> On Tue 01 Nov 2011 08:56:41 PM EDT, Max gmail wrote: > Heh, yeah. It's usually a bad idea to do stuff like that (I know a guy (Windows) who deleted his OS of his system). > > On Nov 1, 2011, at 7:40 PM, Joel Montes de Oca wrote: > >> I just discovered that it is a bad idea to complete uninstall Python 2.7 on Ubuntu 11.10. If you do, expect a lot of things not to work, mainly your system. haha >> >> I just reinstalled Python 2.7 and I hope things are not so bad now when I reboot. >> >> -- >> -Joel M. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > Yea, It wiped out GNOME and UNITY along with a few other applications. It wasn't a big deal tho, I just reinstalled ubuntu-desktop threw apt-get. :) -- -Joel M. From alan.gauld at btinternet.com Wed Nov 2 01:50:20 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Nov 2011 00:50:20 +0000 Subject: [Tutor] login window using Tk In-Reply-To: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> References: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> Message-ID: On 01/11/11 21:28, Chris Hare wrote: > > Good feedback Alan, thanks. > > I wasn't using the root window to hold the login form, although I > suppose I could. I guess where I am stuck is the login to control > displaying the login window, and hiding it to display the actual > application window once the user has authenticated. Thats what your command function does. So when the button is pressed your event handler authenticates the user details, if valid it closes the Login and shows the main window(which could be root...) In pseudocode: def doLogin(self): userid = idField.get() passwd = pwField.get() if self.validateUser(userid,passwd): root.show() self.window.hide() else: self.beep() # or whatever warning message you want self.logError("User authentication failed for " + userid) self.idField.clear() self.pwField.clear() Then in creating the button you pass that as the command handler: btnLogin = Button(self.window, text="Login", command=doLogin) Now, when the user hits the button the doLogin function will be called. If the login is ok we show the main window and hide the login dialog. If the entry is invalid we beep, clear the fields for a retry and log an error. We could also add a count so after, say, three attempts we close the app. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 2 01:54:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Nov 2011 00:54:17 +0000 Subject: [Tutor] login window using Tk In-Reply-To: <4EB06164.4070808@gmail.com> References: <4EB06164.4070808@gmail.com> Message-ID: On 01/11/11 21:15, Joel Montes de Oca wrote: > Question, once the code is compiled to a binary, can someone inject code > to cause the hidden window to show, skipping the login altogether? In general you don't compile Python to a binary, although tools exist that give a good approximation to that. But to inject code would need access to the source files and if you have been sensible with permissions etc that would require admin access to the machine... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 2 02:00:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Nov 2011 01:00:58 +0000 Subject: [Tutor] login window using Tk In-Reply-To: <4EB08BD8.80500@justinstraube.com> References: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> <4EB08BD8.80500@justinstraube.com> Message-ID: On 02/11/11 00:16, Justin Straube wrote: > Have you looked into using a Frame to hold you input fields, and then > using .destroy() to remove it upon successful login? This is a valid approach for some scenarios but its not the norm for login dialogs. They usually popup as fairly small standalone windows. But what you suggest could be done in a banner frame at the top or bottom of the main window, then either replaced or removed from the geometry. > Im just a hobbyist, so if there are reasons not to use this approach, > I'd be interested in why. Only user experience I think. Its usually best to make a GUI work like the other GUIs that the user is accustomed to. OTOH many web pages use the login style that you are suggesting so maybe the fashions will change for desktop apps too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From maxskywalker1 at gmail.com Wed Nov 2 01:56:41 2011 From: maxskywalker1 at gmail.com (Max gmail) Date: Tue, 01 Nov 2011 20:56:41 -0400 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: <4EB08384.8080508@gmail.com> References: <4EB08384.8080508@gmail.com> Message-ID: Heh, yeah. It's usually a bad idea to do stuff like that (I know a guy (Windows) who deleted his OS of his system). On Nov 1, 2011, at 7:40 PM, Joel Montes de Oca wrote: > I just discovered that it is a bad idea to complete uninstall Python 2.7 on Ubuntu 11.10. If you do, expect a lot of things not to work, mainly your system. haha > > I just reinstalled Python 2.7 and I hope things are not so bad now when I reboot. > > -- > -Joel M. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From chare at labr.net Wed Nov 2 06:05:16 2011 From: chare at labr.net (Chris Hare) Date: Wed, 2 Nov 2011 00:05:16 -0500 Subject: [Tutor] login window using Tk In-Reply-To: References: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> Message-ID: <3D22A08C-03F4-4B2C-9E5F-8E213F5DDE7C@labr.net> Thanks everyone for all of the help. I almost have this working. Everything is written in a class. I think I have that right, but that remains to be seen. :-) I can create the login window and get all of the controls on it. My function gets called to validate the information in the fields when the user presses the button. the function called however, can't seem to be able to get the items from the fields. I get the error like list.get(ACTIVE) doesn't have a function for get. (list was defined as a listbox.) the same is true for the other form fields. I opted to use the root window and implement a frame in it for the login. Once the login data has been validated, i can destroy the frame and reuse the window. This may or may not work ;-) I am a python newbie, biting off a big complicated chunk The class is defined: class Login: def __init__(self, parent): self.window = parent When I show the class instance, everything is displayed. My verification code, def verifyLogin(self): farmid = list.get(ACTIVE) userid = login_userid.get() login_passwd = login_passwd.get() gets called, but I get the error Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ return self.func(*args) File "z.py", line 229, in verifyLogin farmid = list.get(ACTIVE) AttributeError: type object 'list' has no attribute 'get' When the frame controls were added, list is defined as list = Listbox(frame) What have I got messed up? I have poked around the net but I can't find anything meaningful to me. Thanks again Chris Hare chare at labr.net http://www.labr.net On Nov 1, 2011, at 7:50 PM, Alan Gauld wrote: > On 01/11/11 21:28, Chris Hare wrote: >> >> Good feedback Alan, thanks. >> >> I wasn't using the root window to hold the login form, although I >> suppose I could. I guess where I am stuck is the login to control >> displaying the login window, and hiding it to display the actual >> application window once the user has authenticated. > > Thats what your command function does. So when the button is pressed your event handler authenticates the user details, if valid it closes the Login and shows the main window(which could be root...) > In pseudocode: > > > def doLogin(self): > userid = idField.get() > passwd = pwField.get() > if self.validateUser(userid,passwd): > root.show() > self.window.hide() > else: > self.beep() # or whatever warning message you want > self.logError("User authentication failed for " + userid) > self.idField.clear() > self.pwField.clear() > > Then in creating the button you pass that as the command handler: > > btnLogin = Button(self.window, text="Login", command=doLogin) > > Now, when the user hits the button the doLogin function will be called. > If the login is ok we show the main window and hide the login dialog. > If the entry is invalid we beep, clear the fields for a retry and log an error. We could also add a count so after, say, three attempts we close the app. > > HTH > -- > Alan G > 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 spawgi at gmail.com Wed Nov 2 07:26:54 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 2 Nov 2011 11:56:54 +0530 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: <4EB0936A.5050803@gmail.com> References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> Message-ID: Shouldn't this be treated as a bug then? As a user I should be allowed to uninstall the software I want to. Or you uninstalled other things by mistake? On Wed, Nov 2, 2011 at 6:18 AM, Joel Montes de Oca wrote: > On Tue 01 Nov 2011 08:56:41 PM EDT, Max gmail wrote: > >> Heh, yeah. It's usually a bad idea to do stuff like that (I know a guy >> (Windows) who deleted his OS of his system). >> >> On Nov 1, 2011, at 7:40 PM, Joel Montes de Oca wrote: >> >> I just discovered that it is a bad idea to complete uninstall Python 2.7 >>> on Ubuntu 11.10. If you do, expect a lot of things not to work, mainly your >>> system. haha >>> >>> I just reinstalled Python 2.7 and I hope things are not so bad now when >>> I reboot. >>> >>> -- >>> -Joel M. >>> >>> ______________________________**_________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/**mailman/listinfo/tutor >>> >> >> > Yea, It wiped out GNOME and UNITY along with a few other applications. It > wasn't a big deal tho, I just reinstalled ubuntu-desktop threw apt-get. :) > > > > -- > -Joel M. > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Nov 2 07:34:53 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 02 Nov 2011 08:34:53 +0200 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> Message-ID: <4EB0E48D.6030807@compuscan.co.za> On 2011/11/02 08:26 AM, spawgi at gmail.com wrote: > Shouldn't this be treated as a bug then? As a user I should be allowed > to uninstall the software I want to. > Or you uninstalled other things by mistake? > > On Wed, Nov 2, 2011 at 6:18 AM, Joel Montes de Oca > > wrote: > > On Tue 01 Nov 2011 08:56:41 PM EDT, Max gmail wrote: > > Heh, yeah. It's usually a bad idea to do stuff like that (I > know a guy (Windows) who deleted his OS of his system). > > On Nov 1, 2011, at 7:40 PM, Joel Montes de Oca wrote: > > I just discovered that it is a bad idea to complete > uninstall Python 2.7 on Ubuntu 11.10. If you do, expect a > lot of things not to work, mainly your system. haha > > I just reinstalled Python 2.7 and I hope things are not so > bad now when I reboot. > > -- > -Joel M. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > Yea, It wiped out GNOME and UNITY along with a few other > applications. It wasn't a big deal tho, I just reinstalled > ubuntu-desktop threw apt-get. :) > > > > -- > -Joel M. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > http://spawgi.wordpress.com > We can do it and do it better. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor It's not a bug. Ubuntu requires Python to be installed for a number of it's applications to run, and uninstalling Python will cause them to stop working. You could argue that then they should maintain a seperate install of Python to handle their core applications, but that would go against the grain of how package management is performed and how releases would need to be packaged etc. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Nov 2 07:42:52 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 2 Nov 2011 07:42:52 +0100 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> Message-ID: On Wed, Nov 2, 2011 at 7:26 AM, wrote: > Shouldn't this be treated as a bug then? As a user I should be allowed to > uninstall the software I want to. > Or you uninstalled other things by mistake? I don't think this is a bug. Python 2.7 is required software for both Gnome and Unity. Without it neither would be able to function. Since they are non-functional anyway, it makes some sense for apt to automatically remove them. I tried it on my virtual machine, and when you run `sudo apt-get remove python,` it does tell you that it's about to remove a metric ass-tonne of packages (including ubuntu-desktop and basically gnome-everything). That kind of output should warn most users that something isn't going according to plan, I'd think :S Hugo From chare at labr.net Wed Nov 2 07:29:04 2011 From: chare at labr.net (Chris Hare) Date: Wed, 2 Nov 2011 01:29:04 -0500 Subject: [Tutor] using separate py files for classes Message-ID: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> I would like to put each of my classes in separate files to make it easier to edit them and keep the various files as small as possible for editing purposes. I have come across a couple of problems: 1. I have to use import statements like "from file import class" instead of "import file" 2. I have to include all of the import statements for things not found in the class file Is this normal or am I doing something wrong? Thanks! Chris Hare chare at labr.net http://www.labr.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Nov 2 08:14:11 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 2 Nov 2011 08:14:11 +0100 Subject: [Tutor] using separate py files for classes In-Reply-To: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> References: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> Message-ID: On Wed, Nov 2, 2011 at 7:29 AM, Chris Hare wrote: > > I would like to put each of my classes in separate files to make it easier > to edit them and keep the various files as small as possible for editing > purposes. > I have come across a couple of problems: > 1. ?I have to use import statements like "from file import class" instead of > "import file" > 2. ?I have to include all of the import statements for things not found in > the class file > Is this normal or am I doing something wrong? > Thanks! > Chris Hare That's exactly how it's supposed to work, actually. One thing though, you can use "import file" rather than "from file import class." You then acces the class like "a = file.class()" Hugo From alan.gauld at btinternet.com Wed Nov 2 11:02:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Nov 2011 10:02:28 +0000 Subject: [Tutor] login window using Tk In-Reply-To: <3D22A08C-03F4-4B2C-9E5F-8E213F5DDE7C@labr.net> References: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> <3D22A08C-03F4-4B2C-9E5F-8E213F5DDE7C@labr.net> Message-ID: On 02/11/11 05:05, Chris Hare wrote: > def verifyLogin(self): > farmid = list.get(ACTIVE) > userid = login_userid.get() > login_passwd = login_passwd.get() > > gets called, but I get the error > > Exception in Tkinter callback > farmid = list.get(ACTIVE) > AttributeError: type object 'list' has no attribute 'get' > > When the frame controls were added, list is defined as > > list = Listbox(frame) names defined in functions are local to that function. They can't be seen outside of the function. So... To be able to access the controls you need to add themas instance attributes to your class. so you should use self.list = Listbox(.... and farmid = self.list.get(.... What you are seeing is Python looking for something called list in your methods namespace and not finding it. It can't see anything global either so it picks up the built-in list() type. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 2 11:07:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Nov 2011 10:07:31 +0000 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> Message-ID: On 02/11/11 06:26, spawgi at gmail.com wrote: > Shouldn't this be treated as a bug then? As a user I should be allowed > to uninstall the software I want to. You can, it just breaks stuff that depends on it. Just as if you uninstalled Java all your Java applications would break (eg Eclipse, Freemind etc) The same is true on any OS. If you remove Java (or .Net) from a Windows box the same kind of bad thing happens. The systems administrator (you for a single user PC!) is expected to know and understand the critical components and their dependencies. Basically if you didn't explicitly install it, don't remove it. (And even if you did explicitly install it there may still be dependencies from things you installed later!) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 2 11:13:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Nov 2011 10:13:21 +0000 Subject: [Tutor] using separate py files for classes In-Reply-To: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> References: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> Message-ID: On 02/11/11 06:29, Chris Hare wrote: > > I would like to put each of my classes in separate files to make it > easier to edit them and keep the various files as small as possible for > editing purposes. > > I have come across a couple of problems: > > 1. I have to use import statements like "from file import class" instead > of "import file" > 2. I have to include all of the import statements for things not found > in the class file > > Is this normal or am I doing something wrong? That's exactly what happens. Its actually a good thing since it makes your code more reliable, although it may not seem like it while you are developing it! :-) You might like to bend your rules of one class per file though. Its usually more convenient to have groups of related classes in a single file. Especially if there is a dependency involved since otherwise the using class code winds up with lots of module references in it. And if you come to distribute the code you have to always distribute both files not one. And its easy to forget the dependency exists over time... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mehgcap at gmail.com Wed Nov 2 14:15:43 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 2 Nov 2011 09:15:43 -0400 Subject: [Tutor] assign all parameters of __init__ to class variables? Message-ID: Hi all, I have a class which takes a large number of optional arguments for its __init__. Instead of going through every single one and assigning it to "self.[name]", is there some quick way to take all the parameters of the constructor and assign them all to self.[name] in one step? -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From chare at labr.net Wed Nov 2 14:03:01 2011 From: chare at labr.net (Chris Hare) Date: Wed, 2 Nov 2011 08:03:01 -0500 Subject: [Tutor] using separate py files for classes In-Reply-To: References: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> Message-ID: <5BE9CCD7-3C57-4554-B59B-8629F4354ADC@labr.net> Ahhhh?. thanks Hugo!! Chris Hare chare at labr.net http://www.labr.net On Nov 2, 2011, at 2:14 AM, Hugo Arts wrote: > On Wed, Nov 2, 2011 at 7:29 AM, Chris Hare wrote: >> >> I would like to put each of my classes in separate files to make it easier >> to edit them and keep the various files as small as possible for editing >> purposes. >> I have come across a couple of problems: >> 1. I have to use import statements like "from file import class" instead of >> "import file" >> 2. I have to include all of the import statements for things not found in >> the class file >> Is this normal or am I doing something wrong? >> Thanks! >> Chris Hare > > That's exactly how it's supposed to work, actually. One thing though, > you can use "import file" rather than "from file import class." You > then acces the class like "a = file.class()" > > Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Nov 2 14:37:47 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 02 Nov 2011 14:37:47 +0100 Subject: [Tutor] assign all parameters of __init__ to class variables? References: Message-ID: Alex Hall wrote: > I have a class which takes a large number of optional arguments for > its __init__. Instead of going through every single one and assigning > it to "self.[name]", is there some quick way to take all the > parameters of the constructor and assign them all to self.[name] in > one step? You could use something like http://code.activestate.com/recipes/280381-clean-up-__init__-methods-that- contain-only-attrib/ or def __init__(self, **kw): self.__dict__.update(kw) but I'd recommend against it. I've never used the recipe myself and instead try hard to keep argument list sizes managable. From cwitts at compuscan.co.za Wed Nov 2 14:44:49 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 02 Nov 2011 15:44:49 +0200 Subject: [Tutor] assign all parameters of __init__ to class variables? In-Reply-To: References: Message-ID: <4EB14951.6040602@compuscan.co.za> On 2011/11/02 03:15 PM, Alex Hall wrote: > Hi all, > I have a class which takes a large number of optional arguments for > its __init__. Instead of going through every single one and assigning > it to "self.[name]", is there some quick way to take all the > parameters of the constructor and assign them all to self.[name] in > one step? > class Test(object): def __init__(self, param1, param2, param2, **kw): self.__dict__.update(locals()) self.__dict__.update(kw) I do prefer assignment by hand, just feels nicer especially when looking at it in the future. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Wed Nov 2 14:57:25 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 2 Nov 2011 09:57:25 -0400 Subject: [Tutor] assign all parameters of __init__ to class variables? In-Reply-To: <4EB14951.6040602@compuscan.co.za> References: <4EB14951.6040602@compuscan.co.za> Message-ID: Thanks to both of you, that will work. I can see the argument for assigning everything manually, but I have each parameter on its own line with a comment to explain what it does, and I know I want all parameters to be class-level for every instantiation, so saying "self.[varName]=[varName]" twenty times seems like a waste of time and space. On 11/2/11, Christian Witts wrote: > On 2011/11/02 03:15 PM, Alex Hall wrote: >> Hi all, >> I have a class which takes a large number of optional arguments for >> its __init__. Instead of going through every single one and assigning >> it to "self.[name]", is there some quick way to take all the >> parameters of the constructor and assign them all to self.[name] in >> one step? >> > class Test(object): > def __init__(self, param1, param2, param2, **kw): > self.__dict__.update(locals()) > self.__dict__.update(kw) > > I do prefer assignment by hand, just feels nicer especially when looking > at it in the future. > -- > > Christian Witts > Python Developer > > // > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From joelmontes01 at gmail.com Wed Nov 2 15:10:09 2011 From: joelmontes01 at gmail.com (Joel Montes de Oca) Date: Wed, 02 Nov 2011 10:10:09 -0400 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> Message-ID: <4EB14F41.2050500@gmail.com> On 11/02/2011 02:26 AM, spawgi at gmail.com wrote: > Shouldn't this be treated as a bug then? As a user I should be allowed > to uninstall the software I want to. > Or you uninstalled other things by mistake? > > On Wed, Nov 2, 2011 at 6:18 AM, Joel Montes de Oca > > wrote: > > On Tue 01 Nov 2011 08:56:41 PM EDT, Max gmail wrote: > > Heh, yeah. It's usually a bad idea to do stuff like that (I > know a guy (Windows) who deleted his OS of his system). > > On Nov 1, 2011, at 7:40 PM, Joel Montes de Oca wrote: > > I just discovered that it is a bad idea to complete > uninstall Python 2.7 on Ubuntu 11.10. If you do, expect a > lot of things not to work, mainly your system. haha > > I just reinstalled Python 2.7 and I hope things are not so > bad now when I reboot. > > -- > -Joel M. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > Yea, It wiped out GNOME and UNITY along with a few other > applications. It wasn't a big deal tho, I just reinstalled > ubuntu-desktop threw apt-get. :) > > > > -- > -Joel M. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > http://spawgi.wordpress.com > We can do it and do it better. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Spawgi, Like a few people have mentioned before, this isn't a bug. Unity and GNOME rely on Python 2.7 to work, which is fine. When I uninstalled Python2.7 GNOME and Unity didn't have a way to run their py files, which results in a broken environment. The package manager was smart enough to list everything that was going to be uninstalled since they rely on Python. So instead of leaving broken systems on my computer, it uninstalled all the packages that would had been broken, including Unity and GNOME. I just want to add one thing that hasn't been mentioned yet. The only bug was the one called Joel M, which failed to read the uninstall list until later when I noticed my environments were being uninstalled. haha! Synaptic, the package manager I was using, listed everything that was going to be uninstalled but I didn't read it. I didn't realize how many system tools used python until later. Live and learn. It wasn't a big deal. All I had to do was reinstall Python2.7 and reboot. Of course, after the reboot, I didn't have an environment to log into. So I pressed Ctr + Alt + F1 to get into tty1 and then ran sudo apt-get install ubuntu-desktop. That took care of the missing environment. Then I restarted with sudo shutdown -r now. I didn't really need to do that since I think restarting X was enough but I restarted anyhow. As far as the comments about Ubuntu 11.10 being buggy. I don't think it's Ubuntu 11.10 that is buggy, I think it's Unity that is a bit buggy. I use Unity and sometimes applications do crash or fail to open when you click on their icons... Like I said, I think it's an issue with Unity but I can't say for sure since I haven't used another environment since I installed Ubuntu 11.10. -- -Joel M. From chare at labr.net Wed Nov 2 15:10:26 2011 From: chare at labr.net (Chris Hare) Date: Wed, 2 Nov 2011 09:10:26 -0500 Subject: [Tutor] login window using Tk In-Reply-To: References: <21D9C7A6-296F-4899-84F8-642519DDADB5@labr.net> <3D22A08C-03F4-4B2C-9E5F-8E213F5DDE7C@labr.net> Message-ID: <73312AAC-1401-4E3A-B211-8C109A1BC52C@labr.net> Just thought I would drop y'all a note and say thank you for your help on this. I have the login code working. I learned a bunch from you guys. Thanks! Chris Hare chare at labr.net http://www.labr.net On Nov 2, 2011, at 5:02 AM, Alan Gauld wrote: > On 02/11/11 05:05, Chris Hare wrote: > >> def verifyLogin(self): >> farmid = list.get(ACTIVE) >> userid = login_userid.get() >> login_passwd = login_passwd.get() >> >> gets called, but I get the error >> >> Exception in Tkinter callback >> farmid = list.get(ACTIVE) >> AttributeError: type object 'list' has no attribute 'get' >> >> When the frame controls were added, list is defined as >> >> list = Listbox(frame) > > names defined in functions are local to that function. They can't be seen outside of the function. So... > To be able to access the controls you need to add themas instance attributes to your class. so you should use > > self.list = Listbox(.... > > and > > farmid = self.list.get(.... > > What you are seeing is Python looking for something called list in your methods namespace and not finding it. It can't see anything global either so it picks up the built-in list() type. > > HTH > > -- > Alan G > 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 spawgi at gmail.com Wed Nov 2 16:02:31 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Wed, 2 Nov 2011 20:32:31 +0530 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: <4EB14F41.2050500@gmail.com> References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> <4EB14F41.2050500@gmail.com> Message-ID: I use OS X / Windows and I have not noticed any dependency issues. So I was not aware about the same with respect to Ubuntu. I am glad that I learnt something from this discussion. Regards, Sumod On Wed, Nov 2, 2011 at 7:40 PM, Joel Montes de Oca wrote: > On 11/02/2011 02:26 AM, spawgi at gmail.com wrote: > >> Shouldn't this be treated as a bug then? As a user I should be allowed to >> uninstall the software I want to. >> Or you uninstalled other things by mistake? >> >> On Wed, Nov 2, 2011 at 6:18 AM, Joel Montes de Oca < >> joelmontes01 at gmail.com > wrote: >> >> On Tue 01 Nov 2011 08:56:41 PM EDT, Max gmail wrote: >> >> Heh, yeah. It's usually a bad idea to do stuff like that (I >> know a guy (Windows) who deleted his OS of his system). >> >> On Nov 1, 2011, at 7:40 PM, Joel Montes de Oca wrote: >> >> I just discovered that it is a bad idea to complete >> uninstall Python 2.7 on Ubuntu 11.10. If you do, expect a >> lot of things not to work, mainly your system. haha >> >> I just reinstalled Python 2.7 and I hope things are not so >> bad now when I reboot. >> >> -- -Joel M. >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> >> >> >> Yea, It wiped out GNOME and UNITY along with a few other >> applications. It wasn't a big deal tho, I just reinstalled >> ubuntu-desktop threw apt-get. :) >> >> >> >> -- -Joel M. >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> >> >> >> >> -- >> http://spawgi.wordpress.com >> We can do it and do it better. >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > Spawgi, > > Like a few people have mentioned before, this isn't a bug. Unity and GNOME > rely on Python 2.7 to work, which is fine. When I uninstalled Python2.7 > GNOME and Unity didn't have a way to run their py files, which results in a > broken environment. The package manager was smart enough to list everything > that was going to be uninstalled since they rely on Python. So instead of > leaving broken systems on my computer, it uninstalled all the packages that > would had been broken, including Unity and GNOME. > > I just want to add one thing that hasn't been mentioned yet. The only bug > was the one called Joel M, which failed to read the uninstall list until > later when I noticed my environments were being uninstalled. haha! > > Synaptic, the package manager I was using, listed everything that was > going to be uninstalled but I didn't read it. I didn't realize how many > system tools used python until later. Live and learn. > > It wasn't a big deal. All I had to do was reinstall Python2.7 and reboot. > Of course, after the reboot, I didn't have an environment to log into. So I > pressed Ctr + Alt + F1 to get into tty1 and then ran sudo apt-get install > ubuntu-desktop. That took care of the missing environment. Then I restarted > with sudo shutdown -r now. I didn't really need to do that since I think > restarting X was enough but I restarted anyhow. > > As far as the comments about Ubuntu 11.10 being buggy. I don't think it's > Ubuntu 11.10 that is buggy, I think it's Unity that is a bit buggy. I use > Unity and sometimes applications do crash or fail to open when you click on > their icons... Like I said, I think it's an issue with Unity but I can't > say for sure since I haven't used another environment since I installed > Ubuntu 11.10. > > > -- > -Joel M. > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Wed Nov 2 16:49:43 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 2 Nov 2011 23:49:43 +0800 Subject: [Tutor] improve the code In-Reply-To: <4EB016C5.8010804@davea.name> References: <4EB0033A.9030500@davea.name> <4EB016C5.8010804@davea.name> Message-ID: On Tue, Nov 1, 2011 at 11:56 PM, Dave Angel wrote: > On 11/01/2011 11:11 AM, lina wrote: >> >> On Tue, Nov 1, 2011 at 10:33 PM, Dave Angel ?wrote: >>> >>> On 11/01/2011 10:11 AM, lina wrote: >>>> >>>> Hi, >>>> >>>> The following code (luckily) partial achieved what I wanted, but I >>>> still have few questions: >>>> >>>> >>>> #!/usr/bin/python3 >>>> >>>> import os.path >>>> >>>> INFILEEXT=".txt" >>>> OUTFILEEXT=".new" >>>> DICTIONARYFILE="dictionary.pdb" >>>> orig_dictionary={} >>>> new_dictionary={} >>>> abetaABresidues={} >>>> >>>> def processonefiledata(infilename): >>>> ? ? with open(infilename,"r") as f: >>>> ? ? ? ? for line in f: >>>> ? ? ? ? ? ? parts=line.strip().split() >>>> ? ? ? ? ? ? orig_dictionary[parts[0]]=parts[1] >>>> >>>> >>>> def build_abetadictionary(infilename,olddict): >>>> ? ? with open(infilename,"r") as f: >>>> ? ? ? ? for line in f: >>>> ? ? ? ? ? ? parts=line.strip().split() >>>> ? ? ? ? ? ? if parts[0] != "85CUR" and (parts[0] not in >>>> abetaABresidues.keys()): >>>> ? ? ? ? ? ? ? ? abetaABresidues[parts[0]]=0 >>>> ? ? ? ? for residues, numbers in abetaABresidues.items(): >>>> ? ? ? ? ? ? if residues in olddict.keys(): >>>> ? ? ? ? ? ? ? ? new_dictionary[residues]=olddict[residues] >>>> ? ? ? ? ? ? else: >>>> ? ? ? ? ? ? ? ? new_dictionary[residues]=0 >>>> ? ? ? ? with open(base+OUTFILEEXT,"w") as f: >>>> ? ? ? ? ? ? for residues, numbers in new_dictionary.items(): >>>> ? ? ? ? ? ? ? ? print(residues,numbers,file=f) >>>> ## Q1: How can I sort the results, like the effect of | sort -g >>>> >>>> from something like: >>>> 84ALA 12 >>>> : >>>> : >>>> 83ILE 28 >>>> : >>>> : >>>> >>>> to >>>> : >>>> 83ILE 28 >>>> 84ALA 12 >>>> : >>> >>> Just use the sort() method of the list object. ?In particular, items() >>> returns an unordered list, so it's ready to be sorted. >>> >>> ? ? ? ? ? ?for residues, numbers in new_dictionary.items().sort(): >>> >>> That will sort such that residues are in sorted order. >> >> Thanks, but still something went wrong here, >> >> Traceback (most recent call last): >> ? File "fill-gap.py", line 41, in >> ? ? build_abetadictionary(DICTIONARYFILE,orig_dictionary) >> ? File "fill-gap.py", line 31, in build_abetadictionary >> ? ? for residues, numbers in new_dictionary.items().sort(): >> AttributeError: 'dict_items' object has no attribute 'sort' >> > > Peter fixed that one. ?Actually my code wasn't even right in Python 2.x, as > the sort() method sorts in place, and doesn't return a value. ?His code will > work in both 2.x and 3.x, and is thus a much better answer. ?I frequently > confuse the sort method and the sorted function, and judging from this list, > so do many others. ?I'm pretty good at spotting that error if someone else > makes it ;-) > > >> I have another concerns, >> is it possible to append the output file content as a sing one, >> such as a.new is >> A 1 >> B 3 >> >> b.new is >> A 3 >> B 5 >> >> I wish the final one like: >> >> A 1 3 >> B 3 5 >> >> I will think about it. Thanks, > > > No idea how you came up with a.new or b.new. ?Or even what they contain. > ?When you say a.new is "> A 1\n> B 3\n" ?I've got to guess you're > misrepresenting it. > > But if you have two dictionaries that use EXACTLY the same keys, and you > want to print out approximately that way, consider [untested] > > def ?printme(dict1, dict2): > ? ?for key in sorted(dict1.keys()): > ? ? ? ? print(key, dict1[key], dict2[key]) > > > But notice that it won't print any value which has a key in dict2, but not > in dict1. ?And it'll get an exception if there's a key in dict1 which is not > in dict2. Thanks, they shared the same keys. ^_^ > > So what's your real problem? ?There are better ways to accomodate multiple > sets of related data, and my answer doesn't help if there are 3, or 4, or 42 > dictionaries. > > By the way, it's usually better to separate outputting the data from > inputting. ?Factoring code into separate functions makes the code more > flexible when requirements change. > > -- > > DaveA > From lina.lastname at gmail.com Wed Nov 2 16:54:05 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 2 Nov 2011 23:54:05 +0800 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> <4EB016C5.8010804@davea.name> Message-ID: Regard the sorted(), I still have a question, how to sort something like >>> results ['1A', '10B', '2C', '3D'] >>> sorted(results) ['10B', '1A', '2C', '3D'] as [ '1A', '2C', '3D','10B'] Thanks, mainly based on their digital value. From ramit.prasad at jpmorgan.com Wed Nov 2 16:39:02 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 2 Nov 2011 11:39:02 -0400 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> <4EB14F41.2050500@gmail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF4619AC@EMARC112VS01.exchad.jpmchase.net> >I use OS X / Windows and I have not noticed any dependency issues. So I was not aware about the same with respect to Ubuntu. I am glad that I learnt something from this discussion. I might be wrong, but Ubuntu itself is not dependent on Python. You can probably run a minimalist headless Ubuntu server without Python. Especially since the OP seemed able to login to his machine without it. X/Desktop requires it. I am not sure if OS X needs it, but I do know it comes with Python installed. Joel M: Pretty much the only things that require restarting (from my experience with Debian) are kernel changes and hardware changes. You just had to restart X / login manager (gdm). Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From d at davea.name Wed Nov 2 17:58:02 2011 From: d at davea.name (Dave Angel) Date: Wed, 02 Nov 2011 12:58:02 -0400 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> <4EB016C5.8010804@davea.name> Message-ID: <4EB1769A.5000903@davea.name> On 11/02/2011 11:54 AM, lina wrote: > > > Regard the sorted(), > > I still have a question, > > how to sort something like > > >>>> results > ['1A', '10B', '2C', '3D'] >>>> sorted(results) > ['10B', '1A', '2C', '3D'] > > as [ '1A', '2C', '3D','10B'] > > Thanks, > > mainly based on their digital value. > Peter answered essentially that question, in his message on this thread, yesterday with timestamp 12:14 Essence of the answer is you can supply a key=myfunc argument to sorted(). Then it's up to you what you put in that function. It sounds like you want to convert any leading digits to an int, and return that int. Once you have that function, you just use it as a keyword argument to sorted(), something like: something = sorted(mylist, key=myfunc) Why don't you have a go at trying to write such a function? The exact details depend on what you're trying to sort, a list of strings, or a list of tuples whose two values are strings. (or a iterable representing one of those). -- DaveA From steve at pearwood.info Wed Nov 2 20:29:13 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Nov 2011 06:29:13 +1100 Subject: [Tutor] using separate py files for classes In-Reply-To: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> References: <85F232D8-FDAC-4AF4-80C1-58E4E42F5DA5@labr.net> Message-ID: <4EB19A09.1010001@pearwood.info> Chris Hare wrote: > I would like to put each of my classes in separate files to make it > easier to edit them and keep the various files as small as possible > for editing purposes. Perhaps you need a better editor, one with a class browser that lets you see the layout of your classes and the relationship between them. Or perhaps you need smaller classes. I've seen people writing Java in Python, and their code ends up anything from 2 to 10 times bigger (and consequently slower) than necessary. "One class per file" is very much a Java thing. But without actually seeing your classes, I can't judge. > I have come across a couple of problems: > > 1. I have to use import statements like "from file import class" > instead of "import file" 2. I have to include all of the import > statements for things not found in the class file > > Is this normal or am I doing something wrong? You may be doing something wrong. In Python, it is not normal to force the rule "one class per module". You wouldn't say "one method per class", would you? In Python, the normal rules are: * put a group of related methods into a class * put a group of related classes and functions into a module * put a group of related modules into a package Python is designed to work that way, and it is quite unusual to design your library or application to be different. -- Steven From steve at pearwood.info Wed Nov 2 20:35:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 03 Nov 2011 06:35:37 +1100 Subject: [Tutor] assign all parameters of __init__ to class variables? In-Reply-To: References: Message-ID: <4EB19B89.4020204@pearwood.info> Alex Hall wrote: > Hi all, > I have a class which takes a large number of optional arguments for > its __init__. Instead of going through every single one and assigning > it to "self.[name]", is there some quick way to take all the > parameters of the constructor and assign them all to self.[name] in > one step? If your class takes more than, oh, half a dozen parameters, that is often Nature's way of telling you the class is badly designed and tries to do Too Many Things. But if you really need to: def __init__(self, **kwargs): self.__dict__.update(kwargs) Add your own error checking :) Also, the above doesn't work with __slots__. -- Steven From alan.gauld at btinternet.com Wed Nov 2 21:22:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 02 Nov 2011 20:22:33 +0000 Subject: [Tutor] improve the code In-Reply-To: <4EB1769A.5000903@davea.name> References: <4EB0033A.9030500@davea.name> <4EB016C5.8010804@davea.name> <4EB1769A.5000903@davea.name> Message-ID: On 02/11/11 16:58, Dave Angel wrote: >>>>> sorted(results) >> ['10B', '1A', '2C', '3D'] >> >> as [ '1A', '2C', '3D','10B'] > Essence of the answer is you can supply a key=myfunc argument to > sorted(). Then it's up to you what you put in that function. It sounds > like you want to convert any leading digits to an int, and return that int. Or in your case it might be hex in which case convert the whole string using int and specify the base to be 16... >>> int('1A',16) 26 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From joelmontes01 at gmail.com Wed Nov 2 22:25:13 2011 From: joelmontes01 at gmail.com (Joel M.) Date: Wed, 2 Nov 2011 17:25:13 -0400 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF4619AC@EMARC112VS01.exchad.jpmchase.net> References: <4EB08384.8080508@gmail.com> <4EB0936A.5050803@gmail.com> <4EB14F41.2050500@gmail.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF4619AC@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Wed, Nov 2, 2011 at 11:39 AM, Prasad, Ramit wrote: > >I use OS X / Windows and I have not noticed any dependency issues. So I > was not aware about the same with respect to Ubuntu. I am glad that I > learnt something from this discussion. > > I might be wrong, but Ubuntu itself is not dependent on Python. You can > probably run a minimalist headless Ubuntu server without Python. Especially > since the OP seemed able to login to his machine without it. X/Desktop > requires it. > > Ubuntu is not dependent on Python, but the environments (Unity, GNOME, etc) will brake if you don't have Python. > I am not sure if OS X needs it, but I do know it comes with Python > installed. > > Joel M: Pretty much the only things that require restarting (from my > experience with Debian) are kernel changes and hardware changes. You just > had to restart X / login manager (gdm). > > Yea I know, but I restarted anyhow. > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > 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 Wed Nov 2 23:00:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 3 Nov 2011 09:00:36 +1100 Subject: [Tutor] assign all parameters of __init__ to class variables? In-Reply-To: References: <4EB14951.6040602@compuscan.co.za> Message-ID: <201111030900.36857.steve@pearwood.info> On Thu, 3 Nov 2011 12:57:25 am Alex Hall wrote: > Thanks to both of you, that will work. I can see the argument for > assigning everything manually, but I have each parameter on its own > line with a comment to explain what it does, and I know I want all > parameters to be class-level for every instantiation, so saying > "self.[varName]=[varName]" twenty times seems like a waste of time > and space. Wait, you you want the parameters to be *class level*, that is, shared by all instances? But you want them to be set each time you instantiate an instance? That's fairly unusual. Normally people want each instance to get its own instance-level attributes. In Python, one way of doing this would be: class K(object): a = 1 # class-level shared attribute defined once only def __init__(self, b): self.__class__.b = b # Set the shared class-level attribute And in action: >>> ham = K(23) >>> ham.a, ham.b (1, 23) >>> eggs = K(42) >>> ham.a, ham.b (1, 42) Notice that you must assign the attribute on the class object itself, not the instance. So if you have a bunch of parameters, rather than updating the instance dictionary, you have to update the class dictionary. (This makes error checking and parameter validation even more important, because you can screw your class up by overwriting methods if you pass the wrong parameter name.) But assuming you like living dangerously, or you trust the caller not to be stupid: class K(object): a = 1 def __init__(self, **kwargs): self.__class__.__dict__.update(kwargs) But having done that, it still won't really work the way you expect (or at least the way I *think* you will expect). The problem is that the instance still has its own dict, so when the caller assigns to an attribute: instance = K(b=2, c=3) instance.d = 4 b and c become class-level, as requested, but d is instance-level and any other instances will not share that value. The best way to ensure all instances share the same attributes is with the Borg design pattern: http://code.activestate.com/recipes/66531/ (Also known as Monostate, or the poorly-named "stateless proxy".) The above recipe is for classic classes, which no longer exist in Python 3; for a new-style class version, see the comment by Alex Naanou on that page. The other alleged new-style Borgs actually implement Singletons. But if the difference between a Singleton and a Borg matters to you, you're probably up to no good. -- Steven D'Aprano From steve at pearwood.info Thu Nov 3 00:18:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 3 Nov 2011 10:18:28 +1100 Subject: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall In-Reply-To: References: <4EB08384.8080508@gmail.com> <4EB14F41.2050500@gmail.com> Message-ID: <201111031018.28823.steve@pearwood.info> On Thu, 3 Nov 2011 02:02:31 am spawgi at gmail.com wrote: > I use OS X / Windows and I have not noticed any dependency issues. > So I was not aware about the same with respect to Ubuntu. I am glad > that I learnt something from this discussion. In general, you should never uninstall any package you didn't install yourself unless you know what the consequences will be. -- Steven D'Aprano From steve at pearwood.info Thu Nov 3 00:46:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 3 Nov 2011 10:46:04 +1100 Subject: [Tutor] login window using Tk In-Reply-To: References: <4EB06164.4070808@gmail.com> Message-ID: <201111031046.04901.steve@pearwood.info> On Wed, 2 Nov 2011 11:54:17 am Alan Gauld wrote: > On 01/11/11 21:15, Joel Montes de Oca wrote: > > Question, once the code is compiled to a binary, can someone > > inject code to cause the hidden window to show, skipping the > > login altogether? > > In general you don't compile Python to a binary, although tools > exist that give a good approximation to that. But to inject code > would need access to the source files A sufficiently clever byte-code hacker can insert byte-code straight into the .pyc file, given write permission to the files -- or an exploit that allows writing to a file. Since people can modify machine code executables (that's how most viruses work, and cracked applications), modifying byte-code is unlikely to give them any trouble. Here's a proof-of-concept virus that does exactly that: http://www.symantec.com/connect/blogs/python-has-venom -- Steven D'Aprano From mehgcap at gmail.com Thu Nov 3 03:53:58 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 2 Nov 2011 22:53:58 -0400 Subject: [Tutor] assign all parameters of __init__ to class variables? In-Reply-To: <201111030900.36857.steve@pearwood.info> References: <4EB14951.6040602@compuscan.co.za> <201111030900.36857.steve@pearwood.info> Message-ID: I'm sorry, I misspoke (well, mistyped anyway). I have a couple class-level variables, but most of them are set in the __init__ so that every instance gets a fresh copy of them. Thatnks for the responses. On 11/2/11, Steven D'Aprano wrote: > On Thu, 3 Nov 2011 12:57:25 am Alex Hall wrote: >> Thanks to both of you, that will work. I can see the argument for >> assigning everything manually, but I have each parameter on its own >> line with a comment to explain what it does, and I know I want all >> parameters to be class-level for every instantiation, so saying >> "self.[varName]=[varName]" twenty times seems like a waste of time >> and space. > > Wait, you you want the parameters to be *class level*, that is, shared > by all instances? But you want them to be set each time you > instantiate an instance? That's fairly unusual. Normally people want > each instance to get its own instance-level attributes. > > In Python, one way of doing this would be: > > class K(object): > a = 1 # class-level shared attribute defined once only > def __init__(self, b): > self.__class__.b = b # Set the shared class-level attribute > > > And in action: > >>>> ham = K(23) >>>> ham.a, ham.b > (1, 23) >>>> eggs = K(42) >>>> ham.a, ham.b > (1, 42) > > > Notice that you must assign the attribute on the class object itself, > not the instance. So if you have a bunch of parameters, rather than > updating the instance dictionary, you have to update the class > dictionary. (This makes error checking and parameter validation even > more important, because you can screw your class up by overwriting > methods if you pass the wrong parameter name.) > > But assuming you like living dangerously, or you trust the caller not > to be stupid: > > class K(object): > a = 1 > def __init__(self, **kwargs): > self.__class__.__dict__.update(kwargs) > > But having done that, it still won't really work the way you expect > (or at least the way I *think* you will expect). The problem is that > the instance still has its own dict, so when the caller assigns to an > attribute: > > instance = K(b=2, c=3) > instance.d = 4 > > b and c become class-level, as requested, but d is instance-level and > any other instances will not share that value. > > The best way to ensure all instances share the same attributes is with > the Borg design pattern: > > http://code.activestate.com/recipes/66531/ > > (Also known as Monostate, or the poorly-named "stateless proxy".) > > The above recipe is for classic classes, which no longer exist in > Python 3; for a new-style class version, see the comment by Alex > Naanou on that page. The other alleged new-style Borgs actually > implement Singletons. > > But if the difference between a Singleton and a Borg matters to you, > you're probably up to no good. > > > > -- > Steven D'Aprano > _______________________________________________ > 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 chare at labr.net Thu Nov 3 05:46:57 2011 From: chare at labr.net (Chris Hare) Date: Wed, 2 Nov 2011 23:46:57 -0500 Subject: [Tutor] binding problem Message-ID: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> I have a Listbox defined self.list = Listbox(self.frame) What I want to do is when the user either single clicks, double clicks, presses tab or return, move the focus to the specified field self.list.bind("", self.login_userid.focus_set()) self.list.bind("", self.login_userid.focus_set()) self.list.bind("", self.login_userid.focus_set()) self.list.bind("", self.login_userid.focus_set()) If I can get this working, I should be able to get the other bindings to work. Chris Hare chare at labr.net http://www.labr.net From CHARE at labr.net Thu Nov 3 05:39:04 2011 From: CHARE at labr.net (Chris Hare) Date: Wed, 2 Nov 2011 23:39:04 -0500 Subject: [Tutor] frame destroy problem Message-ID: I have the following code: def listUsers(self): self.frameBottom = Frame(self.base, bd=0, bg=backColor) self.frameBottom.grid(row=1, column=0,sticky=N+E+S+W) self.text = Text(self.frameBottom) self.text.grid(row=1, column=6, columnspan=5, sticky=E) self.text.insert(END, security.listUsers()) self.btnClose = Button(self.frameBottom, text="Close", command=self.closeFrameBottom,highlightbackground=backColor) self.btnClose.grid(row=2, column=4) def closeFrameBottom(self): self.franeBottom.destroy() When the listUsers method is called, everything is displayed correctly. However, when the btnClose is pressed, I get an error Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ return self.func(*args) File "z.py", line 454, in closeFrameBottom self.franeBottom.destroy() AttributeError: Display instance has no attribute 'franeBottom' What have I got wrong? the objective is to use the bottom part opt the window over and over again. Chris Hare chare at labr.net http://www.labr.net From mnickey at gmail.com Thu Nov 3 06:12:58 2011 From: mnickey at gmail.com (Mike Nickey) Date: Wed, 2 Nov 2011 22:12:58 -0700 Subject: [Tutor] Creating Android Apps w/ Python Message-ID: I'm currently taking a class on Android Development. The instructor says that the code needed has to be done through Java. Isn't there any way to create these same apps with Python? I read on the Android Dev site that MonkeyRunner can assist but does anyone else have any experience on how well this works or if Python is only really supported through MonkeyRunner? I am hoping that there is a Python ADK that will allow creation of apps with Python but I haven't seen one and wanted to see what you know is out there. Thanks in advance. -- ~MEN From delegbede at dudupay.com Thu Nov 3 06:58:30 2011 From: delegbede at dudupay.com (Dipo Elegbede) Date: Thu, 3 Nov 2011 06:58:30 +0100 Subject: [Tutor] frame destroy problem In-Reply-To: References: Message-ID: There is nothing called franeButton it should be frameButton. I guess its a typo. On 3 Nov 2011 05:52, "Chris Hare" wrote: > > I have the following code: > > def listUsers(self): > self.frameBottom = Frame(self.base, bd=0, bg=backColor) > self.frameBottom.grid(row=1, column=0,sticky=N+E+S+W) > self.text = Text(self.frameBottom) > self.text.grid(row=1, column=6, columnspan=5, sticky=E) > self.text.insert(END, security.listUsers()) > self.btnClose = Button(self.frameBottom, text="Close", > command=self.closeFrameBottom,highlightbackground=backColor) > self.btnClose.grid(row=2, column=4) > > def closeFrameBottom(self): > self.franeBottom.destroy() > > When the listUsers method is called, everything is displayed correctly. > However, when the btnClose is pressed, I get an error > > Exception in Tkinter callback > Traceback (most recent call last): > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", > line 1410, in __call__ > return self.func(*args) > File "z.py", line 454, in closeFrameBottom > self.franeBottom.destroy() > AttributeError: Display instance has no attribute 'franeBottom' > > What have I got wrong? the objective is to use the bottom part opt the > window over and over again. > > Chris Hare > chare at labr.net > http://www.labr.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 sander.sweers at gmail.com Thu Nov 3 09:00:03 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 03 Nov 2011 09:00:03 +0100 Subject: [Tutor] Creating Android Apps w/ Python In-Reply-To: References: Message-ID: <1320307203.16852.5.camel@Nokia-N900> On Thu,? 3 Nov 2011, 06:12:58 CET, Mike Nickey wrote: > I am hoping that there is a Python ADK that will allow creation of > apps with Python but I haven't seen one and wanted to see what you know is out there. Linux journal has an article on this [1]. I have no experience in this but it looks a good start. Greets sander [1] http://www.linuxjournal.com/article/10940 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 3 09:23:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 03 Nov 2011 08:23:43 +0000 Subject: [Tutor] binding problem In-Reply-To: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> Message-ID: On 03/11/11 04:46, Chris Hare wrote: > > I have a Listbox defined > > self.list = Listbox(self.frame) > > What I want to do is when the user either single clicks, double clicks, presses tab or return, move the focus to the specified field > > self.list.bind("", self.login_userid.focus_set()) Don't call the function, just pass its name: self.list.bind("", self.login_userid.focus_set) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chare at labr.net Thu Nov 3 13:58:27 2011 From: chare at labr.net (Chris Hare) Date: Thu, 3 Nov 2011 07:58:27 -0500 Subject: [Tutor] frame destroy problem In-Reply-To: References: Message-ID: Dang it - sure is a typo! Thanks! Chris Hare chare at labr.net http://www.labr.net On Nov 3, 2011, at 12:58 AM, Dipo Elegbede wrote: > There is nothing called franeButton it should be frameButton. I guess its a typo. > > On 3 Nov 2011 05:52, "Chris Hare" wrote: > > > I have the following code: > > def listUsers(self): > self.frameBottom = Frame(self.base, bd=0, bg=backColor) > self.frameBottom.grid(row=1, column=0,sticky=N+E+S+W) > self.text = Text(self.frameBottom) > self.text.grid(row=1, column=6, columnspan=5, sticky=E) > self.text.insert(END, security.listUsers()) > self.btnClose = Button(self.frameBottom, text="Close", command=self.closeFrameBottom,highlightbackground=backColor) > self.btnClose.grid(row=2, column=4) > > def closeFrameBottom(self): > self.franeBottom.destroy() > > When the listUsers method is called, everything is displayed correctly. However, when the btnClose is pressed, I get an error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > File "z.py", line 454, in closeFrameBottom > self.franeBottom.destroy() > AttributeError: Display instance has no attribute 'franeBottom' > > What have I got wrong? the objective is to use the bottom part opt the window over and over again. > > Chris Hare > chare at labr.net > http://www.labr.net > > _______________________________________________ > 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 chare at labr.net Thu Nov 3 14:01:41 2011 From: chare at labr.net (Chris Hare) Date: Thu, 3 Nov 2011 08:01:41 -0500 Subject: [Tutor] binding problem In-Reply-To: References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> Message-ID: <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> Thanks for the advice. When I do that, I get this error Exception in Tkinter callback Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ return self.func(*args) TypeError: focus_set() takes exactly 1 argument (2 given) In situations like this where the function isn't one you wrote, how to you debug these? Chris Hare chare at labr.net http://www.labr.net On Nov 3, 2011, at 3:23 AM, Alan Gauld wrote: > On 03/11/11 04:46, Chris Hare wrote: >> >> I have a Listbox defined >> >> self.list = Listbox(self.frame) >> >> What I want to do is when the user either single clicks, double clicks, presses tab or return, move the focus to the specified field >> >> self.list.bind("", self.login_userid.focus_set()) > > Don't call the function, just pass its name: > > self.list.bind("", self.login_userid.focus_set) > > HTH, > > -- > Alan G > 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 d at davea.name Thu Nov 3 14:26:52 2011 From: d at davea.name (Dave Angel) Date: Thu, 03 Nov 2011 09:26:52 -0400 Subject: [Tutor] binding problem In-Reply-To: <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> Message-ID: <4EB2969C.2080202@davea.name> (You mistakenly top-posted, so now in order to keep this next message in order, I have to delete the out of order history) On 11/03/2011 09:01 AM, Chris Hare wrote: > Thanks for the advice. When I do that, I get this error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > TypeError: focus_set() takes exactly 1 argument (2 given) > > In situations like this where the function isn't one you wrote, how to you debug these? > Lots of clues in that traceback. We can deduce that you're probably on a non-Windows machine, and that you're using CPython 2.7, and Tkinter. Those all would have been good information to include in your initial posting. The other thing it tells you is that your function object focus_set() takes one too few arguments. So, the question is how do you determine the types of each of those arguments? First, write a non-class simple function, that takes two arguments, and prints the type() and repr() for each. Use that function object in the self.list.bind function call, and see what it prints when it runs. Then, once you know the types, you have a clue as to what the real function should look like. We don't know what your self and login_user classes look like, so I was trying to eliminate them as contenders for the confusion. The other thing would be to read the tkinter docs, or find example code. But since I've never used tkinter, I can't give you advice along those lines. -- DaveA From __peter__ at web.de Thu Nov 3 15:08:31 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 03 Nov 2011 15:08:31 +0100 Subject: [Tutor] binding problem References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> Message-ID: Chris Hare wrote: > Thanks for the advice. When I do that, I get this error > > Exception in Tkinter callback > Traceback (most recent call last): > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib- tk/Tkinter.py", > line 1410, in __call__ > return self.func(*args) > TypeError: focus_set() takes exactly 1 argument (2 given) > > In situations like this where the function isn't one you wrote, how to you > debug these? In this case there is not much to debug, the error message says it all: you have an extra argument that the focus_set() method doesn't accept. The simplest way to drop that argument is to wrap the method call: def focus_set(event): # only one arg because it's a function, not a method self.login_userid.focus_set() self.list.bind("", focus_set) This is sometimes written with a lambda function self.list.bind("", lambda event: self.login_userid.focus_set()) If you wanted to learn more about that extra argument you could temporarily replace the callback with something that can give you the necessary information, e. g. def inspect_args(*args): for arg in args: print arg print vars(arg) self.list.bind("", inspect_args) As a last resort and an idea almost too revolutionary to mention in public, you could read some tutorial or documentation... From chare at labr.net Thu Nov 3 15:41:18 2011 From: chare at labr.net (Chris Hare) Date: Thu, 3 Nov 2011 09:41:18 -0500 Subject: [Tutor] binding problem In-Reply-To: References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> Message-ID: Thanks Peter. Actually, I have read a bunch of stuff and looked at example code. The problem in this case is I am using a defined method - focus_set(), which is part of Tkinter and isn't part of my code. since I am using it in the manner in which I have seen other examples, I am confused about why it is complaining about 2 arguments, when I am not passing any. Although, I think I know what the problem is now. Thanks for your help anyway. Chris Hare chare at labr.net http://www.labr.net On Nov 3, 2011, at 9:08 AM, Peter Otten wrote: > Chris Hare wrote: > >> Thanks for the advice. When I do that, I get this error >> >> Exception in Tkinter callback >> Traceback (most recent call last): >> File >> > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib- > tk/Tkinter.py", >> line 1410, in __call__ >> return self.func(*args) >> TypeError: focus_set() takes exactly 1 argument (2 given) >> >> In situations like this where the function isn't one you wrote, how to you >> debug these? > > In this case there is not much to debug, the error message says it all: you > have an extra argument that the focus_set() method doesn't accept. The > simplest way to drop that argument is to wrap the method call: > > def focus_set(event): # only one arg because it's a function, not a method > self.login_userid.focus_set() > > self.list.bind("", focus_set) > > This is sometimes written with a lambda function > > self.list.bind("", lambda event: self.login_userid.focus_set()) > > If you wanted to learn more about that extra argument you could temporarily > replace the callback with something that can give you the necessary > information, e. g. > > def inspect_args(*args): > for arg in args: > print arg > print vars(arg) > > self.list.bind("", inspect_args) > > As a last resort and an idea almost too revolutionary to mention in public, > you could read some tutorial or documentation... > > _______________________________________________ > 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 Thu Nov 3 16:08:22 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 3 Nov 2011 10:08:22 -0500 Subject: [Tutor] binding problem In-Reply-To: References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> Message-ID: On Thu, Nov 3, 2011 at 9:41 AM, Chris Hare wrote: > Thanks Peter. Actually, I have read a bunch of stuff and looked at > example code. The problem in this case is I am using a defined method - > focus_set(), which is part of Tkinter and isn't part of my code. since I > am using it in the manner in which I have seen other examples, I am > confused about why it is complaining about 2 arguments, when I am not > passing any. > > Although, I think I know what the problem is now. > The problem is that when you use .bind() Tkinter will pass an event into your function. This event contains useful information such as the x,y position of your mouse, the key that fired the event, and a few other items. Of course, since focus_set() belongs to a class it will always pass 'self' as the first parameter. So when you bind widget.focus_set, when the event loop handles say, , it finds the function bound (focus_set), and Python passes self and Tkinter passes the event - two parameters, even though you're passing none. As has been touched on, the standard thing to do when you are binding an event but you don't actually care about the event (like focus_set()), is to use the lambda, which allows you to ignore the event argument: self.list.bind("", lambda _: self.login_userid.focus_set()) It's convention to use the _ variable name to tell other programmers that you don't care about that value, and you're intentionally ignoring whatever gets passed to that function. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From chare at labr.net Thu Nov 3 16:32:56 2011 From: chare at labr.net (Chris Hare) Date: Thu, 3 Nov 2011 10:32:56 -0500 Subject: [Tutor] binding problem In-Reply-To: References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> Message-ID: <907699E1-9813-489D-B5B7-7A2655C01C18@labr.net> That helps Wayne - and was what I was referring to when I posted that I thought I had figured it out. Thanks for your help. Chris Hare chare at labr.net http://www.labr.net On Nov 3, 2011, at 10:08 AM, Wayne Werner wrote: > On Thu, Nov 3, 2011 at 9:41 AM, Chris Hare wrote: > Thanks Peter. Actually, I have read a bunch of stuff and looked at example code. The problem in this case is I am using a defined method - focus_set(), which is part of Tkinter and isn't part of my code. since I am using it in the manner in which I have seen other examples, I am confused about why it is complaining about 2 arguments, when I am not passing any. > > Although, I think I know what the problem is now. > > The problem is that when you use .bind() Tkinter will pass an event into your function. This event contains useful information such as the x,y position of your mouse, the key that fired the event, and a few other items. Of course, since focus_set() belongs to a class it will always pass 'self' as the first parameter. > > So when you bind widget.focus_set, when the event loop handles say, , it finds the function bound (focus_set), and Python passes self and Tkinter passes the event - two parameters, even though you're passing none. > > As has been touched on, the standard thing to do when you are binding an event but you don't actually care about the event (like focus_set()), is to use the lambda, which allows you to ignore the event argument: > > self.list.bind("", lambda _: self.login_userid.focus_set()) > > It's convention to use the _ variable name to tell other programmers that you don't care about that value, and you're intentionally ignoring whatever gets passed to that function. > > HTH, > Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 3 17:30:18 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 4 Nov 2011 00:30:18 +0800 Subject: [Tutor] how to separate the digital and the alphabeta Message-ID: Hi, ['1AB','57GL', '76LE'] How can I extract 1, 57 , 76 out? except the one I tried as: >>> for i in range(len(a)): print(a[i][:-2]) 1 57 76 are there some way to tell the difference between the [0-9] and [A-Z], Thanks for the help (you will give and you have given). Best regards, From lina.lastname at gmail.com Thu Nov 3 17:37:18 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 4 Nov 2011 00:37:18 +0800 Subject: [Tutor] how to separate the digital and the alphabeta In-Reply-To: References: Message-ID: I have another question, regarding the generator, def translate_process(dictionary,tobetranslatedfile): results=[] with open(tobetranslatedfile,"r") as f: results=(dictionary[line.split()[2]] for line in f) print(list(results)) print(len(list(results))) Here the print(list(results)) did print a long list out, but why later print(len(list(results))) print 0 out? sorry, seems that way is very trivial. Best regards, From d at davea.name Thu Nov 3 18:05:50 2011 From: d at davea.name (Dave Angel) Date: Thu, 03 Nov 2011 13:05:50 -0400 Subject: [Tutor] how to separate the digital and the alphabeta In-Reply-To: References: Message-ID: <4EB2C9EE.4040602@davea.name> On 11/03/2011 12:30 PM, lina wrote: > Hi, > > ['1AB','57GL', '76LE'] > > How can I extract 1, 57 , 76 out? > > except the one I tried as: > >>>> for i in range(len(a)): > print(a[i][:-2]) > > > 1 > 57 > 76 > > are there some way to tell the difference between the [0-9] and [A-Z], > In the last thread, somebody else gave you a regular expression that would separate the digits out. I avoid regex'es like the plague, for no good reason, so I can't help with that approach. You can tell a particular string is all digits by using the isdigit() function. So some sort of while loop will find it. Perhaps (untested): def getkey(item): """find the largest prefix of the given string that is all digits. return the integer so produced""" res = "0" while(res and (res + item[0]).isdigit(): res += item[0] return int(res, 10) But your (tiny) sample always has two letters after the digits. Is that the rule? If so, you've got a simple version def getkey(item): b = item[:-2] return int(b) -- DaveA From d at davea.name Thu Nov 3 18:09:32 2011 From: d at davea.name (Dave Angel) Date: Thu, 03 Nov 2011 13:09:32 -0400 Subject: [Tutor] how to separate the digital and the alphabeta In-Reply-To: References: Message-ID: <4EB2CACC.6010804@davea.name> On 11/03/2011 12:37 PM, lina wrote: > > > I have another question, regarding the generator, > > def translate_process(dictionary,tobetranslatedfile): > results=[] > with open(tobetranslatedfile,"r") as f: > results=(dictionary[line.split()[2]] for line in f) > print(list(results)) > print(len(list(results))) > > > Here the print(list(results)) > did print a long list out, > but why later print(len(list(results))) > print 0 out? > > sorry, seems that way is very trivial. > > Best regards, > _ resuts is a generator, and they can only be iterated through once. So if you need it more than once, convert it to a list first, and save that list. or just use a list comprehension in the first place, (just change the parenthese to square brackets) -- DaveA From alan.gauld at btinternet.com Thu Nov 3 19:22:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 03 Nov 2011 18:22:29 +0000 Subject: [Tutor] binding problem In-Reply-To: <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> References: <9F270964-B8AC-433C-BDAC-27C933DA209B@labr.net> <410E1C87-A385-4772-8B27-0EC7E2D5BD0E@labr.net> Message-ID: On 03/11/11 13:01, Chris Hare wrote: > Thanks for the advice. When I do that, I get this error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1410, in __call__ > return self.func(*args) > TypeError: focus_set() takes exactly 1 argument (2 given) > > In situations like this where the function isn't one you wrote, how to you debug these? Its not a bug in the function, its a bug in your use of bind(). bind() assumes that the function you are binding takes two arguments: self and the event. This is different to the function assigned to a command parameter which only takes a single (self) argument. So if you want to use a built-in function that doesn't match what bind expects (either more or less arguments) you need to provide a wrapper. Usually this will be in the form of a lambda: Where the function is short of args: self.list.bind("", lambda e: the_builtin() ) # drop the event Where the function needs extra args: self.list.bind("", lambda e: aBuiltIn(e, def1, def2) ) ) # supply defaults However if you are the creator of the method - as seems to be true here - you just change the signature of your function/method to take two args (and possibly ignore the event). def myMethod(self, e=None) # just ignore e if you don't need it # ... self.list.bind("", self.myMethod ) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Nov 4 02:00:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Nov 2011 12:00:23 +1100 Subject: [Tutor] Creating Android Apps w/ Python In-Reply-To: References: Message-ID: <4EB33927.5010305@pearwood.info> Mike Nickey wrote: > I'm currently taking a class on Android Development. > The instructor says that the code needed has to be done through Java. > Isn't there any way to create these same apps with Python? This is not really the place to be asking this sort of question. This list is focused on learning Python the programming language, not about the vagaries of using Python on random platforms. If you're lucky, somebody here may have done Android development and be able to give a useful answer, but you are more likely to get a good response from the python-list at python.org mailing list, also available as comp.lang.python on Usenet. You can also try using a good search engine: https://duckduckgo.com/html/?q=android%20development%20python Good luck! -- Steven From steve at pearwood.info Fri Nov 4 02:42:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Nov 2011 12:42:30 +1100 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> Message-ID: <4EB34306.4040004@pearwood.info> Alan Gauld wrote: > Use the list form, even though it does involve a few more keystrokes and > a lot more screen space. The extra typing to avoid the problems are not > worth it! :-) If you're worried about the screen space and/or keystrokes, you can do this: if direction.upper() in tuple('NSEW'): ... instead of if direction.upper() in ('N', 'S', 'E', 'W'): ... You can also use list, set or frozenset instead of tuple., but I prefer tuple because it signals the intention that the result should be read-only. -- Steven From lina.lastname at gmail.com Fri Nov 4 03:39:13 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 4 Nov 2011 10:39:13 +0800 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> Message-ID: On Wed, Nov 2, 2011 at 12:14 AM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >>> sorted(new_dictionary.items()) >> >> Thanks, it works, but there is still a minor question, >> >> can I sort based on the general numerical value? >> >> namely not: >> : >> : >> 83ILE 1 >> 84ALA 2 >> 8SER 0 >> 9GLY 0 >> : >> : >> >> rather 8 9 ...83 84, >> >> Thanks, > > You need a custom key function for that one: > >>>> import re >>>> def gnv(s): > ... ? ? parts = re.split(r"(\d+)", s) > ... ? ? parts[1::2] = map(int, parts[1::2]) > ... ? ? return parts > ... >>>> items = [("83ILE", 1), ("84ALA", 2), ("8SER", 0), ("9GLY", 0)] >>>> sorted(items, key=lambda pair: (gnv(pair[0]), pair[1])) > [('8SER', 0), ('9GLY', 0), ('83ILE', 1), ('84ALA', 2)] Thanks, I can follow the procedure and get the exact results, but still don't understand this part parts = re.split(r'"(\d+)",s) r"(\d+)", sorry, >>> items [('83ILE', 1), ('84ALA', 2), ('8SER', 0), ('9GLY', 0)] >>> parts = re.split(r"(\d+)",items) Traceback (most recent call last): File "", line 1, in parts = re.split(r"(\d+)",items) File "/usr/lib/python3.2/re.py", line 183, in split return _compile(pattern, flags).split(string, maxsplit) TypeError: expected string or buffer Thanks, > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lina.lastname at gmail.com Fri Nov 4 03:42:05 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 4 Nov 2011 10:42:05 +0800 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> Message-ID: On Fri, Nov 4, 2011 at 10:39 AM, lina wrote: > On Wed, Nov 2, 2011 at 12:14 AM, Peter Otten <__peter__ at web.de> wrote: >> lina wrote: >> >>>> sorted(new_dictionary.items()) >>> >>> Thanks, it works, but there is still a minor question, >>> >>> can I sort based on the general numerical value? >>> >>> namely not: >>> : >>> : >>> 83ILE 1 >>> 84ALA 2 >>> 8SER 0 >>> 9GLY 0 >>> : >>> : >>> >>> rather 8 9 ...83 84, >>> >>> Thanks, >> >> You need a custom key function for that one: >> >>>>> import re >>>>> def gnv(s): >> ... ? ? parts = re.split(r"(\d+)", s) >> ... ? ? parts[1::2] = map(int, parts[1::2]) >> ... ? ? return parts >> ... >>>>> items = [("83ILE", 1), ("84ALA", 2), ("8SER", 0), ("9GLY", 0)] >>>>> sorted(items, key=lambda pair: (gnv(pair[0]), pair[1])) >> [('8SER', 0), ('9GLY', 0), ('83ILE', 1), ('84ALA', 2)] > > > Thanks, I can follow the procedure and get the exact results, but > still don't understand this part > > parts = re.split(r'"(\d+)",s) > > r"(\d+)", sorry, > >>>> items > [('83ILE', 1), ('84ALA', 2), ('8SER', 0), ('9GLY', 0)] > > >>>> parts = re.split(r"(\d+)",items) > Traceback (most recent call last): > ?File "", line 1, in > ? ?parts = re.split(r"(\d+)",items) > ?File "/usr/lib/python3.2/re.py", line 183, in split > ? ?return _compile(pattern, flags).split(string, maxsplit) > TypeError: expected string or buffer Sorry, now works. parts = re.split(r"(\d+)", str(items)) > > Thanks, >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > From d at davea.name Fri Nov 4 03:50:04 2011 From: d at davea.name (Dave Angel) Date: Thu, 03 Nov 2011 22:50:04 -0400 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> Message-ID: <4EB352DC.2010803@davea.name> On 11/03/2011 10:39 PM, lina wrote: > On Wed, Nov 2, 2011 at 12:14 AM, Peter Otten<__peter__ at web.de> wrote: >> lina wrote: >> >> >>>> items > [('83ILE', 1), ('84ALA', 2), ('8SER', 0), ('9GLY', 0)] > > >>>> parts = re.split(r"(\d+)",items) > Traceback (most recent call last): > File "", line 1, in > parts = re.split(r"(\d+)",items) > File "/usr/lib/python3.2/re.py", line 183, in split > return _compile(pattern, flags).split(string, maxsplit) > TypeError: expected string or buffer > > Thanks, This email of Peter's is what I was referring to as regex. The re module is for processing regular expressions. You'll have to go to someone else for help in it, but I can point out that you can only process one string with that line. You're handing it a whole list. So something like: for item in items: parts = re.split(..... print (repr(parts)) might show you what it's doing. I suspect it'll give you a tuple with the numeric part first, and the non-numeric part second. -- DaveA From pdc.cse at gmail.com Fri Nov 4 03:58:30 2011 From: pdc.cse at gmail.com (Peter Camilleri) Date: Fri, 4 Nov 2011 13:58:30 +1100 Subject: [Tutor] improve the code In-Reply-To: References: <4EB0033A.9030500@davea.name> Message-ID: Not sure if that is what you are after since you are calling re.split() using items when Peter was using re.split() on a single item within items so instead of this parts = re.split(r"(\d+)", str(items)) try specifying just one item, like this parts = re.split(r"(\d+)", items[0]) On Fri, Nov 4, 2011 at 1:42 PM, lina wrote: > On Fri, Nov 4, 2011 at 10:39 AM, lina wrote: >> On Wed, Nov 2, 2011 at 12:14 AM, Peter Otten <__peter__ at web.de> wrote: >>> lina wrote: >>> >>>>> sorted(new_dictionary.items()) >>>> >>>> Thanks, it works, but there is still a minor question, >>>> >>>> can I sort based on the general numerical value? >>>> >>>> namely not: >>>> : >>>> : >>>> 83ILE 1 >>>> 84ALA 2 >>>> 8SER 0 >>>> 9GLY 0 >>>> : >>>> : >>>> >>>> rather 8 9 ...83 84, >>>> >>>> Thanks, >>> >>> You need a custom key function for that one: >>> >>>>>> import re >>>>>> def gnv(s): >>> ... ? ? parts = re.split(r"(\d+)", s) >>> ... ? ? parts[1::2] = map(int, parts[1::2]) >>> ... ? ? return parts >>> ... >>>>>> items = [("83ILE", 1), ("84ALA", 2), ("8SER", 0), ("9GLY", 0)] >>>>>> sorted(items, key=lambda pair: (gnv(pair[0]), pair[1])) >>> [('8SER', 0), ('9GLY', 0), ('83ILE', 1), ('84ALA', 2)] >> >> >> Thanks, I can follow the procedure and get the exact results, but >> still don't understand this part >> >> parts = re.split(r'"(\d+)",s) >> >> r"(\d+)", sorry, >> >>>>> items >> [('83ILE', 1), ('84ALA', 2), ('8SER', 0), ('9GLY', 0)] >> >> >>>>> parts = re.split(r"(\d+)",items) >> Traceback (most recent call last): >> ?File "", line 1, in >> ? ?parts = re.split(r"(\d+)",items) >> ?File "/usr/lib/python3.2/re.py", line 183, in split >> ? ?return _compile(pattern, flags).split(string, maxsplit) >> TypeError: expected string or buffer > > Sorry, now works. > > parts = re.split(r"(\d+)", str(items)) >> >> Thanks, >>> >>> >>> _______________________________________________ >>> 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 alan.gauld at btinternet.com Fri Nov 4 04:50:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 04 Nov 2011 03:50:49 +0000 Subject: [Tutor] Paper Rock Scissors game - User's choice not returned properly In-Reply-To: <4EB34306.4040004@pearwood.info> References: <4EAEC191.3060208@gmail.com> <4EAED63C.90603@gmail.com> <4EB34306.4040004@pearwood.info> Message-ID: On 04/11/11 01:42, Steven D'Aprano wrote: > Alan Gauld wrote: > If you're worried about the screen space and/or keystrokes, you can do > this: > > if direction.upper() in tuple('NSEW'): ... It's not so much the keystrokes that I don't like but it's the fact that I invariably miss out a quote or a comma every time I try to construct a long sequence of single character strings. This avoids that by getting Python to do the work for me. I like it! The best of both worlds. :-) Thanks Stephen, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Nov 4 07:32:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 04 Nov 2011 17:32:38 +1100 Subject: [Tutor] assign all parameters of __init__ to class variables? In-Reply-To: References: <4EB14951.6040602@compuscan.co.za> <201111030900.36857.steve@pearwood.info> Message-ID: <4EB38706.8090906@pearwood.info> Alex Hall wrote: > I'm sorry, I misspoke (well, mistyped anyway). I have a couple > class-level variables, but most of them are set in the __init__ so > that every instance gets a fresh copy of them. Thatnks for the > responses. Ah I see, or at least I think I see. Possibly we're talking at cross-purposes. When you talk about "class-level variables", to me that means class attributes: attributes of a class, like this: class Spam: x = "this is at the class level" as opposed to "instance-level variables", which I would interpret as instance attributes: class Ham: def __init__(self): self.x = "this is on the instance" If you mean something different from this, then we're talking past each other. -- Steven From __peter__ at web.de Fri Nov 4 09:10:42 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Nov 2011 09:10:42 +0100 Subject: [Tutor] improve the code References: <4EB0033A.9030500@davea.name> Message-ID: lina wrote: > On Wed, Nov 2, 2011 at 12:14 AM, Peter Otten <__peter__ at web.de> wrote: >> lina wrote: >> >>>> sorted(new_dictionary.items()) >>> >>> Thanks, it works, but there is still a minor question, >>> >>> can I sort based on the general numerical value? >>> >>> namely not: >>> : >>> : >>> 83ILE 1 >>> 84ALA 2 >>> 8SER 0 >>> 9GLY 0 >>> : >>> : >>> >>> rather 8 9 ...83 84, >>> >>> Thanks, >> >> You need a custom key function for that one: >> >>>>> import re >>>>> def gnv(s): >> ... parts = re.split(r"(\d+)", s) >> ... parts[1::2] = map(int, parts[1::2]) >> ... return parts >> ... >>>>> items = [("83ILE", 1), ("84ALA", 2), ("8SER", 0), ("9GLY", 0)] >>>>> sorted(items, key=lambda pair: (gnv(pair[0]), pair[1])) >> [('8SER', 0), ('9GLY', 0), ('83ILE', 1), ('84ALA', 2)] > > > Thanks, I can follow the procedure and get the exact results, but > still don't understand this part > > parts = re.split(r'"(\d+)",s) > > r"(\d+)", sorry, > >>>> items > [('83ILE', 1), ('84ALA', 2), ('8SER', 0), ('9GLY', 0)] > > >>>> parts = re.split(r"(\d+)",items) > Traceback (most recent call last): > File "", line 1, in > parts = re.split(r"(\d+)",items) > File "/usr/lib/python3.2/re.py", line 183, in split > return _compile(pattern, flags).split(string, maxsplit) > TypeError: expected string or buffer I was a bit lazy and hoped you would accept the gnv() function as a black box... Here's a step-through: re.split() takes a pattern where to split the string and a string. In the following example the pattern is the character "_": >>> re.split("_", "alpha_beta___gamma") ['alpha', 'beta', '', '', 'gamma'] You can see that this simple form works just like "alpha_beta___gamma".split("_"), and finds an empty string between two adjacent "_". If you want both "_" and "___" to work as a single separator you can change the pattern to "_+", where the "+" means one or more of the previous: >>> re.split("_+", "alpha_beta___gamma") ['alpha', 'beta', 'gamma'] If we want to keep the separators, we can wrap the whole expression in parens: >>> re.split("(_+)", "alpha_beta___gamma") ['alpha', '_', 'beta', '___', 'gamma'] Now for the step that is a bit unobvious: we can change the separator to include all digits. Regular expressions have two ways to spell "any digit": [0-9] or \d: >>> re.split("([0-9]+)", "alpha1beta123gamma") ['alpha', '1', 'beta', '123', 'gamma'] I chose the other (which will also accept non-ascii digits) >>> re.split(r"(\d+)", "alpha1beta123gamma") ['alpha', '1', 'beta', '123', 'gamma'] At this point we are sure that the list contains a sequence of non-integer- str, integer-str, ..., non-integer-str, the first and the last always being a non-integer str. >>> parts = re.split(r"(\d+)", "alpha1beta123gamma") So >>> parts[1::2] ['1', '123'] will always give us the parts that can be converted to an integer >>> parts ['alpha', '1', 'beta', '123', 'gamma'] >>> parts[1::2] = map(int, parts[1::2]) >>> parts ['alpha', 1, 'beta', 123, 'gamma'] We need to do the conversion because strings won't sort the way we like: >>> sorted(["2", "20", "10"]) ['10', '2', '20'] >>> sorted(["2", "20", "10"], key=int) ['2', '10', '20'] We now have the complete gnv() function >>> def gnv(s): ... parts = re.split(r"(\d+)", s) ... parts[1::2] = map(int, parts[1::2]) ... return parts ... and can successfully sort a simple list of strings like >>> values = ["83ILE", "84ALA", "8SER", "9GLY"] >>> sorted(values, key=gnv) ['8SER', '9GLY', '83ILE', '84ALA'] The sorted() function calls gnv() internally for every item in the list and uses the results to determine the order of the items. When sorted()/list.sort() did not feature the key argument you could do this manually with "decorate sort undecorate": >>> decorated = [(gnv(item), item) for item in values] >>> decorated [(['', 83, 'ILE'], '83ILE'), (['', 84, 'ALA'], '84ALA'), (['', 8, 'SER'], '8SER'), (['', 9, 'GLY'], '9GLY')] >>> decorated.sort() >>> decorated [(['', 8, 'SER'], '8SER'), (['', 9, 'GLY'], '9GLY'), (['', 83, 'ILE'], '83ILE'), (['', 84, 'ALA'], '84ALA')] >>> undecorated ['8SER', '9GLY', '83ILE', '84ALA'] For your actual data >>> items [('83ILE', 1), ('84ALA', 2), ('8SER', 0), ('9GLY', 0)] you need to extract the first from an (x, y) pair >>> def first_gnv(item): ... return gnv(item[0]) ... >>> first_gnv(("83ILE", 1)) ['', 83, 'ILE'] but what if there are items with the same x? In that case the order is undefined: >>> sorted([("83ILE", 1), ("83ILE", 2)], key=first_gnv) [('83ILE', 1), ('83ILE', 2)] >>> sorted([("83ILE", 2), ("83ILE", 1)], key=first_gnv) [('83ILE', 2), ('83ILE', 1)] Let's take y into account, too: >>> def first_gnv(item): ... return gnv(item[0]), item[1] ... >>> sorted([("83ILE", 1), ("83ILE", 2)], key=first_gnv) [('83ILE', 1), ('83ILE', 2)] >>> sorted([("83ILE", 2), ("83ILE", 1)], key=first_gnv) [('83ILE', 1), ('83ILE', 2)] We're done! >>> sorted(items, key=first_gnv) [('8SER', 0), ('9GLY', 0), ('83ILE', 1), ('84ALA', 2)] (If you look back into my previous post, can you find the first_gnv() function?) From mehgcap at gmail.com Fri Nov 4 14:08:37 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 4 Nov 2011 09:08:37 -0400 Subject: [Tutor] assign all parameters of __init__ to class variables? In-Reply-To: <4EB38706.8090906@pearwood.info> References: <4EB14951.6040602@compuscan.co.za> <201111030900.36857.steve@pearwood.info> <4EB38706.8090906@pearwood.info> Message-ID: No, I mean what you said. My class has one or two class-level: class myClass: x=5 and a lot of instance-level: def __init__(self, p1, p2...): self.__dict__.update(locals()) On 11/4/11, Steven D'Aprano wrote: > Alex Hall wrote: >> I'm sorry, I misspoke (well, mistyped anyway). I have a couple >> class-level variables, but most of them are set in the __init__ so >> that every instance gets a fresh copy of them. Thatnks for the >> responses. > > > Ah I see, or at least I think I see. Possibly we're talking at > cross-purposes. > > When you talk about "class-level variables", to me that means class > attributes: attributes of a class, like this: > > class Spam: > x = "this is at the class level" > > as opposed to "instance-level variables", which I would interpret as > instance attributes: > > > class Ham: > def __init__(self): > self.x = "this is on the instance" > > > If you mean something different from this, then we're talking past each > other. > > > > -- > Steven > _______________________________________________ > 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 joebatt at hotmail.co.uk Fri Nov 4 20:42:15 2011 From: joebatt at hotmail.co.uk (Joe Batt) Date: Fri, 4 Nov 2011 19:42:15 +0000 Subject: [Tutor] Help with re in Python 3 Message-ID: Hi all,Still trying with Python and programming in general?. I am trying to get a grip with re. I am writing a program to open a text file and scan it for exactly 3 uppercase letters in a row followed by a lowercase followed by exactly 3 uppercase letters. ( i.e. oooXXXoXXXooo )If possible could you explain why I am getting "EOL while scanning string literal" when I try running the following program in Python 3. My program: import reregexp=re.compile(r"[a-z]"r"[A-Z]"r"[A-Z]"r"[A-Z]"r"[a-z]"r"[A-Z]"r"[A-Z]"r"[A-Z]"r"[a-z]) file=('///Users/joebatt/Desktop/python3.txt','r')for line in file.readlines(): if regexp.search(line): print("Found value 3 caps followed by lower case followed by 3 caps")file.close() If possible could you explain why I am getting "EOL while scanning string literal" when I try running my program in Python 3. Thanks for your help Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Nov 4 20:51:38 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 4 Nov 2011 15:51:38 -0400 Subject: [Tutor] Help with re in Python 3 In-Reply-To: References: Message-ID: On Fri, Nov 4, 2011 at 3:42 PM, Joe Batt wrote: > Hi all, > Still trying with Python and programming in general?. > > I am trying to get a grip with re. I am writing a program to open a text > file and scan it for exactly 3 uppercase letters in a row followed by a > lowercase followed by exactly 3 uppercase letters. ( i.e. oooXXXoXXXooo ) > If possible could you explain why I am getting "EOL while scanning string > literal" when I try running the following program in Python 3. > > My program: > > import re > > regexp=re.compile(r"[a-z]"r"[A-Z]"r"[A-Z]"r"[A-Z]"r"[a-z]"r"[A-Z]"r"[A-Z]"r"[A-Z]"r"[a-z]) > > file=('///Users/joebatt/Desktop/python3.txt','r') > for line in file.readlines(): > if regexp.search(line): > print("Found value 3 caps followed by lower case followed by 3 > caps") > file.close() > > If possible could you explain why I am getting "EOL while scanning string > literal" when I try running my program in Python 3. > > Thanks for your help > > Joe > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You should read a little more about regular expressions to simplify yours, but I believe your problem is that you have no closing " after this: r"[a-z]) change it to r"[a-z]") -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Nov 4 20:59:42 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 4 Nov 2011 12:59:42 -0700 (PDT) Subject: [Tutor] Help with re in Python 3 In-Reply-To: References: Message-ID: <1320436782.97616.YahooMailNeo@web110707.mail.gq1.yahoo.com> It seems that you are not opening the file properly. You could do f = file('///Users/joebatt/Desktop/python3.txt','r') or: withfile('///Users/joebatt/Desktop/python3.txt','r') as f: ? for line in f: ??? m = re.search("[A-Z]{3}[a-z][A-Z]{3}", line) ??? if m: ????? print("Pattern found") ????? print(m.group(0)) ? 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: Joe Batt >To: tutor at python.org >Sent: Friday, November 4, 2011 8:42 PM >Subject: [Tutor] Help with re in Python 3 > > > >Hi all, >Still trying with Python and programming in general?.? > > >I am trying to get a grip with re. I am writing a program to open a text file and scan it for exactly 3 uppercase letters in a row followed by a lowercase followed by exactly 3 uppercase letters. ( i.e. ?oooXXXoXXXooo ) >If possible could you explain why I am getting "EOL while scanning string literal" when I try running the following program in Python 3. > > >My program: > > >import re >regexp=re.compile(r"[a-z]"r"[A-Z]"r"[A-Z]"r"[A-Z]"r"[a-z]"r"[A-Z]"r"[A-Z]"r"[A-Z]"r"[a-z]) >? ? ? ? ? ? ? ? ?? >file=('///Users/joebatt/Desktop/python3.txt','r') >for line in file.readlines(): >? ? if regexp.search(line): >? ? ? ? print("Found value 3 caps followed by lower case followed by 3 caps") >file.close() > > >If possible could you explain why I am getting "EOL while scanning string literal" when I try running my program in Python 3. > > >Thanks for your help > > >Joe > > > > >_______________________________________________ >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 maxskywalker1 at gmail.com Fri Nov 4 22:21:06 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Fri, 4 Nov 2011 17:21:06 -0400 Subject: [Tutor] Assigning variables with names set by other variables Message-ID: Is it possible to create a variable with a string held by another variable in Python? For example, >>> var_name = input("Variable name: ") (input: 'var') >>> var_name = 4 >>> print(var) (output: 4) (Yeah, I know that if this gets typed into Python, it won't work. It just pseudocode.) I'm on a Windows Vista with Python 3.2.2. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Nov 4 22:06:57 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 4 Nov 2011 17:06:57 -0400 Subject: [Tutor] Help with re in Python 3 In-Reply-To: <1320436782.97616.YahooMailNeo@web110707.mail.gq1.yahoo.com> References: <1320436782.97616.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF64EA21@EMARC112VS01.exchad.jpmchase.net> > m = re.search("[A-Z]{3}[a-z][A-Z]{3}", line) That is the expression I would suggest, except it is still more efficient to use a compiled regular expression like the original version. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From waynejwerner at gmail.com Fri Nov 4 22:38:49 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 4 Nov 2011 16:38:49 -0500 Subject: [Tutor] Assigning variables with names set by other variables In-Reply-To: References: Message-ID: On Fri, Nov 4, 2011 at 4:21 PM, Max S. wrote: > Is it possible to create a variable with a string held by another variable > in Python? For example, > > >>> var_name = input("Variable name: ") > (input: 'var') > >>> var_name = 4 > >>> print(var) > (output: 4) > > (Yeah, I know that if this gets typed into Python, it won't work. It just > pseudocode.) > There are a few ways to do what you want. The most dangerous (you should never use this unless you are 100% absolutely, totally for certain that the input will be safe. Which means you should probably not use it) method is by using exec(), which does what it sounds like: it executes whatever is passed to it in a string: >>> statement = input("Variable name: ") Variable name: var >>> exec(statement + "=4") >>> var 4 The (hopefully) obvious danger here is that someone could type anything into this statement: >>> statement = input("Variable name: ") Variable name: import sys; sys.exit(1); x >>> exec(statement + " =4") and now you're at your prompt. If the user wanted to do something more malicious there are commands like shutil.rmtree that could do *much* more damage. A much safer way is to use a dictionary: >>> safety = {} >>> safety[input("Variable Name: ")] = 4 Variable Name: my_var >>> safety["my_var"] 4 It requires a little more typing, but it also has the advantage of accepting perfectly arbitrary strings. There may be some other ways to do what you want, but hopefully that should get you started. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Nov 4 22:43:00 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 04 Nov 2011 22:43 +0100 Subject: [Tutor] Assigning variables with names set by other variables References: Message-ID: Max S. wrote: > Is it possible to create a variable with a string held by another variable > in Python? For example, > >>>> var_name = input("Variable name: ") > (input: 'var') >>>> var_name = 4 >>>> print(var) > (output: 4) > > (Yeah, I know that if this gets typed into Python, it won't work. It just > pseudocode.) > > I'm on a Windows Vista with Python 3.2.2. Thanks. The direct translation into python uses exec() >>> name = input("variable name: ") variable name: var >>> exec(name + " = 4") >>> var 4 However, exec() can execute arbitrary code, and if a malicious user enters import shutil; shutil.rmtree("/path/to/your/data"); x as the "variable name" you may be in trouble. Therefore experienced users normally use a dictionary instead: >>> namespace = {} >>> name = input("variable name: ") variable name: var >>> namespace[name] = 4 >>> namespace[name] 4 It may look less convenient at first sight, but can save you a lot of trouble later on. From carroll at tjc.com Fri Nov 4 22:39:56 2011 From: carroll at tjc.com (Terry Carroll) Date: Fri, 4 Nov 2011 14:39:56 -0700 (PDT) Subject: [Tutor] Assigning variables with names set by other variables In-Reply-To: References: Message-ID: On Fri, 4 Nov 2011, Max S. wrote: > Is it possible to create a variable with a string held by another variable > in Python?? For example, It's possible, but in almost all cases where this comes up, the better approach is to use a dictionary. From di.marvellous at gmail.com Fri Nov 4 23:34:13 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Sat, 5 Nov 2011 02:34:13 +0400 Subject: [Tutor] regexp Message-ID: Hello, I need to find the words in a corpus, which letters are in the alphabetical order ("almost", "my" etc.) I started with matching two consecutive letters in a word, which are in the alphabetical order, and tried to use this expression: ([a-z])[\1-z], but it won't work, it's matching any sequence of two letters. I can't figure out why... Evidently I can't refer to a group like this, can I? But how in this case can I achieve what I need? Thank you. -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Nov 4 23:45:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Nov 2011 09:45:35 +1100 Subject: [Tutor] Assigning variables with names set by other variables In-Reply-To: References: Message-ID: <4EB46B0F.1080901@pearwood.info> Max S. wrote: > Is it possible to create a variable with a string held by another variable > in Python? For example, Yes, but you shouldn't do it. Seriously. Don't do this, you will regret it. var_name = input("Variable name? ") # use raw_input in Python 2 exec("%s = 4" % var_name) Instead, you should use a dictionary, like this: var_name = input("Variable name? ") table = {var_name: 4} and then later when you need to retrieve the value: print(table[var_name]) Why shouldn't you use exec? Three main reasons: (1) This code contains a MAJOR vulnerability to a code injection attack. There are enough code injection vulnerabilities in the world without you adding to it, please don't add another. (2) It makes for hard to read, difficult to follow code. (3) It's slow. If you don't know what code injection attacks means, consider this simple example where I create a variable spam=4 while executing any code I like: >>> var_name = input('Enter the variable name: ') Enter the variable name: print(123*456); spam >>> exec("%s = 4" % var_name) 56088 >>> spam 4 In this case, executing "print(123*456)" is harmless, but annoying, but it could do *anything* that Python can do (which is pretty much *anything at all*: delete files, send email, take over your computer, anything). Code injection attacks are among the two or three most common methods that viruses and malware operate. Sanitising user input so it is safe to pass to exec is a hard job. But suppose you do it (somehow!): var_name = sanitise(input('Enter the variable name: ')) exec("%s = 4" % var_name) # ... # ... later on # ... print(spam+1) # do something useful with the new variable But wait, that can't work! How do you know that the variable is called "spam"? You don't. It could be called anything. So now you have to do this: exec("print(%s+1)" % var_name) which is a nuisance, it is harder to read and harder to follow, and defeats any of the useful features in your editor or IDE. It gets worse if you need to use this var_name repeatedly: exec("print(%s+1)" % var_name) exec("my_list = [1, 2, 3, %s, 5]" % var_name) print(my_list) exec("y = func(23, %s, 42) + %s" % (var_name, var_name)) print(y) How tedious and painful and hard to follow. And it is potentially buggy: what if the user typed "func" as the variable name, by accident? Or over-wrote one of your other variables? And it's slow. Every time you call exec(), Python has to run a mini-interpreter over the string, analyzing it, splitting it into tokens, compiling it into code that can be executed, and then finally execute it. In general, this is slow: in my experience, running exec("command") is about 10 times slower than just running command directly. So just avoid using exec. Anytime you think you need exec, you almost certainly do not. And you definitely don't need it for indirect variables! Just use a dictionary instead: var_name = input("Variable name? ") table = {var_name: 4} # ... # ... later on # ... print(table[var_name]+1) my_list = [1, 2, 3, table[var_name], 5] print(my_list) y = func(23, table[var_name], 42) + table[var_name] print(y) -- Steven From steve at pearwood.info Sat Nov 5 00:00:55 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Nov 2011 10:00:55 +1100 Subject: [Tutor] regexp In-Reply-To: References: Message-ID: <4EB46EA7.20209@pearwood.info> Dinara Vakhitova wrote: > Hello, > > I need to find the words in a corpus, which letters are in the alphabetical > order ("almost", "my" etc.) Quoting Jamie Zawinski: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. Now you have two problems: find words in the corpus which are in alphabetical order, and get the damn regular expression to work correctly. Don't use a regex for this. It is much simpler to write a Python function to solve it: def letters_in_order(astring): """Return True if letters in astring are in alphabetical order. >>> letters_in_order("almost") True >>> letters_in_order("zoology") False """ if len(astring) <= 1: return True for i in range(1, len(astring)): if astring[i] < astring[i-1]: # Pair of characters are out of order. return False # If none of the pairs are out of order, they whole string # must be in order. return True words = filter(letters_in_order, corpus) for word in words: print(word) -- Steven From di.marvellous at gmail.com Sat Nov 5 00:06:44 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Sat, 5 Nov 2011 03:06:44 +0400 Subject: [Tutor] regexp In-Reply-To: <4EB46EA7.20209@pearwood.info> References: <4EB46EA7.20209@pearwood.info> Message-ID: Thank you for your answer, Steven. Of course it would have been easier to write this function, but unfortunately my task is to do it with a regular expression :( D. 2011/11/5 Steven D'Aprano > Dinara Vakhitova wrote: > >> Hello, >> >> I need to find the words in a corpus, which letters are in the >> alphabetical >> order ("almost", "my" etc.) >> > > Quoting Jamie Zawinski: > > Some people, when confronted with a problem, think "I know, I'll > use regular expressions." Now they have two problems. > > Now you have two problems: find words in the corpus which are in > alphabetical order, and get the damn regular expression to work correctly. > > Don't use a regex for this. It is much simpler to write a Python function > to solve it: > > def letters_in_order(astring): > """Return True if letters in astring are in alphabetical order. > > >>> letters_in_order("almost") > True > >>> letters_in_order("zoology") > False > > """ > if len(astring) <= 1: > return True > for i in range(1, len(astring)): > if astring[i] < astring[i-1]: > # Pair of characters are out of order. > return False > # If none of the pairs are out of order, they whole string > # must be in order. > return True > > words = filter(letters_in_order, corpus) > for word in words: > print(word) > > > > -- > Steven > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Nov 5 00:29:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Nov 2011 10:29:40 +1100 Subject: [Tutor] regexp In-Reply-To: References: <4EB46EA7.20209@pearwood.info> Message-ID: <4EB47564.1030309@pearwood.info> Dinara Vakhitova wrote: > Thank you for your answer, Steven. > > Of course it would have been easier to write this function, > but unfortunately my task is to do it with a regular expression :( Is this homework? You should have said so. I don't understand questions like this. Do carpenters ask their apprentices to cut a piece of wood with a hammer? Do apprentice chefs get told to dice carrots using only a spoon? Computer programming is the only skill I know of where teachers routinely insist that students use inappropriate tools to solve a problem, just to prove they can do it. In any case, if this is even possible using regular expressions -- and I don't think it is -- I have no idea how to do it. Good luck. Maybe somebody else might have a clue. I don't think it's possible because you don't know how many characters the string will have. Even if [\1-z] works (which it doesn't), you still have the same problem that you don't know where to stop: [a-z][\1-z][\2-z][\3-z][\4-z]...[\99-z] This is related to the reason you can't parse indefinitely nested parentheses using a regular expression. -- Steven From di.marvellous at gmail.com Sat Nov 5 00:38:55 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Sat, 5 Nov 2011 03:38:55 +0400 Subject: [Tutor] regexp In-Reply-To: <4EB47564.1030309@pearwood.info> References: <4EB46EA7.20209@pearwood.info> <4EB47564.1030309@pearwood.info> Message-ID: Sorry, I didn?t know that I couldn?t ask questions about the homework... I wanted to do it recursively, like this: def check_abc(string): string = string.lower() check_pair = re.compile("([a-z])[\1-z]") if check_pair.match(string): if check_abc(string[1:]): return True else: return False else: return False the only problem is that this regex doesn?t work and this case is not specified in the Python documentation... Excuse me for disturbing you. 2011/11/5 Steven D'Aprano > Dinara Vakhitova wrote: > >> Thank you for your answer, Steven. >> >> Of course it would have been easier to write this function, >> but unfortunately my task is to do it with a regular expression :( >> > > Is this homework? You should have said so. > > I don't understand questions like this. Do carpenters ask their > apprentices to cut a piece of wood with a hammer? Do apprentice chefs get > told to dice carrots using only a spoon? Computer programming is the only > skill I know of where teachers routinely insist that students use > inappropriate tools to solve a problem, just to prove they can do it. > > In any case, if this is even possible using regular expressions -- and I > don't think it is -- I have no idea how to do it. Good luck. Maybe somebody > else might have a clue. > > I don't think it's possible because you don't know how many characters the > string will have. Even if [\1-z] works (which it doesn't), you still have > the same problem that you don't know where to stop: > > [a-z][\1-z][\2-z][\3-z][\4-z].**..[\99-z] > > This is related to the reason you can't parse indefinitely nested > parentheses using a regular expression. > > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Nov 5 01:29:50 2011 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 5 Nov 2011 01:29:50 +0100 Subject: [Tutor] regexp In-Reply-To: References: <4EB46EA7.20209@pearwood.info> <4EB47564.1030309@pearwood.info> Message-ID: On 5 November 2011 00:38, Dinara Vakhitova wrote: > Sorry, I didn?t know that I couldn?t ask questions about the homework... This list is meant to help with learning python and not to do homework assignments. So if you get stuck with something yes you can post it but be open about it and show what you have tried (code). I suspect then people on this list will provide guidance and drop hints but leave the *writing* of the code to you. > I wanted to do it recursively, like this: > def check_abc(string): > ? ? string = string.lower() > ? ? check_pair = re.compile("([a-z])[\1-z]") > ? ? if check_pair.match(string): > ? ? ? ? if check_abc(string[1:]): > ? ? ? ? ? ? return True > ? ? ? ? else: > ? ? ? ? ? ? return False > ? ? else: > ? ? ? ? return False Is using regular expressions a requirement? As Steve already pointed out this is a hard problem to solve (if it can be solved at all) with regex. So unless the home work requires regex just drop it. > the only problem is that this regex doesn?t work and this case is not > specified in the Python documentation... There is a separate howto on http://docs.python.org/howto/regex.html does a decent job. > Excuse me for disturbing you. Well, people on this list are volunteers and do not get paid for answering questions. He actually gave you good and well reasoned advice and if I was you I'd take it. Greets Sander From steve at pearwood.info Sat Nov 5 02:01:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Nov 2011 12:01:11 +1100 Subject: [Tutor] regexp In-Reply-To: References: <4EB46EA7.20209@pearwood.info> <4EB47564.1030309@pearwood.info> Message-ID: <4EB48AD7.1050300@pearwood.info> Dinara Vakhitova wrote: > Sorry, I didn?t know that I couldn?t ask questions about the homework... You're welcome to ask questions about homework or school projects, but most of the people here believe that ethically the student should do the homework, not the tutor :) So if something looks like a homework question, we will usually point the student in the right direction and ask them to actually write the code, rather than write the code ourselves. Good luck with the question! If you do solve it, please come back and tell us how you did it. I for one am curious now whether or not it can be done using Python regexes. Perhaps someone else might have a solution. You could try the python-list at python.org mailing list, also available on comp.lang.python on Usenet. (You could also try it with Perl regexes, which I understand are more powerful.) -- Steven From steve at pearwood.info Sat Nov 5 02:03:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 05 Nov 2011 12:03:34 +1100 Subject: [Tutor] Help with re in Python 3 In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF64EA21@EMARC112VS01.exchad.jpmchase.net> References: <1320436782.97616.YahooMailNeo@web110707.mail.gq1.yahoo.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF64EA21@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4EB48B66.3040508@pearwood.info> Prasad, Ramit wrote: >> m = re.search("[A-Z]{3}[a-z][A-Z]{3}", line) > > That is the expression I would suggest, except it is still more > efficient to use a compiled regular expression like the original > version. Not necessarily. The Python regex module caches recently used regex strings, avoiding re-compiling them when possible. However there is no guarantee on how many regexes are kept in the cache, so if you care, it is safer to keep your own compiled version. -- Steven From wprins at gmail.com Sat Nov 5 02:06:45 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 5 Nov 2011 01:06:45 +0000 Subject: [Tutor] regexp In-Reply-To: <4EB47564.1030309@pearwood.info> References: <4EB46EA7.20209@pearwood.info> <4EB47564.1030309@pearwood.info> Message-ID: Dinara, Steven, On 4 November 2011 23:29, Steven D'Aprano wrote: > Is this homework? You should have said so. > Inded he should've... > I don't understand questions like this. Do carpenters ask their > apprentices to cut a piece of wood with a hammer? Do apprentice chefs get > told to dice carrots using only a spoon? Computer programming is the only > skill I know of where teachers routinely insist that students use > inappropriate tools to solve a problem, just to prove they can do it. > Calm down dear, it's only a reg-ex... ;) Additionally, if I may say so, I find this part of your response rather less than helpful, it's rant-ish IMHO, and as far as I'm concerned the apprentice analogies are not akin to what programming teachers do and why they do it. Fact is, people need to learn the tools of their trade somewhere. Sometimes it's neccesary to focus on a particular tool and therefore dream up some artificial problem for the sake of learning to use the tool. It's not that apprentices are being taught to cut wood with a hammer or whatnot. And yes, regular expression can be damn useful sometimes. Whether or not you like regular expressions, use them, or are good at them have no bearing on whether Dinara should be able learn how to use them, nor is it relevant what you think of the question or if the context of the learning is a contrived question/excercise. > In any case, if this is even possible using regular expressions -- and I > don't think it is -- I have no idea how to do it. Good luck. Maybe somebody > else might have a clue. > @Dinara: It is actually. Let's describe the requirement a bit differently, first in words, then see if we can write a regular expression that will match that description: A word that matches our requirement will start with 0 or more occurences of a, and be followed by 0 or more occurrences of b, and so on, until z, after which we must have reached the end of the word. So the requirements for the regex is: 1.) The regex must start at the beginning of the string 2.) 0 or more a's may be matched, followed by 0 or more b's, followed by 0 or more c's and son on, up to z, 3.) The regex must end at the end of the string (so 1 and 3 together imply that all the text in the string must be matched/consumed by the regex for a match to have been found. If we write an equivalent regex, to the above requirement, and it matches all the text in a string (e.g. a match is found), then by definition it will have found a word containing letters in alphabetized order. The only special case to handle would be the empty string -- this would be matched by the above regex but may not be considered correct per the intent of the problem. (On the other hand, an empty string is not a word either, so one might consider this invalid input in the first place and should properly probably reject the input and refuse to process it.) I'll give you some further hints. 1.) To specify/match the beginning of a string, you use the ^ character in a regex. 2.) To specify 0 or more of something you append an asterisk, e.g. * 3.) To specify a letter to be matched, you can write it directly. To therefore match 0 or more a's for example, you'd write a* 4.) To specify a sequence of things you simply write them out. So for example the regular expression a*b* will match strings like 'ab', 'aab', 'abb', 'b', 'a', but not 'baa'... 5.) To specify the end of a string, you use the $ character in a regex. By the way, it's possible to write an alternatve version of the function that Steven provied in a single line (of body code) with a regex. HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Nov 5 02:49:14 2011 From: d at davea.name (Dave Angel) Date: Fri, 04 Nov 2011 21:49:14 -0400 Subject: [Tutor] regexp In-Reply-To: <4EB46EA7.20209@pearwood.info> References: <4EB46EA7.20209@pearwood.info> Message-ID: <4EB4961A.9000102@davea.name> On 11/04/2011 07:00 PM, Steven D'Aprano wrote: > Dinara Vakhitova wrote: >> Hello, >> >> I need to find the words in a corpus, which letters are in the >> alphabetical >> order ("almost", "my" etc.) > > Quoting Jamie Zawinski: > > Some people, when confronted with a problem, think "I know, I'll > use regular expressions." Now they have two problems. > > Now you have two problems: find words in the corpus which are in > alphabetical order, and get the damn regular expression to work > correctly. > > Don't use a regex for this. It is much simpler to write a Python > function to solve it: > > def letters_in_order(astring): > """Return True if letters in astring are in alphabetical order. > > >>> letters_in_order("almost") > True > >>> letters_in_order("zoology") > False > > """ > if len(astring) <= 1: > return True > for i in range(1, len(astring)): > if astring[i] < astring[i-1]: > # Pair of characters are out of order. > return False > # If none of the pairs are out of order, they whole string > # must be in order. > return True > > words = filter(letters_in_order, corpus) > for word in words: > print(word) > > > Seems to me it'd much simpler to do something like: return "".join(sorted(astring)) == astring with suitable adjustment if both lower and uppercase are desirable. -- DaveA From maxskywalker1 at gmail.com Sat Nov 5 03:23:14 2011 From: maxskywalker1 at gmail.com (Max gmail) Date: Fri, 04 Nov 2011 22:23:14 -0400 Subject: [Tutor] Assigning variables with names set by other variables In-Reply-To: References: Message-ID: Thank you, Wayne! This helps a lot. On Nov 4, 2011, at 5:38 PM, Wayne Werner wrote: > On Fri, Nov 4, 2011 at 4:21 PM, Max S. wrote: > Is it possible to create a variable with a string held by another variable in Python? For example, > > >>> var_name = input("Variable name: ") > (input: 'var') > >>> var_name = 4 > >>> print(var) > (output: 4) > > (Yeah, I know that if this gets typed into Python, it won't work. It just pseudocode.) > > There are a few ways to do what you want. The most dangerous (you should never use this unless you are 100% absolutely, totally for certain that the input will be safe. Which means you should probably not use it) method is by using exec(), which does what it sounds like: it executes whatever is passed to it in a string: > > >>> statement = input("Variable name: ") > Variable name: var > >>> exec(statement + "=4") > >>> var > 4 > > The (hopefully) obvious danger here is that someone could type anything into this statement: > > >>> statement = input("Variable name: ") > Variable name: import sys; sys.exit(1); x > >>> exec(statement + " =4") > > and now you're at your prompt. If the user wanted to do something more malicious there are commands like shutil.rmtree that could do *much* more damage. > > A much safer way is to use a dictionary: > > >>> safety = {} > >>> safety[input("Variable Name: ")] = 4 > Variable Name: my_var > >>> safety["my_var"] > 4 > > It requires a little more typing, but it also has the advantage of accepting perfectly arbitrary strings. > > There may be some other ways to do what you want, but hopefully that should get you started. > HTH, > Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Sat Nov 5 03:23:52 2011 From: maxskywalker1 at gmail.com (Max gmail) Date: Fri, 04 Nov 2011 22:23:52 -0400 Subject: [Tutor] Assigning variables with names set by other variables In-Reply-To: <4EB46B0F.1080901@pearwood.info> References: <4EB46B0F.1080901@pearwood.info> Message-ID: <696062EA-FCC8-4DB8-8D80-2BF05BCCE116@gmail.com> Thanks Steven. On Nov 4, 2011, at 6:45 PM, Steven D'Aprano wrote: > Max S. wrote: >> Is it possible to create a variable with a string held by another variable >> in Python? For example, > > Yes, but you shouldn't do it. Seriously. Don't do this, you will regret it. > > var_name = input("Variable name? ") # use raw_input in Python 2 > exec("%s = 4" % var_name) > > > Instead, you should use a dictionary, like this: > > var_name = input("Variable name? ") > table = {var_name: 4} > > and then later when you need to retrieve the value: > > print(table[var_name]) > > > > Why shouldn't you use exec? > > Three main reasons: > > (1) This code contains a MAJOR vulnerability to a code injection attack. There are enough code injection vulnerabilities in the world without you adding to it, please don't add another. > > (2) It makes for hard to read, difficult to follow code. > > (3) It's slow. > > > If you don't know what code injection attacks means, consider this simple example where I create a variable spam=4 while executing any code I like: > > >>> var_name = input('Enter the variable name: ') > Enter the variable name: print(123*456); spam > >>> exec("%s = 4" % var_name) > 56088 > >>> spam > 4 > > > In this case, executing "print(123*456)" is harmless, but annoying, but it could do *anything* that Python can do (which is pretty much *anything at all*: delete files, send email, take over your computer, anything). Code injection attacks are among the two or three most common methods that viruses and malware operate. > > Sanitising user input so it is safe to pass to exec is a hard job. But suppose you do it (somehow!): > > var_name = sanitise(input('Enter the variable name: ')) > exec("%s = 4" % var_name) > # ... > # ... later on > # ... > print(spam+1) # do something useful with the new variable > > But wait, that can't work! How do you know that the variable is called "spam"? You don't. It could be called anything. So now you have to do this: > > exec("print(%s+1)" % var_name) > > which is a nuisance, it is harder to read and harder to follow, and defeats any of the useful features in your editor or IDE. It gets worse if you need to use this var_name repeatedly: > > exec("print(%s+1)" % var_name) > exec("my_list = [1, 2, 3, %s, 5]" % var_name) > print(my_list) > exec("y = func(23, %s, 42) + %s" % (var_name, var_name)) > print(y) > > How tedious and painful and hard to follow. And it is potentially buggy: what if the user typed "func" as the variable name, by accident? Or over-wrote one of your other variables? > > And it's slow. Every time you call exec(), Python has to run a mini-interpreter over the string, analyzing it, splitting it into tokens, compiling it into code that can be executed, and then finally execute it. In general, this is slow: in my experience, running exec("command") is about 10 times slower than just running command directly. > > So just avoid using exec. Anytime you think you need exec, you almost certainly do not. And you definitely don't need it for indirect variables! Just use a dictionary instead: > > var_name = input("Variable name? ") > table = {var_name: 4} > # ... > # ... later on > # ... > print(table[var_name]+1) > my_list = [1, 2, 3, table[var_name], 5] > print(my_list) > y = func(23, table[var_name], 42) + table[var_name] > print(y) > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From andreas.perstinger at gmx.net Sat Nov 5 08:24:51 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 05 Nov 2011 08:24:51 +0100 Subject: [Tutor] Help with re in Python 3 In-Reply-To: <1320436782.97616.YahooMailNeo@web110707.mail.gq1.yahoo.com> References: <1320436782.97616.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: <4EB4E4C3.3020107@gmx.net> On 2011-11-04 20:59, Albert-Jan Roskam wrote: > It seems that you are not opening the file properly. You could do > f = file('///Users/joebatt/Desktop/python3.txt','r') > or: > withfile('///Users/joebatt/Desktop/python3.txt','r') as f: OP is using Python 3, where "file" is removed. Thus, you have to use "open": f = open('...') with open('...') as f: Bye, Andreas From __peter__ at web.de Sat Nov 5 09:22:05 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 05 Nov 2011 09:22:05 +0100 Subject: [Tutor] regexp References: <4EB46EA7.20209@pearwood.info> <4EB47564.1030309@pearwood.info> <4EB48AD7.1050300@pearwood.info> Message-ID: Steven D'Aprano wrote: > Good luck with the question! If you do solve it, please come back and > tell us how you did it. I for one am curious now whether or not it can > be done using Python regexes. Perhaps someone else might have a > solution. You could try the python-list at python.org mailing list, also > available on comp.lang.python on Usenet. Dinara, here's a hint: I found a brute-force solution where the regex contains every allowed letter explicitly, followed by a quantifier. As long as you confine yourself to ascii-letters the performance may be acceptable. If that hurts your sense of esthetics the tip to try comp.lang.python is a good one. Matthew Barnett aka MRAB, author of an alternative regex library for python, posts there regularly. From fomcl at yahoo.com Sat Nov 5 10:18:43 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 5 Nov 2011 02:18:43 -0700 (PDT) Subject: [Tutor] regexp In-Reply-To: <4EB4961A.9000102@davea.name> References: <4EB46EA7.20209@pearwood.info> <4EB4961A.9000102@davea.name> Message-ID: <1320484723.38821.YahooMailNeo@web110707.mail.gq1.yahoo.com> Hi, I would know if or how it could be done with regexes, but isn't the following simple code a solution? It requires that the text be split up into separate words. Or am I overlooking something? >>word = 'ym' >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == list(word[1:]) False >>word = 'almost' >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == list(word[1:]) ?True 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: Dave Angel >To: Steven D'Aprano >Cc: tutor at python.org >Sent: Saturday, November 5, 2011 2:49 AM >Subject: Re: [Tutor] regexp > >On 11/04/2011 07:00 PM, Steven D'Aprano wrote: >> Dinara Vakhitova wrote: >>> Hello, >>> >>> I need to find the words in a corpus, which letters are in the alphabetical >>> order ("almost", "my" etc.) >> >> Quoting Jamie Zawinski: >> >>? ? Some people, when confronted with a problem, think "I know, I'll >>? ? use regular expressions." Now they have two problems. >> >> Now you have two problems: find words in the corpus which are in alphabetical order, and get the damn regular expression to work correctly. >> >> Don't use a regex for this. It is much simpler to write a Python function to solve it: >> >> def letters_in_order(astring): >>? ? """Return True if letters in astring are in alphabetical order. >> >> >>> letters_in_order("almost") >>? ? True >> >>> letters_in_order("zoology") >>? ? False >> >>? ? """ >>? ? if len(astring) <= 1: >>? ? ? ? return True >>? ? for i in range(1, len(astring)): >>? ? ? ? if astring[i] < astring[i-1]: >>? ? ? ? ? ? # Pair of characters are out of order. >>? ? ? ? ? ? return False >>? ? # If none of the pairs are out of order, they whole string >>? ? # must be in order. >>? ? return True >> >> words = filter(letters_in_order, corpus) >> for word in words: >>? ? print(word) >> >> >> >Seems to me it'd much simpler to do something like: >? ? return "".join(sorted(astring)) == astring > >with suitable adjustment if both lower and uppercase are desirable. > >-- >DaveA > >_______________________________________________ >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 di.marvellous at gmail.com Sat Nov 5 14:50:34 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Sat, 5 Nov 2011 17:50:34 +0400 Subject: [Tutor] regexp In-Reply-To: <1320484723.38821.YahooMailNeo@web110707.mail.gq1.yahoo.com> References: <4EB46EA7.20209@pearwood.info> <4EB4961A.9000102@davea.name> <1320484723.38821.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: Steven, Walter, Dave, Peter and Albert, First of all, thank you very much for your suggestions, I appreciate a lot your help. I would only like to mention that I would have never asked something to be done for me just because it's my homework, I posted this question only because I couldn't find a solution myself and I was dying from curiosity how to do it. For me it makes no difference if it was homework or not, because it's practice first of all, I'm not studying for marks, that's why I was surprised to know that I should have specified it. So, yesterday I was so upset that I couldn't make it work that I went to bed and gave it up for a while :) But then I came up with the solution similar to that proposed by Walter and Peter, i.e. list all the letters in alphabetical order marked by "*": [a*b*c*d*...x*y*z*] - with the only difference that I don't need to mark the beginning and the end of the line, because I first tokenized my text and I work with a single word (and it's supposed that the word is well-formed, without punctuation marks attached to it or empty strings or something) But naturally, this solution doesn't seem to be very elegant one (however, it might be exactly that solution that our teacher supposed us to find) I think, that I leave it like this till I find something more elegant if it's possible at all. I would know if or how it could be done with regexes, but isn't the > following simple code a solution? It requires that the text be split up > into separate words. Or am I overlooking something? > >>word = 'ym' > >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == > list(word[1:]) > False > >>word = 'almost' > >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == > list(word[1:]) > True Albert, concerning your question - yes, the text is tokenized to separate words. Thank you for your suggestion! I'm trying to understand how it works now :) Kind Regards, Dinara 2011/11/5 Albert-Jan Roskam > Hi, > > I would know if or how it could be done with regexes, but isn't the > following simple code a solution? It requires that the text be split up > into separate words. Or am I overlooking something? > >>word = 'ym' > >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == > list(word[1:]) > False > >>word = 'almost' > >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == > list(word[1:]) > True > > Cheers!! > Albert-Jan > -------------- next part -------------- An HTML attachment was scrubbed... URL: From di.marvellous at gmail.com Sat Nov 5 15:37:30 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Sat, 5 Nov 2011 18:37:30 +0400 Subject: [Tutor] regexp In-Reply-To: References: <4EB46EA7.20209@pearwood.info> <4EB4961A.9000102@davea.name> <1320484723.38821.YahooMailNeo@web110707.mail.gq1.yahoo.com> Message-ID: Oh, sorry, of course it should be without brackets: 'a*b*c*...' > [a*b*c*d*...x*y*z*] 2011/11/5 Dinara Vakhitova > Steven, Walter, Dave, Peter and Albert, > > First of all, thank you very much for your suggestions, I appreciate a lot > your help. I would only like to mention that I would have never asked > something to be done for me just because it's my homework, I posted this > question only because I couldn't find a solution myself and I was dying > from curiosity how to do it. For me it makes no difference if it was > homework or not, because it's practice first of all, I'm not studying for > marks, that's why I was surprised to know that I should have specified it. > > So, yesterday I was so upset that I couldn't make it work that I went to > bed and gave it up for a while :) But then I came up with the solution > similar to that proposed by Walter and Peter, i.e. list all the letters in > alphabetical order marked by "*": > > [a*b*c*d*...x*y*z*] - with the only difference that I don't need to mark > the beginning and the end of the line, because I first tokenized my text > and I work with a single word (and it's supposed that the word is > well-formed, without punctuation marks attached to it or empty strings or > something) > > But naturally, this solution doesn't seem to be very elegant one (however, > it might be exactly that solution that our teacher supposed us to find) > I think, that I leave it like this till I find something more elegant if > it's possible at all. > > I would know if or how it could be done with regexes, but isn't the >> following simple code a solution? It requires that the text be split up >> into separate words. Or am I overlooking something? >> >>word = 'ym' >> >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == >> list(word[1:]) >> False >> >>word = 'almost' >> >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == >> list(word[1:]) >> True > > > Albert, concerning your question - yes, the text is tokenized to separate > words. Thank you for your suggestion! I'm trying to understand how it > works now :) > > Kind Regards, > Dinara > > 2011/11/5 Albert-Jan Roskam > >> Hi, >> >> I would know if or how it could be done with regexes, but isn't the >> following simple code a solution? It requires that the text be split up >> into separate words. Or am I overlooking something? >> >>word = 'ym' >> >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == >> list(word[1:]) >> False >> >>word = 'almost' >> >>> [letter for n, letter in enumerate(word) if letter > word[n-1]] == >> list(word[1:]) >> True >> >> Cheers!! >> Albert-Jan >> > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From mayoadams at gmail.com Sat Nov 5 20:04:50 2011 From: mayoadams at gmail.com (Mayo Adams) Date: Sat, 5 Nov 2011 15:04:50 -0400 Subject: [Tutor] Writing processed text to another file(beginner) Message-ID: Code to build a list z to contain all the first words in each line of a text file: z=[] f=open('C:/atextfile.txt') for aLine in f: str=aLine a=str.split() z.append(a) I would like to work further with the list z once the file has been stripped, and the list is complete but am so clueless about Python and its curlybracelessness that I don't know when the for loop terminates. Obviously I don't want to write to the file after every line is read. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Nov 5 20:20:26 2011 From: d at davea.name (Dave Angel) Date: Sat, 05 Nov 2011 15:20:26 -0400 Subject: [Tutor] Writing processed text to another file(beginner) In-Reply-To: References: Message-ID: <4EB58C7A.40806@davea.name> On 11/05/2011 03:04 PM, Mayo Adams wrote: > Code to build a list z to contain all the first words in each line of a > text file: > > z=[] > > f=open('C:/atextfile.txt') > > for aLine in f: > > str=aLine > > a=str.split() > > z.append(a) > > > I would like to work further with the list z once the file has been > stripped, and the list is complete but am so clueless about Python and its > curlybracelessness that I don't know when the for loop terminates. > Obviously I don't want to write to the file after every line is read. > > Python's indentation rules are pretty simple. You need to indent all the contents of a for-loop, and the loop is over when you outdent back to line up with the for statement. In your posting, you don't indent at all, so you'll get an error on the line following the for statement. Now perhaps that's the fault of the way you're posting. Easiest is usually to tell your email program to compose as plain text. z=[] f=open('C:/atextfile.txt') for aLine in f: str=aLine a=str.split() z.append(a) f.close() print z Now you mention writing to a file. I hope you're not planning to write to the same file you're reading from. Anyway,tell us more about what you want, and whether the print of z shows what you're expecting, or want. -- DaveA From d at davea.name Sat Nov 5 21:32:42 2011 From: d at davea.name (Dave Angel) Date: Sat, 05 Nov 2011 16:32:42 -0400 Subject: [Tutor] Writing processed text to another file(beginner) In-Reply-To: References: <4EB58C7A.40806@davea.name> Message-ID: <4EB59D6A.5090608@davea.name> On 11/05/2011 03:31 PM, Mayo Adams wrote: > Thank you for your reply, this is all I needed to know: > >> the loop is over when you outdent back to line up with the for statement >> > > Indeed, the indentation rules are very simple. I just wanted to be sure > about what they were. > > >> Sounds good. Three more comments: You replied to me privately, but everyone else deserves to know your problem is resolved. Usually you just do a Reply-all, and it'll go both to the list and to the individual(s) already involved. And in commenting about indenting, I should clarify that you should never mix tabs and spaces in the same file. I used spaces exclusively, and have never run into problems. My editor does not put a tab in, it's configured differently. Note also that a few other things indent, besides just for-loop. Same principle applies to if statements, functions, to class definitions, to with statements. Roughly, if the line ends with a colon, you probably should indent all the following lines that it controls. -- DaveA From hothottrott at gmail.com Sun Nov 6 01:57:04 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Sat, 5 Nov 2011 18:57:04 -0600 Subject: [Tutor] Having trouble visiting the subscribers list. Message-ID: I recently subscribed to tutor and I am trying to visit the subscribers list so I can ask a question but I was'nt given an admin address. Not only that but I don't know what an admin address is. Your help is greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Nov 6 02:16:27 2011 From: d at davea.name (Dave Angel) Date: Sat, 05 Nov 2011 21:16:27 -0400 Subject: [Tutor] Having trouble visiting the subscribers list. In-Reply-To: References: Message-ID: <4EB5DFEB.8070207@davea.name> On 11/05/2011 08:57 PM, Nathaniel Trujillo wrote: > I recently subscribed to tutor and I am trying to visit the subscribers > list so I can ask a question but I was'nt given an admin address. Not only > that but I don't know what an admin address is. Your help is greatly > appreciated. > > You've figured out how to post, so post your question already. No need to address it to specific "subscribers," since that's not what the list is all about. FWIW I have no idea how to get a subscriber's list. Most subscribers don't post anyway, so the only thing that concerns me is the ones who do. -- DaveA From steve at pearwood.info Sun Nov 6 02:24:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 06 Nov 2011 12:24:12 +1100 Subject: [Tutor] Having trouble visiting the subscribers list. In-Reply-To: References: Message-ID: <4EB5E1BC.8060804@pearwood.info> Nathaniel Trujillo wrote: > I recently subscribed to tutor and I am trying to visit the subscribers > list so I can ask a question but I was'nt given an admin address. Not only > that but I don't know what an admin address is. Your help is greatly > appreciated. Why do you want to see the list of subscribers? That's private information. If you want to ask a question, ask it by sending an email to . -- Steven From hothottrott at gmail.com Sun Nov 6 03:02:12 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Sat, 5 Nov 2011 20:02:12 -0600 Subject: [Tutor] getting nasty TypeError: Message-ID: Hello. I am currently working with Python version 3.1.1 . I am working out of the book called Python Programming for the Absolute Beginner Third Edition which teaches version 3.1.1 . I wrote the following blackjack program that is on page 275 and I imported the modules that you see below. First the cards module which is on page 271 and then the games module which is on page 268. I tried typing everything in exactly the way it is in the book but when I run the blackjack program that you see below it will first ask me how many players just like it should, then I tell it how many players, then it will ask me the names of each player just like it should, then I tell it the name of each player and after I do that and press enter I get the following error message. Traceback (most recent call last): File "C:\Python31\blackjack.py", line 184, in main() File "C:\Python31\blackjack.py", line 181, in main game.play() File "C:\Python31\blackjack.py", line 132, in play print(player) File "C:\Python31\blackjack.py", line 34, in __str__ rep = self.name + "\t" + super(BJ_Hand, self).__str__() TypeError: can only concatenate list (not "str") to list Here is the blackjack program. It is called blackjack.py # Blackjack # From 1 to 7 players compete against a dealer import cards, games class BJ_Card(cards.Card): """ A Blackjack Card. """ ACE_VALUE = 1 @property def value(self): if self.is_face_up: v = BJ_Card.RANKS.index(self.rank) + 1 if v > 10: v = 10 else: v = None return v class BJ_Deck(cards.Deck): """ A Blackjack Deck. """ def populate(self): for suit in BJ_Card.SUITS: for rank in BJ_Card.RANKS: self.cards.append(BJ_Card(rank, suit)) class BJ_Hand(cards.Hand): """ A Blackjack Hand. """ def __init__(self, name): super(BJ_Hand, self).__init__() self.name = name def __str__(self): rep = self.name + "\t" + super(BJ_Hand, self).__str__() if self.total: rep += "(" + str(self.total) + ")" return rep @property def total(self): # if a card in the hand has value of None, then total is None for card in self.cards: if not card.value: return None # add up card values, treat each Ace as 1 t = 0 for card in self.cards: t += card.value # determine if hand contains an Ace contains_ace = False for card in self.cards: if card.value == BJ_Card.ACE_VALUE: contains_ace = True # if hand contains Ace and total is low enough, treat Ace as 11 if contains_ace and t <= 11: # add only 10 since we've already added 1 for the Ace t += 10 return t def is_busted(self): return self.total > 21 class BJ_Player(BJ_Hand): """ A Blackjack Player. """ def is_hitting(self): response = games.ask_yes_no("\n" + self.name + ", do you want a hit? (Y/N): ") return response == "y" def bust(self): print(self.name, "busts.") self.lose() def lose(self): print(self.name, "loses.") def win(self): print(self.name, "wins.") def push(self): print(self.name, "pushes.") class BJ_Dealer(BJ_Hand): """ A Blackjack Dealer. """ def is_hitting(self): return self.total < 17 def bust(self): print(self.name, "busts.") def flip_first_card(self): first_card = self.cards[0] first_card.flip() class BJ_Game(object): """ A Blackjack Game. """ def __init__(self, names): self.players = [] for name in names: player = BJ_Player(name) self.players.append(player) self.dealer = BJ_Dealer("Dealer") self.deck = BJ_Deck() self.deck.populate() self.deck.shuffle() @property def still_playing(self): sp = [] for player in self.players: if not player.is_busted(): sp.append(player) return sp def __additional_cards(self, player): while not player.is_busted() and player.is_hitting(): self.deck.deal([player]) print(player) if player.is_busted(): player.bust() def play(self): # deal initial 2 cards to everyone self.deck.deal(self.players + [self.dealer], per_hand = 2) self.dealer.flip_first_card() # hide dealer's first card for player in self.players: print(player) print(self.dealer) # deal additional cards to players for player in self.players: self.__additional_cards(player) self.dealer.flip_first_card() # reveal dealer's first if not self.still_playing: # since all players have busted, just show the dealer's hand print(self.dealer) else: # deal additional cards to dealer print(self.dealer) self.__additional_cards(self.dealer) if self.dealer.is_busted(): # everyone still playing wins for player in self.still_playing: player.win() else: # compare each player still playing to dealer for player in self.still_playing: if player.total > self.dealer.total: player.win() elif player.total < self.dealer.total: player.lose() else: player.push() # remove everyone's cards for player in self.players: player.clear() self.dealer.clear() def main(): print("\t\tWelcome to Blackjack!\n") names = [] number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) for i in range(number): name = input("Enter player name: ") names.append(names) print() game = BJ_Game(names) again = None while again != "n": game.play() again = games.ask_yes_no("\nDo you want to play again?: ") main() input("\n\nPress the enter key to exit.") Here is the cards module I imported. It is called cards.py # Cards Module # Basic classes for a game with playing cards class Card(object): """ A playing card. """ RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] SUITS = ["c", "d", "h", "s"] def __init__(self, rank, suit, face_up = True): self.rank = rank self.suit = suit self.is_face_up = face_up def __str__(self): if self.is_face_up: rep = self.rank + self.suit else: rep = "XX" return rep def flip(self): self.is_face_up = not self.is_face_up class Hand(object): """ A hand of playing cards. """ def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + "\t" else: rep = "" return rep def clear(self): self.cards = [] def add(self, card): self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card) class Deck(Hand): """ A deck of playing cards. """ def populate(self): for suit in Card.SUITS: for rank in Card.RANKS: self.add(Card(rank, suit)) def shuffle(self): import random random.shuffle(self.cards) def deal(self, hands, per_hand = 1): for rounds in range(per_hand): for hand in hands: if self.cards: top_card = self.cards[0] self.give(top_card, hand) else: print("Can't continue deal. Out of cards!") if __name__ == "__main__": print("This is a module with classes for playing cards.") input("\n\nPress the enter key to exit.") And finally, here is the games module I imported. It is called games.py # Games # Demonstrates module creation class Player(object): """ A player for a game. """ def __init__(self, name, score = 0): self.name = name self.score = score def __str__(self): rep = self.name + ":\t" + str(self.score) return rep def ask_yes_no(question): """Ask a yes or no question.""" response = None while response not in ("y", "n"): response = input(question).lower() return response def ask_number(question, low, high): """Ask for a number within a range.""" response = None while response not in range(low, high): response = int(input(question)) return response if __name__ == "__main__": print("You ran this module directly (and did not 'import' it).") input("\n\nPress the enter key to exit.") Can you please tell me what I did wrong? Your help is greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Nov 6 03:46:13 2011 From: d at davea.name (Dave Angel) Date: Sat, 05 Nov 2011 22:46:13 -0400 Subject: [Tutor] getting nasty TypeError: In-Reply-To: References: Message-ID: <4EB5F4F5.5040902@davea.name> On 11/05/2011 10:02 PM, Nathaniel Trujillo wrote: > Hello. I am currently working with Python version 3.1.1 . I am working out > of the book called Python Programming for the Absolute Beginner Third > Edition which teaches version 3.1.1 . I wrote the following blackjack > program that is on page 275 and I imported the modules that you see below. > First the cards module which is on page 271 and then the games module which > is on page 268. I tried typing everything in exactly the way it is in the > book but when I run the blackjack program that you see below it will first > ask me how many players just like it should, then I tell it how many > players, then it will ask me the names of each player just like it should, > then I tell it the name of each player and after I do that and press enter > I get the following error message. > > Traceback (most recent call last): > File "C:\Python31\blackjack.py", line 184, in > main() > File "C:\Python31\blackjack.py", line 181, in main > game.play() > File "C:\Python31\blackjack.py", line 132, in play > print(player) > File "C:\Python31\blackjack.py", line 34, in __str__ > rep = self.name + "\t" + super(BJ_Hand, self).__str__() > TypeError: can only concatenate list (not "str") to list > Did you omit the __init__() method on some of these classes? For example, I don't see one for BJ_Player, and yet instances are created with a name argument. Anyway, let me point you to a standard debugging technique which should be introduced by page 10 of any such book: You have an error message which is complaining about a specific line, and the error message is complaining about the types of the objects in the expression on that line., So add some print()s, to show type and value (usually repr() is good enough) for the items in the statement. Judging from the wording, self.name is a list, rather than a string as expected. Given that, work backwards to see how it got its value. -- DaveA From steve at pearwood.info Sun Nov 6 03:48:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 06 Nov 2011 13:48:28 +1100 Subject: [Tutor] getting nasty TypeError: In-Reply-To: References: Message-ID: <4EB5F57C.4030002@pearwood.info> Nathaniel Trujillo wrote: > I get the following error message. > > Traceback (most recent call last): > File "C:\Python31\blackjack.py", line 184, in > main() > File "C:\Python31\blackjack.py", line 181, in main > game.play() > File "C:\Python31\blackjack.py", line 132, in play > print(player) > File "C:\Python31\blackjack.py", line 34, in __str__ > rep = self.name + "\t" + super(BJ_Hand, self).__str__() > TypeError: can only concatenate list (not "str") to list > > Here is the blackjack program. It is called blackjack.py Oooh, that was a tricky one! And yet the bug turned out to be a tiny little thing... In your blackjack.py module, in the main() function, change the line names.append(names) to names.append(name) For what it's worth, how I debugged this was to insert the line: print(names) in the main() function, and saw that it was printing [[...]] instead of a list of strings. Once I realised that the main function was screwing up the list of names, it was easy to solve. -- Steven From joebatt at hotmail.co.uk Sun Nov 6 07:31:28 2011 From: joebatt at hotmail.co.uk (Joe Batt) Date: Sun, 6 Nov 2011 06:31:28 +0000 Subject: [Tutor] Printing with no newline :( Message-ID: I am learning Python 3 and programming and am very new so please bear with me? I am writing a program to pull out specific characters in a sequence and then print then out. So far so good however when the characters are printed out they pint on separate lines as opposed to what I want, all on the same line. I have tried \n and just , in the pint statement i.e. print(letterGroup[4],) and print(letterGroup[4]\n) and even print(letterGroup[4],/n)??.. Can anyone help and explain please?.Thank you for line in file: m = re.search(regexp, line) if m: letterGroup=m.group(0) print(letterGroup[4]) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Nov 6 08:41:58 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 06 Nov 2011 08:41:58 +0100 Subject: [Tutor] Printing with no newline :( References: Message-ID: Joe Batt wrote: > I am learning Python 3 and programming and am very new so please bear with > me? > I am writing a program to pull out specific characters in a sequence and > then print then out. So far so good however when the characters are > printed out they pint on separate lines as opposed to what I want, all on > the same line. I have tried \n and just , in the pint statement i.e. > print(letterGroup[4],) and print(letterGroup[4]\n) and even > print(letterGroup[4],/n)??.. Can anyone help and explain please?.Thank you The following arrived in a totally messed up formatting: > for line in file: > m = re.search(regexp, line) > if m: > letterGroup = m.group(0) > print(letterGroup[4]) You can specify what to print after the argument(s) with the end keyword parameter: >>> items = 1, 2, 3 >>> for item in items: ... print(item, end=" ") ... 1 2 3 >>> >>> for item in items: ... print(item, end="") ... 123>>> >>> for item in items: ... print(item, end="WHATEVER") ... 1WHATEVER2WHATEVER3WHATEVER>>> The default for end is of course newline, spelt "\n" in a Python string literal. Use >>> help(print) in the interactive interpreter to learn more about the print() function. From tvssarma.omega9 at gmail.com Sun Nov 6 10:45:58 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Sun, 6 Nov 2011 15:15:58 +0530 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: Message-ID: On 6 November 2011 13:11, Peter Otten <__peter__ at web.de> wrote: > Joe Batt wrote: > > > I am learning Python 3 and programming and am very new so please bear > with > > me? > > I am writing a program to pull out specific characters in a sequence and > > then print then out. So far so good however when the characters are > > printed out they pint on separate lines as opposed to what I want, all on > > the same line. I have tried \n and just , in the pint statement i.e. > > print(letterGroup[4],) and print(letterGroup[4]\n) and even > > print(letterGroup[4],/n)??.. Can anyone help and explain please?.Thank > you > > The following arrived in a totally messed up formatting: > > > for line in file: > > m = re.search(regexp, line) > > if m: > > letterGroup = m.group(0) > > print(letterGroup[4]) > > You can specify what to print after the argument(s) with the end keyword > parameter: > > >>> items = 1, 2, 3 > >>> for item in items: > ... print(item, end=" ") > ... > 1 2 3 >>> > >>> for item in items: > ... print(item, end="") > ... > 123>>> > >>> for item in items: > ... print(item, end="WHATEVER") > Another way of writing the above. for i in items: print item[i], "whatever", "\n" ... > 1WHATEVER2WHATEVER3WHATEVER>>> > > The default for end is of course newline, spelt "\n" in a Python string > literal. Use > > >>> help(print) > > in the interactive interpreter to learn more about the print() function. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Nov 6 11:17:36 2011 From: d at davea.name (Dave Angel) Date: Sun, 06 Nov 2011 05:17:36 -0500 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: Message-ID: <4EB65EC0.1050701@davea.name> On 11/06/2011 04:45 AM, Sarma Tangirala wrote: > On 6 November 2011 13:11, Peter Otten<__peter__ at web.de> wrote: > >> Joe Batt wrote: >> >>> I am learning Python 3 and programming and am very new so please bear >> >>>>> for item in items: >> ... print(item, end="WHATEVER") >> > > Another way of writing the above. > > for i in items: > print item[i], "whatever", "\n" > > Nope. That would put a newline between each iteration, which is explicitly what the OP did not want. More importantly, it'd give a syntax error in Python 3, which the OP carefully specified. -- DaveA From tvssarma.omega9 at gmail.com Sun Nov 6 11:23:23 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Sun, 6 Nov 2011 15:53:23 +0530 Subject: [Tutor] Printing with no newline :( In-Reply-To: <4EB65EC0.1050701@davea.name> References: <4EB65EC0.1050701@davea.name> Message-ID: On 6 November 2011 15:47, Dave Angel wrote: > On 11/06/2011 04:45 AM, Sarma Tangirala wrote: > >> On 6 November 2011 13:11, Peter Otten<__peter__ at web.de> wrote: >> >> Joe Batt wrote: >>> >>> I am learning Python 3 and programming and am very new so please bear >>>> >>> >>> >>> for item in items: >>>>>> >>>>> ... print(item, end="WHATEVER") >>> >>> >> Another way of writing the above. >> >> for i in items: >> print item[i], "whatever", "\n" >> >> >> Nope. That would put a newline between each iteration, which is > explicitly what the OP did not want. More importantly, it'd give a syntax > error in Python 3, which the OP carefully specified. > > -- > > DaveA > > I'm sorry. Didn't notice the python 3 part, I just joined the list and did not look at the OPs post. Sorry about that. Please bear with me on this, but does the following not print "end" for every iteration of "items"? for item in items: print(item, end="") -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From tvssarma.omega9 at gmail.com Sun Nov 6 11:27:57 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Sun, 6 Nov 2011 15:57:57 +0530 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: <4EB65EC0.1050701@davea.name> Message-ID: I am so very sorry for the noise. I was careless in reading the OPs post. On 6 November 2011 15:53, Sarma Tangirala wrote: > > > On 6 November 2011 15:47, Dave Angel wrote: > >> On 11/06/2011 04:45 AM, Sarma Tangirala wrote: >> >>> On 6 November 2011 13:11, Peter Otten<__peter__ at web.de> wrote: >>> >>> Joe Batt wrote: >>>> >>>> I am learning Python 3 and programming and am very new so please bear >>>>> >>>> >>>> >>>> for item in items: >>>>>>> >>>>>> ... print(item, end="WHATEVER") >>>> >>>> >>> Another way of writing the above. >>> >>> for i in items: >>> print item[i], "whatever", "\n" >>> >>> >>> Nope. That would put a newline between each iteration, which is >> explicitly what the OP did not want. More importantly, it'd give a syntax >> error in Python 3, which the OP carefully specified. >> >> -- >> >> DaveA >> >> > > I'm sorry. Didn't notice the python 3 part, I just joined the list and did > not look at the OPs post. Sorry about that. > > Please bear with me on this, but does the following not print "end" for > every iteration of "items"? > > for item in items: > print(item, end="") > > > > > -- > Sarma Tangirala, > Class of 2012, > Department of Information Science and Technology, > College of Engineering Guindy - Anna University > > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Nov 6 12:01:29 2011 From: d at davea.name (Dave Angel) Date: Sun, 06 Nov 2011 06:01:29 -0500 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: <4EB65EC0.1050701@davea.name> Message-ID: <4EB66909.2050706@davea.name> On 11/06/2011 05:23 AM, Sarma Tangirala wrote: > > python 3 > . > > Please bear with me on this, but does the following not print "end" for > every iteration of "items"? > > for item in items: > print(item, end="") > > Sure it does. And the value of end is the empty string. So it prints nothing but the item itself. If you don't supply an argument for 'end', it also prints end, but the default value, which is documented as a newline. So it prints the item followed by a newline. In other words, it prints each item on a separate line. -- DaveA From d at davea.name Sun Nov 6 12:27:47 2011 From: d at davea.name (Dave Angel) Date: Sun, 06 Nov 2011 06:27:47 -0500 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: <4EB65EC0.1050701@davea.name> Message-ID: <4EB66F33.1010008@davea.name> On 11/06/2011 05:23 AM, Sarma Tangirala wrote: > > I just joined the list and did WELCOME to the list. I should have said that first. -- DaveA From tvssarma.omega9 at gmail.com Sun Nov 6 13:07:59 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Sun, 6 Nov 2011 17:37:59 +0530 Subject: [Tutor] Printing with no newline :( In-Reply-To: <4EB66F33.1010008@davea.name> References: <4EB65EC0.1050701@davea.name> <4EB66F33.1010008@davea.name> Message-ID: On 6 November 2011 16:57, Dave Angel wrote: > On 11/06/2011 05:23 AM, Sarma Tangirala wrote: > >> >> > > I just joined the list and did >> > > WELCOME to the list. I should have said that first. > > -- > > DaveA > > Ha! Sorry for the noise again! -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 6 16:39:03 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 06 Nov 2011 15:39:03 +0000 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: <4EB65EC0.1050701@davea.name> Message-ID: On 06/11/11 10:23, Sarma Tangirala wrote: > I'm sorry. Didn't notice the python 3 part, I just joined the list and > did not look at the OPs post. Sorry about that. welcome to the list :-) > Please bear with me on this, but does the following not print "end" for > every iteration of "items"? > > for item in items: > print(item, end="") No, end is a new optional parameter for the print function in Python 3. Recall that in Python2 print was a command whereas in Python 3 it is a function which has a couple of new options: --------------- Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From carroll at tjc.com Sun Nov 6 20:21:26 2011 From: carroll at tjc.com (Terry Carroll) Date: Sun, 6 Nov 2011 11:21:26 -0800 (PST) Subject: [Tutor] regexp In-Reply-To: References: Message-ID: On Sat, 5 Nov 2011, Dinara Vakhitova wrote: > I need to find the words in a corpus, which letters are in the alphabetical > order ("almost", "my" etc.) > I started with matching two consecutive letters in a word, which are in > the alphabetical order, and tried to use this expression: ([a-z])[\1-z], but > it won't work, it's matching any sequence of two letters. I can't figure out > why... Evidently I can't refer to a group like this, can I? But how in this > case can I achieve what I need? First, I agree with the others that this is a lousy task for regular expressions. It's not the tool I would use. But, I do think it's doable, provided the requirement is not to check with a single regular expression. For simplicity's sake, I'll construe the problem as determining whether a given string consists entirely of lower-case alphabetic characters, arranged in alphabetical order. What I would do is set a variable to the lowest permissible character, i.e., "a", and another to the highest permissible character, i.e., "z" (actually, you could just use a constant, for the highest, but I like the symmetry. Then construct a regex to see if a character is within the lowest-permissible to highest-permissible range. Now, iterate through the string, processing one character at a time. On each iteration: - test if your character meets the regexp; if not, your answer is "false"; on pass one, this means it's not lower-case alphabetic; on subsequent passes, it means either that, or that it's not in sorted order. - If it passes, update your lowest permissible character with the character you just processed. - regenerate your regexp using the updated lowest permissible character. - iterate. I assumed lower case alphabetic for simplicity, but you could modify this basic approach with mixed case (e.g., first transforming to all-lower-case copy) or other complications. I don't think there's a problem with asking for help with homework on this list; but you should identify it as homework, so the responders know not to just give you a solution to your homework, but instead provide you with hints to help you solve it. From di.marvellous at gmail.com Sun Nov 6 20:35:57 2011 From: di.marvellous at gmail.com (Dinara Vakhitova) Date: Sun, 6 Nov 2011 23:35:57 +0400 Subject: [Tutor] regexp In-Reply-To: References: Message-ID: Dear Terry, Thank you for your advise, I'll try to implement it. D. 2011/11/6 Terry Carroll > On Sat, 5 Nov 2011, Dinara Vakhitova wrote: > > I need to find the words in a corpus, which letters are in the >> alphabetical >> order ("almost", "my" etc.) >> I started with matching two consecutive letters in a word, which are in >> the alphabetical order, and tried to use this expression: ([a-z])[\1-z], >> but >> it won't work, it's matching any sequence of two letters. I can't figure >> out >> why... Evidently I can't refer to a group like this, can I? But how in >> this >> case can I achieve what I need? >> > > First, I agree with the others that this is a lousy task for regular > expressions. It's not the tool I would use. But, I do think it's doable, > provided the requirement is not to check with a single regular expression. > For simplicity's sake, I'll construe the problem as determining whether a > given string consists entirely of lower-case alphabetic characters, > arranged in alphabetical order. > > What I would do is set a variable to the lowest permissible character, > i.e., "a", and another to the highest permissible character, i.e., "z" > (actually, you could just use a constant, for the highest, but I like the > symmetry. > > Then construct a regex to see if a character is within the > lowest-permissible to highest-permissible range. > > Now, iterate through the string, processing one character at a time. On > each iteration: > > - test if your character meets the regexp; if not, your answer is > "false"; on pass one, this means it's not lower-case alphabetic; on > subsequent passes, it means either that, or that it's not in sorted > order. > - If it passes, update your lowest permissible character with the > character you just processed. > - regenerate your regexp using the updated lowest permissible character. > - iterate. > > I assumed lower case alphabetic for simplicity, but you could modify this > basic approach with mixed case (e.g., first transforming to all-lower-case > copy) or other complications. > > I don't think there's a problem with asking for help with homework on this > list; but you should identify it as homework, so the responders know not to > just give you a solution to your homework, but instead provide you with > hints to help you solve it. > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- *Yours faithfully, Dinara Vakhitova* -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Sun Nov 6 21:59:26 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Sun, 6 Nov 2011 15:59:26 -0500 Subject: [Tutor] Accessing methods in same class Message-ID: Hi. I'm working on a project for my friend, but I'm running into errors. No matter what I do, I can't seem to get one method to execute another method in the same class. Is there a way that I can do this? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Nov 6 22:20:08 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 6 Nov 2011 22:20:08 +0100 Subject: [Tutor] Accessing methods in same class In-Reply-To: References: Message-ID: On Sun, Nov 6, 2011 at 9:59 PM, Max S. wrote: > Hi.? I'm working on a project for my friend, but I'm running into errors. > No matter what I do, I can't seem to get one method to execute another > method in the same class.? Is there a way that I can do this?? Thanks. > Yes, you can do this, and it's very straightforward. However, we cannot help you unless you give us three things: A) The code you're running B) what you expect to happen C) what happened instead A minimal example is best, as I would prefer not to dig through 300 lines of code on my own time. Illustrutate our problem for us. Hugo From lists at solderintheveins.co.uk Sun Nov 6 22:23:03 2011 From: lists at solderintheveins.co.uk (Peter Lavelle) Date: Sun, 06 Nov 2011 21:23:03 +0000 Subject: [Tutor] Accessing methods in same class In-Reply-To: References: Message-ID: <4EB6FAB7.3060900@solderintheveins.co.uk> Hi, Could you post a copy of the code you are working on, so we can help you better with this? Usually, when calling a method in the same class you use the syntax: self.method_name() 'self' refers to an attribute or method within the same class. Sorry, if this does not help you. Regards Peter Lavelle From maxskywalker1 at gmail.com Sun Nov 6 22:28:58 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Sun, 6 Nov 2011 16:28:58 -0500 Subject: [Tutor] Accessing methods in same class In-Reply-To: <4EB6FAB7.3060900@solderintheveins.co.uk> References: <4EB6FAB7.3060900@solderintheveins.co.uk> Message-ID: Oh. Sorry. It's 500 lines, so I'll just post an example. Windows Vista and Python 3, just because I forgot. class K: def __init__(self): doThis() def doThis(self): print("Hi.") k = K() >From what I understand by your help, the code class K: def __init__(self): self.doThis() def doThis(self): print("Hi.") k = K() should work. Thank you for coping with my lack of code to work with. On Sun, Nov 6, 2011 at 4:23 PM, Peter Lavelle wrote: > Hi, > > Could you post a copy of the code you are working on, so we can help you > better with this? > > Usually, when calling a method in the same class you use the syntax: > self.method_name() > > 'self' refers to an attribute or method within the same class. > > Sorry, if this does not help you. > > Regards > > Peter Lavelle > ______________________________**_________________ > 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 pasokan at talentsprint.com Mon Nov 7 04:02:33 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Mon, 7 Nov 2011 08:32:33 +0530 Subject: [Tutor] regexp In-Reply-To: References: Message-ID: IMO the regex is not too bad; I will not use it for this job -- typing a 50+ character string is more painful (and more error prone) than writing 5--10 lines of code. That said, if it made you look at regexes deeply and beyond the simple explanation of what each character (*, ., +) does I think the teacher ended up making you learn something. FInally, the simplest NON-REGEX method is probably isAlphaOrder(s): return sorted(s) == list(s) It is useful learning to add default parameters to this to improve the functionality to case-dependent or case independent modes. Happy learning Asokan Pichai From __peter__ at web.de Mon Nov 7 10:33:24 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Nov 2011 10:33:24 +0100 Subject: [Tutor] regexp References: Message-ID: Asokan Pichai wrote: > IMO the regex is not too bad; I will not use it for this job -- typing > a 50+ character string > is more painful (and more error prone) than writing 5--10 lines of code. Well, you can build the string programmatically: >>> "*".join(string.ascii_lowercase) + "*" 'a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*' From fomcl at yahoo.com Mon Nov 7 11:09:28 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 7 Nov 2011 02:09:28 -0800 (PST) Subject: [Tutor] regexp In-Reply-To: References: Message-ID: <1320660568.18654.YahooMailNeo@web110712.mail.gq1.yahoo.com> Nice solution indeed! Will it also work with accented characters? And how should one incorporate the collating sequence into the solution? By explicitly setting the locale? It might be nice if the outcome is always the same, whereever you are in the world. ? 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: Terry Carroll >To: tutor at python.org >Sent: Sunday, November 6, 2011 8:21 PM >Subject: Re: [Tutor] regexp > >On Sat, 5 Nov 2011, Dinara Vakhitova wrote: > >> I need to find the words in a corpus, which letters are in the alphabetical >> order ("almost", "my" etc.) >> I started with matching two consecutive letters in a word, which are in >> the alphabetical order, and tried to use this expression: ([a-z])[\1-z], but >> it won't work, it's matching any sequence of two letters. I can't figure out >> why... Evidently I can't refer to a group like this, can I? But how in this >> case can I achieve what I need? > >First, I agree with the others that this is a lousy task for regular expressions.? It's not the tool I would use.? But, I do think it's doable, provided the requirement is not to check with a single regular expression. For simplicity's sake, I'll construe the problem as determining whether a given string consists entirely of lower-case alphabetic characters, arranged in alphabetical order. > >What I would do is set a variable to the lowest permissible character, i.e., "a", and another to the highest permissible character, i.e., "z" (actually, you could just use a constant, for the highest, but I like the symmetry. > >Then construct a regex to see if a character is within the lowest-permissible to highest-permissible range. > >Now, iterate through the string, processing one character at a time.? On each iteration: > >- test if your character meets the regexp; if not, your answer is >? "false"; on pass one, this means it's not lower-case alphabetic; on >? subsequent passes, it means either that, or that it's not in sorted >? order. >- If it passes, update your lowest permissible character with the >? character you just processed. >- regenerate your regexp using the updated lowest permissible character. >- iterate. > >I assumed lower case alphabetic for simplicity, but you could modify this basic approach with mixed case (e.g., first transforming to all-lower-case copy) or other complications. > >I don't think there's a problem with asking for help with homework on this list; but you should identify it as homework, so the responders know not to just give you a solution to your homework, but instead provide you with hints to help you solve it. >_______________________________________________ >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 Mon Nov 7 11:48:55 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 07 Nov 2011 11:48:55 +0100 Subject: [Tutor] regexp References: <1320660568.18654.YahooMailNeo@web110712.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > Nice solution indeed! Will it also work with accented characters? And how > should one incorporate the collating sequence into the solution? By > explicitly setting the locale? It might be nice if the outcome is always > the same, whereever you are in the world. This is probably easier to achieve with sorted() than with regular expressions: >>> locale.setlocale(locale.LC_ALL, "") 'de_DE.UTF-8' >>> words = [line.strip() for line in open("/usr/share/dict/ngerman") if len(line)>4] >>> [w for w in words if "".join(sorted(w, key=locale.strxfrm)) == w] ['Abel', 'Abels', 'Abgott', 'Abort', 'Achim', 'Achims', 'Adel', 'Adelns', 'Adels', 'Ader', 'Agio', 'Agios', 'Akku', 'Alls', 'Amor', 'Amors', 'BGHSt', 'BIOS', 'Beet', 'Beginns', 'Behr', 'Behrs', 'Beil', 'Beils', 'Bein', 'Beins', 'Bens', 'Benz', 'Beos', 'Bert', 'Bett', 'Betty', 'Bill', 'Bills', 'Billy', 'Boot', 'Boss', 'Cello', 'Cellos', 'Cent', 'Chintz', 'Chip', 'Chips', 'Chlor', 'Chlors', 'Chor', 'Chors', 'City', 'Clou', 'Cmos', 'Cruz', 'Dekor', 'Dekors', 'Dell', 'Dells', 'Delors', 'Demo', 'Demos', 'Depp', 'Depps', 'Dill', 'Dills', 'Egos', 'Film', 'Films', 'Filz', 'First', 'Flop', 'Flo?', 'Fl?z', 'Forst', 'Gips', 'Gott', 'Hinz', 'Horst', 'Hort', 'Inst', 'Klops', 'Klos', 'Klotz', 'Klo?', 'Knox', 'Kost', 'L?ss', 'Moor', 'Moors', 'Moos', 'Mopp', 'Mopps', 'Mops', 'Most', 'aalst', 'aalt', 'abbei?t', 'aber', 'abesst', 'abfloss', 'abflosst', 'abh?rst', 'abh?rt', 'abl?st', 'acht', 'adeln', 'adelst', 'adelt', 'agil', 'ahmst', 'ahmt', 'ahnst', 'ahnt', 'anno', 'beehrst', 'beehrt', 'beeilst', 'beeilt', 'beginn', 'beginnst', 'beginnt', 'begoss', 'begosst', 'beim', 'beirrst', 'beirrt', 'bei?t', 'bellst', 'bellt', 'biss', 'bisst', 'bist', 'blo?', 'dehnst', 'dehnt', 'dein', 'denn', 'dimm', 'dimmst', 'dimmt', 'dorrst', 'dorrt', 'dort', 'd?rrst', 'd?rrt', 'd?st', 'ehrst', 'ehrt', 'eilst', 'eilt', 'eins', 'einst', 'eint', 'erst', 'esst', 'filmst', 'filmt', 'floss', 'flosst', 'flott', 'fl??t', 'foppst', 'foppt', 'fort', 'gilt', 'goss', 'gosst', 'hisst', 'hopst', 'h?rst', 'h?rt', 'irrst', 'irrt', 'isst', 'lost', 'l?st', '?ffin', '?ffst', '?fft'] From gerhardus.geldenhuis at gmail.com Mon Nov 7 12:52:24 2011 From: gerhardus.geldenhuis at gmail.com (Gerhardus Geldenhuis) Date: Mon, 7 Nov 2011 11:52:24 +0000 Subject: [Tutor] Handling exceptions Message-ID: Hi I am trying to handle exceptions for a xmlrpc class interfacing with cobbler. The exception: xmlrpclib.Fault: and the experimental code. try: server = xmlrpclib.Server("http://192.168.2.11/cobbler_api") #... except xmlrpclib.Fault as detail: print 'xmlrpc error' print detail # print detail.arguments print repr(detail) I don't understand what I am getting from the exception. Do I only get a string and is the above snippet a good/clean/nice way of handling it. If I only get a string then it is likely that I will have to have few if's to handle the various error strings returned. Regards -- Gerhardus Geldenhuis -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Mon Nov 7 13:45:13 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 7 Nov 2011 13:45:13 +0100 Subject: [Tutor] Handling exceptions In-Reply-To: References: Message-ID: On Mon, Nov 7, 2011 at 12:52 PM, Gerhardus Geldenhuis wrote: > Hi > I am trying to handle exceptions for a xmlrpc class interfacing with > cobbler. > The exception: > ?xmlrpclib.Fault: test_profile'"> > > and the experimental code. > ? try: > ? ? server = xmlrpclib.Server("http://192.168.2.11/cobbler_api") > ? ? #... > ? except xmlrpclib.Fault as detail: > ? ? print 'xmlrpc error' > ? ? print detail > # ? ?print detail.arguments > ? ? print repr(detail) > I don't understand what I am getting from the exception. Do I only get a > string and is the above snippet a good/clean/nice way of handling it. If I > only get a string then it is likely that I will have to have ?few if's to > handle the various error strings returned. > Regards > -- > Gerhardus Geldenhuis > It depends on the specific library used. Generally, the type of the exception, sometimes in conjunction with the error message, will tell you what went wrong. In this case, the xmlrpclib.Fault exception represents all XML-RPC Faults, and there are faultCode and faultString attributes to figure out where it went wrong. See also the xmlrpclib documentation (docs are your friend!) http://docs.python.org/library/xmlrpclib.html#fault-objects HTH, Hugo From steve at pearwood.info Mon Nov 7 17:01:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Nov 2011 03:01:15 +1100 Subject: [Tutor] Handling exceptions In-Reply-To: References: Message-ID: <4EB800CB.3060303@pearwood.info> Gerhardus Geldenhuis wrote: > try: > server = xmlrpclib.Server("http://192.168.2.11/cobbler_api") > #... > except xmlrpclib.Fault as detail: > > print 'xmlrpc error' > print detail > # print detail.arguments > print repr(detail) > > I don't understand what I am getting from the exception. Do I only get a > string and is the above snippet a good/clean/nice way of handling it. If I > only get a string then it is likely that I will have to have few if's to > handle the various error strings returned. No, that is the wrong way of handling exceptions. You should not catch exceptions only to print them. (Actually, there are a few times where it *is* appropriate to catch and print exceptions by hand, as you have done, but they are rare.) In general, the only reason to catch an exception is to recover from it, then to proceed. E.g. "if it fails, try something different". In the above, you don't recover from the failure to connect to the server. You print some diagnostic information, but then your code tries to continue without a defined server. (If your code above is only for experimentation, that's fine.) If you aren't able to recover from an exception, normally the right thing to do is... just don't catch it at all. In this case, just write this: server = xmlrpclib.Server("http://192.168.2.11/cobbler_api") without a try...except block, and if an exception is raised, you will get a traceback automatically printed showing you: * the type of error * an error message * the line number of the code that failed * the full stack trace of each operation leading up to the error Learning to read stack traces is not hard, but it is absolutely vital to being a good Python coder. In particular, you should never programmatically make decisions about an error based on the error message: # Don't do this! try: x = mylist.index(None) except ValueError as e: if e.message == "x not in list": process_failure() The problem is that the error message is not part of the promised interface of the language. It could change suddenly, without warning, at any time. Just because the message is "x not in list" today, doesn't mean it will be tomorrow, or next week, or in two minutes. The only promise being made is that the error message will be useful to a human reader (or at least, it *should* be useful). The exact wording is certainly not promised, and so cannot be relied upon. -- Steven From rhettnaxel at gmail.com Mon Nov 7 17:32:32 2011 From: rhettnaxel at gmail.com (Alexander) Date: Mon, 7 Nov 2011 11:32:32 -0500 Subject: [Tutor] Having trouble visiting the subscribers list. In-Reply-To: <4EB5E1BC.8060804@pearwood.info> References: <4EB5E1BC.8060804@pearwood.info> Message-ID: On Sat, Nov 5, 2011 at 9:24 PM, Steven D'Aprano wrote: > Nathaniel Trujillo wrote: > >> I recently subscribed to tutor and I am trying to visit the subscribers >> list so I can ask a question but I wasn't given an admin address. Not only >> that but I don't know what an admin address is. Your help is greatly >> appreciated. >> > >From the website: http://mail.python.org/mailman/listinfo/tutor (*The subscribers list is only available to the list administrator.*) And for good reason. We ( you and I and other members of the list ) and not admins. Alexander > Why do you want to see the list of subscribers? That's private information. > > If you want to ask a question, ask it by sending an email to < > tutor at python.org>. > -- > 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 tvssarma.omega9 at gmail.com Mon Nov 7 17:42:37 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Mon, 7 Nov 2011 22:12:37 +0530 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: <4EB65EC0.1050701@davea.name> Message-ID: On 6 November 2011 21:09, Alan Gauld wrote: > On 06/11/11 10:23, Sarma Tangirala wrote: > > I'm sorry. Didn't notice the python 3 part, I just joined the list and >> did not look at the OPs post. Sorry about that. >> > > welcome to the list :-) > > > Please bear with me on this, but does the following not print "end" for >> every iteration of "items"? >> >> for item in items: >> print(item, end="") >> > > No, end is a new optional parameter for the print function in Python 3. > Recall that in Python2 print was a command whereas in Python 3 it is a > function which has a couple of new options: > > Thank you! > --------------- > Help on built-in function print in module builtins: > > print(...) > print(value, ..., sep=' ', end='\n', file=sys.stdout) > > Prints the values to a stream, or to sys.stdout by default. > Optional keyword arguments: > file: a file-like object (stream); defaults to the current sys.stdout. > sep: string inserted between values, default a space. > end: string appended after the last value, default a newline. > > > > -- > Alan G > 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 > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Mon Nov 7 18:21:35 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 7 Nov 2011 12:21:35 -0500 Subject: [Tutor] Printing with no newline :( In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF64F350@EMARC112VS01.exchad.jpmchase.net> >> for line in file: >> m = re.search(regexp, line) >> if m: >> letterGroup = m.group(0) >> print(letterGroup[4]) >You can specify what to print after the argument(s) with the end keyword >parameter: >>>> items = 1, 2, 3 >>>> for item in items: >... print(item, end=" ") >... Alternatively you could do the following. letterGroups = [] for line in file: m = re.search(regexp, line) if m: letterGroups.append( m.group(0)[4] ) print( ' '.join( letterGroups ) ) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From roadierich at googlemail.com Tue Nov 8 00:23:04 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 7 Nov 2011 23:23:04 +0000 Subject: [Tutor] Single line webserver Message-ID: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> Hi all, I was part of this list a couple of years ago, and a recent discussion at a python dojo brought to mind something I'd seen then: a one-liner (potentially single statement) webserver. I'm pretty sure it was posted to this list, but I can't find it in the archives, and a google search is similarly lacking in relevant results. I was wondering if anyone (maybe the original author?) had a copy they could send me. Rich "RoadieRich" Lovely There are 10 types of people in the world: Those who know binary, Those who do not, And those who are off by one. From steven.rafael.turner at gmail.com Tue Nov 8 00:32:23 2011 From: steven.rafael.turner at gmail.com (Rafael Turner) Date: Mon, 7 Nov 2011 17:32:23 -0600 Subject: [Tutor] Writing the Map function as a oneliner Message-ID: Hello, I am trying to write the map function as a oneliner. I currently have implement map as a list comprehension: map = lambda F,li: [F(x) for x in li] But I would like to make recursive version. Here is what I was thinking: I can write map as def pyMap(F,li): if li == []: return [] else: return [F(li[0])] + map2(F, li[1:]) I can logical encode an if-then-else structure as follows: Let Q be the result of the following IF,THEN, ELSE conditional structure: If(S): Then: A Else: B We can implement this only using logical constructors. Q = (A AND S) OR (B AND NOT S) where: S is the input for the If condition, A is the input to Then subexpression B is the input for the Else subexpression Q is the output of the entire If-Then-Else expression. So, I tried: def pyMap2(F, li): def ifFun(P,eq): return li == [] return ([] and ifFun(li,[])) or ([F(li[0])] + pyMap2(F, li[1:]) and not []) But it's no use. pyMap works fine but pyMap2 does not. I saved the above code as map.py and ran it in the interpreter. >>> import map >>> map.pyMap2(lambda x: x + 2, [1,2,3]) Traceback (most recent call last): File "", line 1, in File "map.py", line 15, in pyMap2 return ([] and fIF(li,[])) or ([F(li[0])] + pyMap2(F, li[1:]) and not []) File "map.py", line 15, in pyMap2 return ([] and fIF(li,[])) or ([F(li[0])] + pyMap2(F, li[1:]) and not []) File "map.py", line 15, in pyMap2 return ([] and fIF(li,[])) or ([F(li[0])] + pyMap2(F, li[1:]) and not []) File "map.py", line 15, in pyMap2 return ([] and fIF(li,[])) or ([F(li[0])] + pyMap2(F, li[1:]) and not []) IndexError: list index out of range Thank you for your help, Rafael From steve at pearwood.info Tue Nov 8 01:26:31 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 08 Nov 2011 11:26:31 +1100 Subject: [Tutor] Single line webserver In-Reply-To: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> References: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> Message-ID: <4EB87737.8020500@pearwood.info> Rich Lovely wrote: > Hi all, I was part of this list a couple of years ago, and a recent discussion at a python dojo brought to mind something I'd seen then: a one-liner (potentially single statement) webserver. I'm pretty sure it was posted to this list, but I can't find it in the archives, and a google search is similarly lacking in relevant results. > > I was wondering if anyone (maybe the original author?) had a copy they could send me. https://duckduckgo.com/html/?q=python%20one%2Dliner%20web%20server Hits #2 #3 and #4 are: http://tobyho.com/2010/04/26/one-liner-webserver-with/ http://www.garyrobinson.net/2004/03/one_line_python.html http://aroberge.blogspot.com/2010/08/my-favourite-python-one-liner.html -- Steven From alan.gauld at btinternet.com Tue Nov 8 01:27:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Nov 2011 00:27:56 +0000 Subject: [Tutor] Writing the Map function as a oneliner In-Reply-To: References: Message-ID: On 07/11/11 23:32, Rafael Turner wrote: > Hello, > > I am trying to write the map function as a oneliner.... > But I would like to make recursive version. Here is what I was thinking: > > I can write map as > > def pyMap(F,li): > if li == []: > return [] > else: > return [F(li[0])] + map2(F, li[1:]) > Using the conditional expression it is nearly trivial to convert your function to a one-liner: def pyMap(F,li): return [] if li == [] else [F(li[0])] + pyMap(F,li[1:]) which becomes pyMap = lambda F, li: [] if li == [] else [F(li[0])] + pyMap(F,li[1:]) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 8 01:29:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Nov 2011 00:29:29 +0000 Subject: [Tutor] Single line webserver In-Reply-To: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> References: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> Message-ID: On 07/11/11 23:23, Rich Lovely wrote: > a one-liner (potentially single statement) webserver. There is a python module in the standard library that implements a basic webserver, presumably it was based on that. Try the docs for the library modules... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ljmamoreira at gmail.com Tue Nov 8 03:45:48 2011 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Tue, 8 Nov 2011 02:45:48 +0000 Subject: [Tutor] tkfiledialogs and hidden files Message-ID: <201111080245.48952.ljmamoreira@gmail.com> Hello! Is there any way to configure tkFileDialogs so that they don't display hidden files? Thanks. Ze Amoreira -------------- next part -------------- An HTML attachment was scrubbed... URL: From hothottrott at gmail.com Tue Nov 8 05:30:55 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Mon, 7 Nov 2011 21:30:55 -0700 Subject: [Tutor] Question about GUI applications. Message-ID: I just wrote the following GUI application. How do I get rid of the 7k in the upper left hand corner and how to I put other stuff there like say a picture of someone. Thanks for the help. Here is the GUI application. It is called mad_lib.py.py # Mad Lib # Create a story based on user input from tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): """ Initialize Frame. """ super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get story infomation and to display story. """ # create instruction label Label(self, text = "Enter information for a new story").grid(row = 0, column = 0, columnspan = 2, sticky = W) # create a label and text entry for the name of a person Label(self, text = "Person: ").grid(row = 1, column = 0, sticky = W) self.person_ent = Entry(self) self.person_ent.grid(row = 1, column = 1, sticky = W) # create a label and text entry for a plural noun Label(self, text = "Plural Noun:").grid(row = 2, column = 0, sticky = W) self.noun_ent = Entry(self) self.noun_ent.grid(row = 2, column = 1, sticky = W) # create a label and text entry for a verb Label(self, text = "Verb:").grid(row = 3, column = 0, sticky = W) self.verb_ent = Entry(self) self.verb_ent.grid(row = 3, column = 1, sticky = W) # create a label for adjectives check buttons Label(self, text = "Adjective(s):").grid(row = 4, column = 0, sticky = W) # create itchy check button self.is_itchy = BooleanVar() Checkbutton(self, text = "itchy", variable = self.is_itchy).grid(row = 4, column = 1, sticky = W) # create joyous check button self.is_joyous = BooleanVar() Checkbutton(self, text = "joyous", variable = self.is_joyous).grid(row = 4, column = 2, sticky = W) # create electric check button self.is_electric = BooleanVar() Checkbutton(self, text = "electric", variable = self.is_electric).grid(row = 4, column = 3, sticky = W) # create a label for body parts radio buttons Label(self, text = "Body Part:").grid(row = 5, column = 0, sticky = W) # create variable for single body part self.body_part = StringVar() self.body_part.set(None) # create body part radio buttons body_parts = ["bellybutton", "big toe", "medulla oblongata"] column = 1 for part in body_parts: Radiobutton(self, text = part, variable = self.body_part, value = part).grid(row = 5, column = column, sticky = W) column += 1 # create a submit button Button(self, text = "Click for story", command = self.tell_story).grid(row = 6, column = 0, sticky = W) self.story_txt = Text(self, width = 75, height = 10, wrap = WORD) self.story_txt.grid(row = 7, column = 0, columnspan = 4) def tell_story(self): """ Fill text box with new story based on user input. """ # gets values fom the GUI person = self.person_ent.get() noun = self.noun_ent.get() verb = self.verb_ent.get() adjectives = "" if self.is_itchy.get(): adjectives += "itchy, " if self.is_joyous.get(): adjectives += "joyous, " if self.is_electric.get(): adjectives += "electric, " body_part = self.body_part.get() # create the story story = "The famous explorer " story += person story += " had nearly given up a life-long quest to find The Lost City of " story += noun.title() story += " when one day, the " story += noun story += " found " story += person + "." story += "A strong, " story += adjectives story += "peculiar feeling overwhelmed the explorer. " story += "After all this time, the quest was finally over. A tear came to " story += person + "'s " story += body_part + ". " story += "And then, the " story += noun story += " promptly devoured " story += person + "." story += "The moral of the story? Be careful what you " story += verb story += " for." # display the story self.story_txt.delete(0.0, END) self.story_txt.insert(0.0, story) # main root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Nov 8 06:34:21 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 08 Nov 2011 16:34:21 +1100 Subject: [Tutor] Single line webserver In-Reply-To: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> References: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> Message-ID: On 11/08/2011 10:23 AM, Rich Lovely wrote: > Hi all, I was part of this list a couple of years ago, and a recent discussion at a python dojo brought to mind something I'd seen then: a one-liner (potentially single statement) webserver. I'm pretty sure it was posted to this list, but I can't find it in the archives, and a google search is similarly lacking in relevant results. > > I was wondering if anyone (maybe the original author?) had a copy they could send me. > Windows Command Prompt gotta be the most powerful language on earth, it has a full-blown server in a single word: C:\Program Files\Apache Software Foundation\Apache2.2\bin> httpd.exe From alan.gauld at btinternet.com Tue Nov 8 09:39:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Nov 2011 08:39:43 +0000 Subject: [Tutor] Question about GUI applications. In-Reply-To: References: Message-ID: On 08/11/11 04:30, Nathaniel Trujillo wrote: > I just wrote the following GUI application. How do I get rid of the 7k > in the upper left hand corner and how to I put other stuff there like > say a picture of someone. Thanks for the help. If you are using Windows I don't think you can, due to a bug in the underlying Tk libraries. If you are using Linux/MacOS then there is a function to replace the control icon. I can't recall what it is, but its similar to the one used for setting the title text on the Window, one of the wm_xxxxx calls. But you might get a better response asking on the Tkinter mailing list... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From roadierich at googlemail.com Tue Nov 8 13:18:45 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Tue, 8 Nov 2011 12:18:45 +0000 Subject: [Tutor] Tutor Digest, Vol 93, Issue 38 In-Reply-To: References: Message-ID: On 8 Nov 2011, at 02:45, tutor-request at python.org wrote: > > Message: 4 > Date: Tue, 08 Nov 2011 11:26:31 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Single line webserver > Message-ID: <4EB87737.8020500 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Rich Lovely wrote: >> Hi all, I was part of this list a couple of years ago, and a recent discussion at a python dojo brought to mind something I'd seen then: a one-liner (potentially single statement) webserver. I'm pretty sure it was posted to this list, but I can't find it in the archives, and a google search is similarly lacking in relevant results. >> >> I was wondering if anyone (maybe the original author?) had a copy they could send me. > > https://duckduckgo.com/html/?q=python%20one%2Dliner%20web%20server > > Hits #2 #3 and #4 are: > > http://tobyho.com/2010/04/26/one-liner-webserver-with/ > http://www.garyrobinson.net/2004/03/one_line_python.html > http://aroberge.blogspot.com/2010/08/my-favourite-python-one-liner.html > > > > -- > Steven I'd like to draw your attention to my original message: "a google search is similarly lacking in relevant results." Shouldn't it be clear from how easy it is to find SimpleHttp that it clearly /isn't/ what I'm looking for? Perhaps I should have mentioned that, but I thought I'd made it clear I'd tried a websearch. The code I remember was a Socket-based webserver, written in one - albeit rather long - line. Rich "RoadieRich" Lovely There are 10 types of people in the world: Those who know binary, Those who do not, And those who are off by one. From d at davea.name Tue Nov 8 13:38:19 2011 From: d at davea.name (Dave Angel) Date: Tue, 08 Nov 2011 07:38:19 -0500 Subject: [Tutor] tkfiledialogs and hidden files In-Reply-To: <201111080245.48952.ljmamoreira@gmail.com> References: <201111080245.48952.ljmamoreira@gmail.com> Message-ID: <4EB922BB.9050504@davea.name> On 11/07/2011 09:45 PM, Jose Amoreira wrote: > Hello! > Is there any way to configure tkFileDialogs so that they don't display hidden > files? > Thanks. > Ze Amoreira > I can't help you with tk, but maybe I can help you ask a better question. "Hidden files" means a different thing on various operating systems. In Linux, it means a name with a leading period. In Windows, it can mean a file with one or more of several attributes. There's even some ambiguity in the latter. Please specify (to everyone else, not to me) what environment you're targeting in as much detail as possible. -- DaveA From ljmamoreira at gmail.com Tue Nov 8 13:56:08 2011 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Tue, 8 Nov 2011 12:56:08 +0000 Subject: [Tutor] tkfiledialogs and hidden files In-Reply-To: <4EB922BB.9050504@davea.name> References: <201111080245.48952.ljmamoreira@gmail.com> <4EB922BB.9050504@davea.name> Message-ID: <201111081256.08414.ljmamoreira@gmail.com> On Tuesday, November 08, 2011 12:38:19 PM Dave Angel wrote: > On 11/07/2011 09:45 PM, Jose Amoreira wrote: > > Hello! > > Is there any way to configure tkFileDialogs so that they don't display > > hidden files? > > Thanks. > > Ze Amoreira > > I can't help you with tk, but maybe I can help you ask a better question. > > "Hidden files" means a different thing on various operating systems. In > Linux, it means a name with a leading period. In Windows, it can mean a > file with one or more of several attributes. There's even some > ambiguity in the latter. > > Please specify (to everyone else, not to me) what environment you're > targeting in as much detail as possible. Yes, I'm sorry. I meant hidden files in Linux. It's just that my home directory contains a lot of those files and directories and I'd rather not need to scroll the dialog display to get to the files/dirs that I usually want to select. Anyway, thank s, Dave. Ze Amoreira -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Nov 8 15:09:53 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 8 Nov 2011 08:09:53 -0600 Subject: [Tutor] tkfiledialogs and hidden files In-Reply-To: <201111081256.08414.ljmamoreira@gmail.com> References: <201111080245.48952.ljmamoreira@gmail.com> <4EB922BB.9050504@davea.name> <201111081256.08414.ljmamoreira@gmail.com> Message-ID: On Tue, Nov 8, 2011 at 6:56 AM, Jose Amoreira wrote: > ** > > On Tuesday, November 08, 2011 12:38:19 PM Dave Angel wrote: > > > On 11/07/2011 09:45 PM, Jose Amoreira wrote: > > > > Is there any way to configure tkFileDialogs so that they don't display > > > > hidden files? > > "Hidden files" means a different thing on various operating systems. In > > > Linux, it means a name with a leading period. In Windows, it can mean a > > > file with one or more of several attributes. There's even some > > > ambiguity in the latter. > > > > > > Please specify (to everyone else, not to me) what environment you're > > > targeting in as much detail as possible. > > > Yes, I'm sorry. > > I meant hidden files in Linux. > > It's just that my home directory contains a lot of those files and > directories and I'd rather not need to scroll the dialog display to get to > the files/dirs that I usually want to select. > If you know exactly what type of files you're looking for, or that it will be in a specific set of extensions, you can at least get rid of the files by specifying the filetypes=[(label1, extension1), (label2, extension2), ...] argument. Other than that, it doesn't look possible to hide the folders. http://mail.python.org/pipermail/python-list/2003-April/199226.html It's not the ideal solution, but you could probably roll your own (as recommended in the referenced post) that gives you the ability to filter based on filename (perhaps using a regex, or at least giving you the "^" not character). HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From nikunjbadjatya at gmail.com Tue Nov 8 16:42:06 2011 From: nikunjbadjatya at gmail.com (Nikunj Badjatya) Date: Tue, 8 Nov 2011 21:12:06 +0530 Subject: [Tutor] Progress Bar In-Reply-To: <1f9f4a778400de4fa3d57d2e74226be3@win-w4> References: <1f9f4a778400de4fa3d57d2e74226be3@win-w4> Message-ID: Hi All, I am writing an installer in Python and Powershell which will be used to install Virtual Machines at specific locations. The main script is in Python and main.py inturn calls Powershell scripts (.PS1). It is complete console based and no gui. I am using Python 2.7 I was thinking to have a progress bar in my installer. similar to the way when we install something in linux via console and a progress bar comes as "[##### ] 40% " etc. I also saw and ran couple of examples based in Python on the net. http://code.google.com/p/python-progressbar/source/browse/examples.py My question is, How do I integrate it with Powershell scripts.? I am using popen() to run powershell scripts. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Tue Nov 8 16:56:58 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 08 Nov 2011 07:56:58 -0800 Subject: [Tutor] Question about GUI applications. In-Reply-To: References: Message-ID: <4EB9514A.2050206@alchemy.com> On 08-Nov-11 00:39, Alan Gauld wrote: > On 08/11/11 04:30, Nathaniel Trujillo wrote: >> I just wrote the following GUI application. How do I get rid of the 7k >> in the upper left hand corner and how to I put other stuff there like >> say a picture of someone. Thanks for the help. > > If you are using Windows I don't think you can, due to a bug in the > underlying Tk libraries. If you are using Linux/MacOS then there is a > function to replace the control icon. > > I can't recall what it is, but its similar to the one used for setting > the title text on the Window, one of the wm_xxxxx calls. > > But you might get a better response asking on the Tkinter mailing list... > I have an app I'm developing and running successfully on Windows (as well as OSX and Linux). At least in this case it is able to replace the application icon in place of the default "TK" one. The code I use is: root = Tkinter.Tk() root.iconbitmap(default=ico_image_filename) (on Linux I use root.iconbitmap(bitmap='@'+xbm_filename)) -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From ranceh at gmail.com Tue Nov 8 17:28:01 2011 From: ranceh at gmail.com (Rance Hall) Date: Tue, 8 Nov 2011 10:28:01 -0600 Subject: [Tutor] Progress Bar In-Reply-To: References: <1f9f4a778400de4fa3d57d2e74226be3@win-w4> Message-ID: On Tue, Nov 8, 2011 at 9:42 AM, Nikunj Badjatya wrote: > Hi All, > I am writing an installer in Python and Powershell which will be used to > install Virtual Machines at specific locations. > The main script is in Python and main.py inturn calls Powershell scripts > (.PS1). > It is complete console based and no gui. > I am using Python 2.7 > I was thinking to have a progress bar in my installer. similar to the way > when we install something in linux via console?and a progress bar comes as > "[##### ? ? ? ? ? ? ? ? ] 40% " > etc. > I also saw and ran couple of examples based in Python on the net. > http://code.google.com/p/python-progressbar/source/browse/examples.py > > My question is, How do I integrate it with Powershell scripts.? > I am using popen() to run powershell scripts. > The easiest way to do this is manually advance your progress bar with each powershell script completion. for example if there are four *ps1 scripts, then completing each represents an additional 25% completion. popen(ps script 1) advance progress meter to 25% popen(ps script 2) advance progress meter to 50% ..... to get anything more sophisticated you have to have the powershell scripts report something back to the main python script but I don't have a feel for how easy/hard that would be. I doubt that the popen call allows much more than waiting for the called script to exit. You could have the power shell scripts keep track of their own progress with a log file or some such and then a thread in your python installer could watch those log files and manually advance your progress meter based on log file entries. HTH Rance From cranky.frankie at gmail.com Tue Nov 8 17:56:23 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 8 Nov 2011 11:56:23 -0500 Subject: [Tutor] string split function - how to tell how many splits Message-ID: How do you tell how many splits the string split funtion returns? For example: field = 'The Good Wife ;' # a string separated by spaces new_list = field.split(' ') # create a list of space delimited elements print (new_list[0]) # print the first one print (new_list[1]) # print the second one print (new_list[2]) # print the third one print (new_list[3]) # print the fourth one print (new_list[4]) # print the fifth one The last line above causes an error. I plan on reading in a file where I don't know what the number of splits will be. How can I find out before trying to access an out of range index? -- Frank L. "Cranky Frankie" Palmeri, Guilderland, NY, USA ? ? ? ? ? ? ?Risible Riding Raconteur & Writer Don't sweat the petty things, and don't pet the sweaty things. From joel.goldstick at gmail.com Tue Nov 8 18:04:48 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 8 Nov 2011 12:04:48 -0500 Subject: [Tutor] string split function - how to tell how many splits In-Reply-To: References: Message-ID: On Tue, Nov 8, 2011 at 11:56 AM, Cranky Frankie wrote: > How do you tell how many splits the string split funtion returns? For > example: > > field = 'The Good Wife ;' # a string separated by spaces > new_list = field.split(' ') # create a list of space delimited elements > print (new_list[0]) # print the first one > print (new_list[1]) # print the second one > print (new_list[2]) # print the third one > print (new_list[3]) # print the fourth one > print (new_list[4]) # print the fifth one > > > The last line above causes an error. I plan on reading in a file where > I don't know what the number of splits will be. How can I find out > before trying to access an out of range index? > > > > -- > Frank L. "Cranky Frankie" Palmeri, Guilderland, NY, USA > Risible Riding Raconteur & Writer > Don't sweat the petty things, and don't pet the sweaty things. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor you can find the length of the list with the len() function >>> field = 'The Good Wife ;' # a string separated by spaces >>> new_list = field.split(' ') # create a list of space delimited elements >>> len(new_list) 4 -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 8 18:06:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 09 Nov 2011 04:06:44 +1100 Subject: [Tutor] string split function - how to tell how many splits In-Reply-To: References: Message-ID: <4EB961A4.6060503@pearwood.info> Cranky Frankie wrote: > How do you tell how many splits the string split funtion returns? For example: > > field = 'The Good Wife ;' # a string separated by spaces > new_list = field.split(' ') # create a list of space delimited elements > print (new_list[0]) # print the first one > print (new_list[1]) # print the second one > print (new_list[2]) # print the third one > print (new_list[3]) # print the fourth one > print (new_list[4]) # print the fifth one > > > The last line above causes an error. I plan on reading in a file where > I don't know what the number of splits will be. How can I find out > before trying to access an out of range index? text = 'Nobody expects the Spanish Inquisition!!!' words = text.split(' ') number_of_words = len(words) print words[number_of_words - 1] # prints "Inquisition!!!" -- Steven From steve at pearwood.info Tue Nov 8 18:07:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 09 Nov 2011 04:07:45 +1100 Subject: [Tutor] Single line webserver [was: Tutor Digest, Vol 93, Issue 38] In-Reply-To: References: Message-ID: <4EB961E1.60800@pearwood.info> Rich Lovely wrote: > I'd like to draw your attention to my original message: "a google > search is similarly lacking in relevant results." Shouldn't it be > clear from how easy it is to find SimpleHttp that it clearly /isn't/ > what I'm looking for? Perhaps I should have mentioned that, but I > thought I'd made it clear I'd tried a websearch. Yes, you should have mentioned that SimpleHttp was not the one-liner you were looking for. That would have been useful to know :) Your request was for a one-liner web server, and you claimed to have done a search which came up with nothing relevant. Since a simple search did in fact come up with an apparently relevant one-liner, the most obvious conclusions were that your search skills are very lousy, or that you were mistaken (i.e. lying) about having attempted to search first. Coming from an apparent first-time poster with no reputation I was aware of, neither would have surprised me. I'm glad that neither is actually the case. > The code I remember was a Socket-based webserver, written in one - > albeit rather long - line. That would have been useful information to have mentioned at the time. For what little it's worth, here's a 15 line socket-based web server: import socket template = ('HTTP/1.0 200 OK\n\nWelcome %s!' '

Header...

...and body.
Your request was: ' '"%s"') sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 8080)) sock.listen(1) print "Listening on port 8080" while True: client, address = sock.accept() cfile = client.makefile('rw', 0) cfile.write(template % (str(address), cfile.readline().strip())) cfile.close() client.close() Save this as "web.py", run "python web.py", and then in your browser go to http://localhost:8080 Turning this into a one-liner is left as an exercise. This may be useful: http://pauldotcom.com/2011/10/python-one-line-shell-code.html P.S. I note you're replying to the digest. Thank you for trimming your reply, rather than including the entire digest, but please note the request at the top of each digest: When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." -- Steven From d at davea.name Tue Nov 8 18:08:03 2011 From: d at davea.name (Dave Angel) Date: Tue, 08 Nov 2011 12:08:03 -0500 Subject: [Tutor] string split function - how to tell how many splits In-Reply-To: References: Message-ID: <4EB961F3.4090209@davea.name> On 11/08/2011 11:56 AM, Cranky Frankie wrote: > How do you tell how many splits the string split funtion returns? For example: > > field = 'The Good Wife ;' # a string separated by spaces > new_list = field.split(' ') # create a list of space delimited elements > print (new_list[0]) # print the first one > print (new_list[1]) # print the second one > print (new_list[2]) # print the third one > print (new_list[3]) # print the fourth one > print (new_list[4]) # print the fifth one > > > The last line above causes an error. I plan on reading in a file where > I don't know what the number of splits will be. How can I find out > before trying to access an out of range index? > > In general, the len() function tells you how many elements a collection has, and in particular split() returns a list, which is supported by len(). But for the printing example, you could also do: for item in newlist: print(item) -- DaveA From ramit.prasad at jpmorgan.com Tue Nov 8 19:16:46 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 8 Nov 2011 13:16:46 -0500 Subject: [Tutor] Single line webserver In-Reply-To: References: <9F00E52C-47F9-414C-8A34-AB16D43E364B@googlemail.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF6DE395@EMARC112VS01.exchad.jpmchase.net> >Windows Command Prompt gotta be the most powerful language on earth, it >has a full-blown server in a single word: >C:\Program Files\Apache Software Foundation\Apache2.2\bin> httpd.exe Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Tue Nov 8 23:01:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Nov 2011 22:01:25 +0000 Subject: [Tutor] Question about GUI applications. In-Reply-To: <4EB9514A.2050206@alchemy.com> References: <4EB9514A.2050206@alchemy.com> Message-ID: On 08/11/11 15:56, Steve Willoughby wrote: >> I can't recall what it is, but its similar to the one used for setting >> the title text on the Window, one of the wm_xxxxx calls. > > I have an app I'm developing and running successfully on Windows ... > > root = Tkinter.Tk() > root.iconbitmap(default=ico_image_filename) Yep, that's the one I was thinking of. Looks like they must have fixed the problem. Last time I tried it ran without errors but didn't change the icon - that would have been with Python 2.2-3(ish) on Windows XP. It was a known issue on the Tk forums... Hmm, Googling, it looks like it was probably fixed in Tk 8.4. Which is a wee while ago! :-) Although I see it still being described as a bug up until April 2008 at least. The suggested "fix" being to edit the icon in wish.exe using a resource editor - yikes! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 8 23:06:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 08 Nov 2011 22:06:39 +0000 Subject: [Tutor] Progress Bar In-Reply-To: References: <1f9f4a778400de4fa3d57d2e74226be3@win-w4> Message-ID: On 08/11/11 15:42, Nikunj Badjatya wrote: > I am writing an installer in Python and Powershell which will be used to > install Virtual Machines at specific locations. I see you got a reply from Rance. But since this list is for folks learning the python language you would be more likely to get results on a more general Python users list (or even a Powershell specific list if such exists) such as the main comp.lang.python group. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jae.esmail at gmail.com Tue Nov 8 23:14:23 2011 From: jae.esmail at gmail.com (Jihad Esmail) Date: Tue, 8 Nov 2011 17:14:23 -0500 Subject: [Tutor] Beginning Python From Perl Message-ID: Hi! I am new to this list so stick with me. I've recently taken interest in learning Python. I have already learned Perl. How should I go about learning Python from Perl? Please help. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From pdc.cse at gmail.com Tue Nov 8 23:22:39 2011 From: pdc.cse at gmail.com (Peter Camilleri) Date: Wed, 9 Nov 2011 09:22:39 +1100 Subject: [Tutor] Beginning Python From Perl In-Reply-To: References: Message-ID: I too learnt perl first and I came to learn python through the google python class http://code.google.com/edu/languages/google-python-class/ It has video lectures and exercises which should help you illustrate the basic concepts in each video. I am by no means an python expert, but I feel that series gave me enough of an introduction to python to be able to go off and learn anything else I needed to know about the language from online tutorials. On Wed, Nov 9, 2011 at 9:14 AM, Jihad Esmail wrote: > Hi! I am new to this list so stick with me. I've recently taken interest in > learning Python. I have already learned Perl. How should I go about learning > Python from Perl? Please help. Thanks! > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From hothottrott at gmail.com Tue Nov 8 23:37:59 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Tue, 8 Nov 2011 15:37:59 -0700 Subject: [Tutor] Another question about GUI applications. Message-ID: I tried the code you suggested and I got the following error message. Here is the code I tried. root = Tkinter.Tk() root.iconbitmap(default=ico_image_filename) And here is the error message. Traceback (most recent call last): File "C:\Python31\mad_lib.py.py", line 112, in root = Tkinter.Tk() NameError: name 'Tkinter' is not defined Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 8 23:41:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 09 Nov 2011 09:41:25 +1100 Subject: [Tutor] Another question about GUI applications. In-Reply-To: References: Message-ID: <4EB9B015.2040209@pearwood.info> Nathaniel Trujillo wrote: > Traceback (most recent call last): > File "C:\Python31\mad_lib.py.py", line 112, in > root = Tkinter.Tk() > NameError: name 'Tkinter' is not defined You have to import the Tkinter module first: import Tkinter -- Steven From joel.goldstick at gmail.com Tue Nov 8 23:42:46 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 8 Nov 2011 17:42:46 -0500 Subject: [Tutor] Beginning Python From Perl In-Reply-To: References: Message-ID: start with python.org. There is a tutorial and lots more On Tue, Nov 8, 2011 at 5:14 PM, Jihad Esmail wrote: > Hi! I am new to this list so stick with me. I've recently taken interest > in learning Python. I have already learned Perl. How should I go about > learning Python from Perl? Please help. Thanks! > _______________________________________________ > 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 beachkidken at gmail.com Tue Nov 8 23:59:17 2011 From: beachkidken at gmail.com (Ken G.) Date: Tue, 08 Nov 2011 17:59:17 -0500 Subject: [Tutor] Beginning Python From Perl In-Reply-To: References: Message-ID: <4EB9B445.7010404@gmail.com> Not necessary learning from Perl but I would recommend Alan Gauld's online website for learning Python from scratch: http://www.alan-g.me.uk/ Good luck in learning Python. Ken On 11/08/2011 05:14 PM, Jihad Esmail wrote: > Hi! I am new to this list so stick with me. I've recently taken interest > in learning Python. I have already learned Perl. How should I go about > learning Python from Perl? Please help. Thanks! From steve at alchemy.com Wed Nov 9 00:09:51 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 08 Nov 2011 15:09:51 -0800 Subject: [Tutor] Beginning Python From Perl In-Reply-To: References: Message-ID: <4EB9B6BF.2010802@alchemy.com> On 08-Nov-11 14:14, Jihad Esmail wrote: > Hi! I am new to this list so stick with me. I've recently taken interest > in learning Python. I have already learned Perl. How should I go about > learning Python from Perl? Please help. Thanks! I, too, was a long-standing Perl programmer before diving into Python. The most important thing, and I just can't stress this enough, is that you should seek to understand Python on its own terms first. Learn the idioms and best practices of Python. Perl and Python (and C and Ruby and Java and... and ...) each have their strengths, weaknesses, and their own way of approaching a problem. If you just try to frame a program as you would in Perl, and "translate" the code into Python straight across, you'll get really crappy Python code and have a miserable time doing it. Don't program in Perl in Python, in other words. (Substitute "Perl" and "Python" with arbitrary languages of your choice.) -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From alan.gauld at btinternet.com Wed Nov 9 01:26:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Nov 2011 00:26:00 +0000 Subject: [Tutor] Another question about GUI applications. In-Reply-To: <4EB9B015.2040209@pearwood.info> References: <4EB9B015.2040209@pearwood.info> Message-ID: On 08/11/11 22:41, Steven D'Aprano wrote: > Nathaniel Trujillo wrote: > >> Traceback (most recent call last): >> File "C:\Python31\mad_lib.py.py", line 112, in >> root = Tkinter.Tk() >> NameError: name 'Tkinter' is not defined > > You have to import the Tkinter module first: And since you seem to be using Python v3 its spelled import tkinter in lowercase... Also: root = Tkinter.Tk() root.iconbitmap(default=ico_image_filename) ico_image_filename is a variable which you will need to define with a real filename. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 9 01:31:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Nov 2011 00:31:29 +0000 Subject: [Tutor] Beginning Python From Perl In-Reply-To: <4EB9B445.7010404@gmail.com> References: <4EB9B445.7010404@gmail.com> Message-ID: On 08/11/11 22:59, Ken G. wrote: > Not necessary learning from Perl but I would recommend Alan Gauld's > online website for learning Python from scratch: > > http://www.alan-g.me.uk/ Thanks for the plug! :-) But if you (the OP) already know Perl the standard official tutorial should be a great start. It will teach you the Python basics in a few hours. And as Steve said, don't try to translate Perl to Python, that leads to awkward code that probably won't run very well. It's a bit like translating a natural language like French into English. You translate the ideas not the words. Every language has its own idioms and vernacular, a literal translation just sounds odd. It's the same with programming languages. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 9 01:38:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 09 Nov 2011 00:38:11 +0000 Subject: [Tutor] Question about GUI applications. In-Reply-To: <4EB9514A.2050206@alchemy.com> References: <4EB9514A.2050206@alchemy.com> Message-ID: On 08/11/11 15:56, Steve Willoughby wrote: > I have an app I'm developing and running successfully on Windows (as > well as OSX and Linux). At least in this case it is able to replace the > application icon in place of the default "TK" one. The code I use is: > > root = Tkinter.Tk() > root.iconbitmap(default=ico_image_filename) > Steve, I just checked the help: ------------- >>> help (top.iconbitmap) Help on method wm_iconbitmap in module tkinter: wm_iconbitmap(self, bitmap=None, default=None) method of tkinter.Tk instance Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given. ------------- I note it says this sets the bitmap for the "iconified widget". That to me means the icon on the desktop, or in the Taskbar. Can you confirm that it also sets the icon at top left in the title bar? The basic icon was always set it is specifically the title bar icon that was broken... Not having a Windows PC anymore I can't test it... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at alchemy.com Wed Nov 9 02:07:50 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 08 Nov 2011 17:07:50 -0800 Subject: [Tutor] Question about GUI applications. In-Reply-To: References: <4EB9514A.2050206@alchemy.com> Message-ID: <4EB9D266.6030009@alchemy.com> On 08-Nov-11 16:38, Alan Gauld wrote: > I note it says this sets the bitmap for the "iconified widget". > That to me means the icon on the desktop, or in the Taskbar. > Can you confirm that it also sets the icon at top left in > the title bar? Yes, it changes the top left of the application window. To test, I made a "G" image and installed it. Here's a screenshot of the app window with and without that code. -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C -------------- next part -------------- A non-text attachment was scrubbed... Name: tk-icon.png Type: image/png Size: 2112 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: g-icon.png Type: image/png Size: 2342 bytes Desc: not available URL: From fomcl at yahoo.com Wed Nov 9 13:26:20 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 9 Nov 2011 04:26:20 -0800 (PST) Subject: [Tutor] Another question about GUI applications. In-Reply-To: References: <4EB9B015.2040209@pearwood.info> Message-ID: <1320841580.14521.YahooMailNeo@web110706.mail.gq1.yahoo.com> Ah, good that they've renamed it to lowercase. Isn't there a convention to only use a capital for class names? (and of course for constants, which are all caps). 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: Wednesday, November 9, 2011 1:26 AM >Subject: Re: [Tutor] Another question about GUI applications. > >On 08/11/11 22:41, Steven D'Aprano wrote: >> Nathaniel Trujillo wrote: >> >>> Traceback (most recent call last): >>> File "C:\Python31\mad_lib.py.py", line 112, in >>> root = Tkinter.Tk() >>> NameError: name 'Tkinter' is not defined >> >> You have to import the Tkinter module first: > > >And since you seem to be using Python v3 its spelled > >import tkinter > >in lowercase... > >Also: > >root = Tkinter.Tk() >root.iconbitmap(default=ico_image_filename) > >ico_image_filename > >is a variable which you will need to define with >a real filename. > >-- >Alan G >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 Wed Nov 9 15:09:08 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 9 Nov 2011 08:09:08 -0600 Subject: [Tutor] Another question about GUI applications. In-Reply-To: <1320841580.14521.YahooMailNeo@web110706.mail.gq1.yahoo.com> References: <4EB9B015.2040209@pearwood.info> <1320841580.14521.YahooMailNeo@web110706.mail.gq1.yahoo.com> Message-ID: On Wed, Nov 9, 2011 at 6:26 AM, Albert-Jan Roskam wrote: > Ah, good that they've renamed it to lowercase. Isn't there a convention > to only use a capital for class names? (and of course for constants, which > are all caps). > I think so, I know to adhere PEP 8 that is definitely required for names inside a file. As a mention, since I'm sure you'll hit this at some point if you program much with Tkinter. The common dialog imports have also changed: Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tkinter.filedialog as fd >>> import tkinter.commondialog as cd I know Google doesn't return (at least for me) very many helpful results, even when explicitly using python 3 in the search field. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Wed Nov 9 18:01:07 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 9 Nov 2011 09:01:07 -0800 (PST) Subject: [Tutor] Another question about GUI applications. In-Reply-To: References: <4EB9B015.2040209@pearwood.info> <1320841580.14521.YahooMailNeo@web110706.mail.gq1.yahoo.com> Message-ID: <1320858067.47228.YahooMailNeo@web110707.mail.gq1.yahoo.com> Thank you. I looked it up and http://www.python.org/dev/peps/pep-0008/?says the following: Class Names ????? Almost without exception, class names use the CapWords convention. ????? Classes for internal use have a leading underscore in addition. Package and Module Names ????? Modules should have short, all-lowercase names.? Underscores can be used ????? in the module name if it improves readability.? Python packages should ????? also have short, all-lowercase names, although the use of underscores is ????? discouraged. 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: Wayne Werner >To: Albert-Jan Roskam >Cc: Alan Gauld ; "tutor at python.org" >Sent: Wednesday, November 9, 2011 3:09 PM >Subject: Re: [Tutor] Another question about GUI applications. > > >On Wed, Nov 9, 2011 at 6:26 AM, Albert-Jan Roskam wrote: > >Ah, good that they've renamed it to lowercase. Isn't there a convention to only use a capital for class names? (and of course for constants, which are all caps). > > >I think so, I know to adhere PEP 8 that is definitely required for names inside a file.? > > >As a mention, since I'm sure you'll hit this at some point if you program much with Tkinter. The common dialog imports have also changed: > > >Python 3.2.2 (default, Sep ?4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> import tkinter.filedialog as fd >>>> import tkinter.commondialog as cd > > >I know Google doesn't return (at least for me) very many helpful results, even when explicitly using python 3 in the search field. > > >HTH, >Wayne > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hothottrott at gmail.com Thu Nov 10 05:29:51 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Wed, 9 Nov 2011 21:29:51 -0700 Subject: [Tutor] Question about graphics. Message-ID: I installed livewires for python 2.x so should that work with python version 2.7.2 ? I typed in the code you see below and got the following error message. Here is the code. from livewires import games and here is the error message Traceback (most recent call last): File "C:/Python27/new_graphics_window.py", line 4, in from livewires import games ImportError: No module named livewires Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hothottrott at gmail.com Thu Nov 10 06:03:19 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Wed, 9 Nov 2011 22:03:19 -0700 Subject: [Tutor] Another question about graphics. Message-ID: I am using python version 2.7.2. I put the version of livewires for python 2.x in the right folder this time and after running the following program I got a different error message. Here they are. program # New Graphics Window # Demonstrates creating a graphics window from livewires import games games.init(screen_width = 640, screen_height = 480, fps = 50) games.screen.mainloop() error message Traceback (most recent call last): File "C:/Python27/new_graphics_window.py", line 6, in games.init(screen_width = 640, screen_height = 480, fps = 50) AttributeError: 'module' object has no attribute 'init' Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 10 08:10:57 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 15:10:57 +0800 Subject: [Tutor] how to remove the coming duplication Message-ID: Hi, How to remove the coming duplication, Here I wrote one (not working): >>> a=['2', '5', '7', '5', '5'] >>> for i in range(len(a)-1): if a[i+1]==a[i]: a.remove(a[i+1]) if i not in range(len(a)): break >>> a ['2', '7', '5', '5'] I wish to get a is [2,5,7,5] just remove the coming duplication, not unique the list. Thanks for any advice, Best regards, From lina.lastname at gmail.com Thu Nov 10 08:20:49 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 15:20:49 +0800 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: b = [] b=b.append(a[i]) for i in range(len(a)) if a[i] != b[-1] showed me: SyntaxError: invalid syntax From pasokan at talentsprint.com Thu Nov 10 08:23:43 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Thu, 10 Nov 2011 12:53:43 +0530 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: On Thu, Nov 10, 2011 at 12:40 PM, lina wrote: > Hi, > > How to remove the coming duplication, > > Here I wrote one (not working): > > > >>> a=['2', '5', '7', '5', '5'] > >>> for i in range(len(a)-1): > if a[i+1]==a[i]: > a.remove(a[i+1]) > if i not in range(len(a)): > break > > > >>> a > ['2', '7', '5', '5'] > > I wish to get a is [2,5,7,5] > Did you mean [2, 5, 7] just remove the coming duplication, not unique the list. > > Thanks for any advice, > I am assuming that you want to remove ALL duplicates. Option 1: Look at a different data structure -- one that does not have duplicates by design: namely sets Option 2: Sort the list and then remove duplicates as you did. look at sorted(a) Option 3: This is probably the least efficient but has the merit of retaining the original order Count the occurrence of each item and remove 1 less look at a.count() I have chosen to indicate the directions; hope it helps Asokan Pichai Enjoy programming in python -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 10 08:24:41 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 15:24:41 +0800 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: >>> for i in range(len(a)): if i == 0: b.append(a[i]) if a[i]!=b[-1]: b.append(a[i]) This one seems work, but looks clumsy, Thanks for any suggestions that helps to improve. Best regards, From pasokan at talentsprint.com Thu Nov 10 08:24:59 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Thu, 10 Nov 2011 12:54:59 +0530 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: Bad to reply to my own post. Failed to understand the >> just remove the coming duplication, not unique the list. Sorry; ignore my ideas Asokan Pichai -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Nov 10 08:29:02 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 10 Nov 2011 07:29:02 +0000 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: <1195747802-1320910149-cardhu_decombobulator_blackberry.rim.net-1277659879-@b18.c12.bise7.blackberry> Try this >>> a=['2', '5', '7', '5', '5'] >>> d=list(set(a)) >>> d ['2','5','7'] Is there any reason why your numbers are in quotes??? Hope this helps. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: lina Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 10 Nov 2011 15:10:57 To: tutor Subject: [Tutor] how to remove the coming duplication Hi, How to remove the coming duplication, Here I wrote one (not working): >>> a=['2', '5', '7', '5', '5'] >>> for i in range(len(a)-1): if a[i+1]==a[i]: a.remove(a[i+1]) if i not in range(len(a)): break >>> a ['2', '7', '5', '5'] I wish to get a is [2,5,7,5] just remove the coming duplication, not unique the list. Thanks for any advice, Best regards, _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From spawgi at gmail.com Thu Nov 10 08:30:00 2011 From: spawgi at gmail.com (spawgi at gmail.com) Date: Thu, 10 Nov 2011 13:00:00 +0530 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: Hello, list.remove will remove the first occurrence of the value from the list. So the output is expected as far as Python is concerned. May be you should think about using pop function. Please take a look at the code below >>> def RemoveComingDuplicates(a): for i in range(len(a)-1): print i,i+1 if a[i+1] == a[i]: a.pop(i+1) print a >>> a = ['2','5','7','5','5'] >>> RemoveComingDuplicates(a) 0 1 ['2', '5', '7', '5', '5'] 1 2 ['2', '5', '7', '5', '5'] 2 3 ['2', '5', '7', '5', '5'] 3 4 ['2', '5', '7', '5'] >>> Hope this helps. Thanks and Regards, Sumod On Thu, Nov 10, 2011 at 12:54 PM, lina wrote: > >>> for i in range(len(a)): > if i == 0: > b.append(a[i]) > if a[i]!=b[-1]: > b.append(a[i]) > > This one seems work, but looks clumsy, > > Thanks for any suggestions that helps to improve. > > Best regards, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- http://spawgi.wordpress.com We can do it and do it better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Nov 10 08:38:40 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 10 Nov 2011 07:38:40 +0000 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: <679390306-1320910720-cardhu_decombobulator_blackberry.rim.net-1810129977-@b18.c12.bise7.blackberry> You have the error because the square brackets are missing. You should have done this: b=[b.append(a[i]) for i in range(len(a)) if a[i] != b[-1]] This would however give you an index out of range error. That said, may I ask what it is exactly you are trying to achieve? Cheers. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: lina Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 10 Nov 2011 15:20:49 To: tutor Subject: Re: [Tutor] how to remove the coming duplication b = [] b=b.append(a[i]) for i in range(len(a)) if a[i] != b[-1] showed me: SyntaxError: invalid syntax _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From cwitts at compuscan.co.za Thu Nov 10 08:55:16 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 10 Nov 2011 09:55:16 +0200 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: <4EBB8364.2050809@compuscan.co.za> On 2011/11/10 09:10 AM, lina wrote: > Hi, > > How to remove the coming duplication, > > Here I wrote one (not working): > > >>>> a=['2', '5', '7', '5', '5'] >>>> for i in range(len(a)-1): > if a[i+1]==a[i]: > a.remove(a[i+1]) > if i not in range(len(a)): > break > > >>>> a > ['2', '7', '5', '5'] > > I wish to get a is [2,5,7,5] > > just remove the coming duplication, not unique the list. > > Thanks for any advice, > > Best regards, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > def remove_coming_duplication(a_list): return [element for idx, element in enumerate(a_list) if element != a_list[idx-1]] >>> remove_coming_duplication([2, 5, 7, 5, 5]) [2, 5, 7, 5] >>> remove_coming_duplication([2, 5, 7, 5, 5, 5, 5, 5, 7, 7, 5]) [2, 5, 7, 5, 7, 5] >>> remove_coming_duplication(['2', '5', '7', '5', '5']) ['2', '5', '7', '5'] With this you're simply iterating through the list and checking if the current element in the list is not equal to the previous element, and if so it is not a duplicate and will be added to the new list you're creating. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Thu Nov 10 09:04:29 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Thu, 10 Nov 2011 13:34:29 +0530 Subject: [Tutor] how to remove the coming duplication In-Reply-To: <4EBB8364.2050809@compuscan.co.za> References: <4EBB8364.2050809@compuscan.co.za> Message-ID: I was so miffed at not reading the OP's mail carefully that I wrote a one liner. Ok. Here it goes: def no_adjacent_dup(lst): return [ x for x, y in zip(lst, lst[1:]) if x != y] + [lst[-1]] :-) Enjoyed working that one out; but whether it is a good solution .... Asokan Pichai -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 10 09:26:24 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 16:26:24 +0800 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: <4EBB8364.2050809@compuscan.co.za> Message-ID: Thanks for all, I found the problems I faced is more tricky than the simple list I gave. Here the list is: a row of numbers, not one number, such as print a_list[1] is: 1 1 9 7 7 9 9 9 print(a_list) is: 617 617 790 571 571 790 790 790 I attached the codes written based on the suggestions all you have given, and also attached the to-be-handled file in the following link: #!/usr/bin/python3 import os.path INFILEEXT=".out" OUTFILEEXT=".bri" atoms=[] def fetchonefiledata(infilename): for line in open(infilename,"r"): parts=line.strip().split() atoms=parts[2] print(atoms[0]) def remove_coming_duplications(a_list): for idx, element in enumerate(a_list): if element != a_list[idx-1]: print(element) if __name__=="__main__": for filename in os.listdir("."): base, ext = os.path.splitext(filename) if ext == INFILEEXT: fetchonefiledata(filename) remove_coming_duplications(atoms) https://docs.google.com/open?id=0B93SVRfpVVg3MjVlODdiOWYtY2FlYy00NDIzLThjMzAtMDk0NTQ4ZTRjZjRh Thanks with best regards, P.S My primary interest is getting the lists from different files, hopefully in the end find some rules between those numbers. or pathway, such as 1 2 4 8 7 6 4 8 7 6 5 1 so it shares a feature of 4 -> 8 -> 7 -> 6. From __peter__ at web.de Thu Nov 10 09:37:22 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Nov 2011 09:37:22 +0100 Subject: [Tutor] how to remove the coming duplication References: <4EBB8364.2050809@compuscan.co.za> Message-ID: Christian Witts wrote: > def remove_coming_duplication(a_list): > return [element for idx, element in enumerate(a_list) if element != > a_list[idx-1]] Beware of negative indices: >>> remove_coming_duplication([1, 2, 1]) [2, 1] # should be [1, 2, 1] From pasokan at talentsprint.com Thu Nov 10 10:05:59 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Thu, 10 Nov 2011 14:35:59 +0530 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: <4EBB8364.2050809@compuscan.co.za> Message-ID: On Thu, Nov 10, 2011 at 2:07 PM, Peter Otten <__peter__ at web.de> wrote: > Christian Witts wrote: > > > def remove_coming_duplication(a_list): > > return [element for idx, element in enumerate(a_list) if element != > > a_list[idx-1]] > > Beware of negative indices: > > >>> remove_coming_duplication([1, 2, 1]) > [2, 1] # should be [1, 2, 1] > > I ran into that and hence I chose to zip, compare and add the last element Asokan Pichai -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Nov 10 10:45:59 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Nov 2011 10:45:59 +0100 Subject: [Tutor] how to remove the coming duplication References: <4EBB8364.2050809@compuscan.co.za> Message-ID: Asokan Pichai wrote: > On Thu, Nov 10, 2011 at 2:07 PM, Peter Otten <__peter__ at web.de> wrote: > >> Christian Witts wrote: >> >> > def remove_coming_duplication(a_list): >> > return [element for idx, element in enumerate(a_list) if element >> > != >> > a_list[idx-1]] >> >> Beware of negative indices: >> >> >>> remove_coming_duplication([1, 2, 1]) >> [2, 1] # should be [1, 2, 1] >> >> > I ran into that and hence I chose to zip, compare and add the last element I have one for you, too ;) >>> def no_adjacent_dup(lst): ... return [ x for x, y in zip(lst, lst[1:]) if x != y] + [lst[-1]] ... >>> no_adjacent_dup([]) Traceback (most recent call last): File "", line 1, in File "", line 2, in no_adjacent_dup IndexError: list index out of range And a subtle one as a bonus: >>> no_adjacent_dup([1, 1.0]) [1.0] # should be 1 Here's a highlevel approach, probably not very efficient: >>> from itertools import groupby >>> [k for k, g in groupby([1, 1.0, 2, 1, 3, 3, 3])] [1, 2, 1, 3] From jerry.scofield at gmail.com Thu Nov 10 10:23:28 2011 From: jerry.scofield at gmail.com (Jerry Zhang) Date: Thu, 10 Nov 2011 17:23:28 +0800 Subject: [Tutor] The python implementation of the "class relationship". Message-ID: As you know, there are several kinds of relationships between classes in the UML -- dependency, association, aggregation, composition. Q1. Is there any article or code example on its implementation in python? Q2. More specific, in composition model, the container object may be responsible for the handling of embedded objects' lifecycle. The common way would be adding __del__ to the container class or something else? Thanks! Biao -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Thu Nov 10 11:47:59 2011 From: timomlists at gmail.com (Timo) Date: Thu, 10 Nov 2011 11:47:59 +0100 Subject: [Tutor] Another question about graphics. In-Reply-To: References: Message-ID: <4EBBABDF.1080901@gmail.com> Op 10-11-11 06:03, Nathaniel Trujillo schreef: > I am using python version 2.7.2. I put the version of livewires for > python 2.x in the right folder this time and after running the > following program I got a different error message. Here they are. > program > # New Graphics Window > # Demonstrates creating a graphics window > from livewires import games > games.init(screen_width = 640, screen_height = 480, fps = 50) > games.screen.mainloop() > error message > Traceback (most recent call last): > File "C:/Python27/new_graphics_window.py", line 6, in > games.init(screen_width = 640, screen_height = 480, fps = 50) > AttributeError: 'module' object has no attribute 'init' Well, the error says it all. The games module has no init method. You should probably see the livewires documentation or mailing list for such questions. The chance for getting your third-party module questions answered is pretty small here. Cheers, Timo > Thanks for the help. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From ma_development at hotmail.com Thu Nov 10 12:07:51 2011 From: ma_development at hotmail.com (Mario Cavett) Date: Thu, 10 Nov 2011 06:07:51 -0500 Subject: [Tutor] lb4cwpci h5woidb Message-ID: 2sovs4c, 83a6uf6jpq. http://2ufgrfdi6r.blog.com/w64/ 52fdsyt04v hwfqg zzxy9lf1dx, d3xxy67x4 acih3ta8. 7hnkugc99tv waacqm1ao. -------------- next part -------------- An HTML attachment was scrubbed... URL: From learner404 at gmail.com Thu Nov 10 12:15:37 2011 From: learner404 at gmail.com (learner404) Date: Thu, 10 Nov 2011 12:15:37 +0100 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) Message-ID: Hello list! - myapp.py is in a "myfolder" folder that the "users" will be able to download and put anywhere on their Mac. - users don't have any Python knowledge and I have no idea if there's a python launcher on their mac => trying to make an applescript file in the folder right next to myapp.py I tried and failed at : *tell* *application* "Terminal" *do script* "python myapp.py" # tried also with ./myapp.py *end* *tell* or do shell script "python myapp.py" # tried also with ./myapp.py In both cases OSX complains it can't find the file. It works though if I give the full path but I can't do that since I have no idea where the folder will be on their macs. With Applescript how would write it so that Python starts in the application folder? (myapp.py & "myfolder") Any other way to do it maybe knowing my constraints above? (I tried py2app but it failed on wxpython on my Lion with Apple Python that I need to use) Thanks! francois -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Thu Nov 10 13:24:07 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 10 Nov 2011 13:24:07 +0100 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: <4EBB8364.2050809@compuscan.co.za> Message-ID: <4EBBC267.7090007@gmx.net> On 2011-11-10 09:26, lina wrote: > atoms=[] > > def fetchonefiledata(infilename): > for line in open(infilename,"r"): > parts=line.strip().split() > atoms=parts[2] > print(atoms[0]) First you define "atoms" as an empty list, but in the line atoms = parts[2] you are redefining it by assigning a string to it. Thus, at the end of the for-loop, only the last string is stored (in every iteration you overwrite the former value with a new one). You probably want to append the values: atoms.append(parts[2]) Bye, Andreas From steve at pearwood.info Thu Nov 10 13:48:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 10 Nov 2011 23:48:48 +1100 Subject: [Tutor] how to remove the coming duplication In-Reply-To: References: Message-ID: <4EBBC830.6070600@pearwood.info> lina wrote: > Hi, > > How to remove the coming duplication, > > Here I wrote one (not working): > > >>>> a=['2', '5', '7', '5', '5'] [...] > I wish to get a is [2,5,7,5] > > just remove the coming duplication, not unique the list. a = [2, 5, 7, 5, 5] b = a[0:1] # slice of the first item only for x in a[1:]: # slice of the second item to the end if x != b[-1]: b.append(x) gives b = [2, 5, 7, 5] as requested. -- Steven From steve at pearwood.info Thu Nov 10 14:14:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Nov 2011 00:14:51 +1100 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: References: Message-ID: <4EBBCE4B.5030600@pearwood.info> learner404 wrote: > Hello list! > > - myapp.py is in a "myfolder" folder that the "users" will be able to > download and put anywhere on their Mac. [...] > In both cases OSX complains it can't find the file. Do you mean that AppleScript can't find the file, or that Python can't find the file? Please don't summarize or paraphrase errors. Please copy and paste the EXACT error message that is shown. If this is a problem with AppleScript being unable to find the file, you will be better off asking on an AppleScript mailing list. In general, on Unix-like systems (and that includes Mac OS X), you can't expect a command like: python myapp.py to work unless myapp.py is in the current directory. -- Steven From lina.lastname at gmail.com Thu Nov 10 14:05:29 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 21:05:29 +0800 Subject: [Tutor] some ideas about some network Message-ID: Hi, Thanks all again for your help in previous post. Here I meet something I am not experienced, about: from 10 groups of data (namely from 1-84) find some pathway, or network. such as Group 1 (file 1): 1 3 8 5 7 4 Group 2 (file 2): 2 8 5 7 4 3 4 8 5 7 4 so we can see that the 8 -> 5 -> 7 -> 4 is a pathway. Thanks for any suggestions. P.S I attached the data file in below link: https://docs.google.com/open?id=0B93SVRfpVVg3MDU0YTEwY2MtNWZjNS00ZWNkLWJiNDAtNTJlNTRlYTg4YTU5 Best regards, From steve at pearwood.info Thu Nov 10 14:56:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Nov 2011 00:56:07 +1100 Subject: [Tutor] The python implementation of the "class relationship". In-Reply-To: References: Message-ID: <4EBBD7F7.6030007@pearwood.info> Jerry Zhang wrote: > As you know, there are several kinds of relationships between classes in > the UML -- dependency, association, aggregation, composition. "As you know"... no, I'm afraid I don't know. Believe it or not, it is possible to be an experienced, good programmer and still know nothing about Unified Modeling Language. > Q1. Is there any article or code example on its implementation in python? > Q2. More specific, in composition model, the container object may be > responsible for the handling of embedded objects' lifecycle. The common way > would be adding __del__ to the container class or something else? If I have guessed correctly what you mean, no, containers are not responsible for handling embedded objects' lifecycle in Python. Every object is responsible for itself. Python objects are garbage collected when there are no longer any references to that object, regardless of whether those references are in the form of name bindings, containment inside a container or attribute, closures, or any other reference. This list is for learning about the Python programming language, aimed mostly at beginners. You might have better luck getting detailed answers on the python-list at python.org mailing list, also available as comp.lang.python on Usenet. -- Steven From lina.lastname at gmail.com Thu Nov 10 14:57:34 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 21:57:34 +0800 Subject: [Tutor] how to remove the coming duplication In-Reply-To: <4EBBC830.6070600@pearwood.info> References: <4EBBC830.6070600@pearwood.info> Message-ID: On Thu, Nov 10, 2011 at 8:48 PM, Steven D'Aprano wrote: > lina wrote: >> >> Hi, >> >> How to remove the coming duplication, >> >> Here I wrote one (not working): >> >> >>>>> a=['2', '5', '7', '5', '5'] > > [...] >> >> I wish to get a is [2,5,7,5] >> >> just remove the coming duplication, not unique the list. > > a = [2, 5, 7, 5, 5] > b = a[0:1] ?# slice of the first item only > for x in a[1:]: ?# slice of the second item to the end > ? ?if x != b[-1]: > ? ? ? ?b.append(x) for index, b in enumerate([b_list]): print(b) how can I avoid the output not as: ['53', '76', '57'] but as 53 76 57 Thanks > > > gives b = [2, 5, 7, 5] as requested. > > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From waynejwerner at gmail.com Thu Nov 10 15:02:03 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 10 Nov 2011 08:02:03 -0600 Subject: [Tutor] some ideas about some network In-Reply-To: References: Message-ID: On Thu, Nov 10, 2011 at 7:05 AM, lina wrote: > Hi, > > Thanks all again for your help in previous post. > > Here I meet something I am not experienced, about: > > from 10 groups of data (namely from 1-84) find some pathway, or network. > > such as > Group 1 (file 1): 1 3 8 5 7 4 > Group 2 (file 2): 2 8 5 7 4 3 4 8 5 7 4 > > so we can see that the 8 -> 5 -> 7 -> 4 is a pathway. > > Thanks for any suggestions. > I'm confused - what are you trying to do with this data? I can only guess you're referring to a graph and you would like some way to visualize this data? It helps when you can show what you've tried to do as well. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Nov 10 15:02:55 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 10 Nov 2011 14:02:55 +0000 Subject: [Tutor] some ideas about some network In-Reply-To: References: Message-ID: Hi Lina, On 10 November 2011 13:05, lina wrote: > from 10 groups of data (namely from 1-84) find some pathway, or network. > > such as > Group 1 (file 1): 1 3 8 5 7 4 > Group 2 (file 2): 2 8 5 7 4 3 4 8 5 7 4 > > so we can see that the 8 -> 5 -> 7 -> 4 is a pathway. > I'm sorry but I'm not really sure what you're asking. Can you be more specific? How exactly do those 2 (or more) combine to form a pathway or network, and what exactly do you mean by pathway? Also, your attachment zip is empty, so you might want to post that again. Going out on a limb and guessing here, though: Is the problem you're trying to solve the same as this (the "longest common substring" problem)?: http://is.gd/pc6zlk Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 10 15:05:03 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 22:05:03 +0800 Subject: [Tutor] some ideas about some network In-Reply-To: References: Message-ID: On Thu, Nov 10, 2011 at 10:02 PM, Wayne Werner wrote: > > On Thu, Nov 10, 2011 at 7:05 AM, lina wrote: >> >> Hi, >> >> Thanks all again for your help in previous post. >> >> Here I meet something I am not experienced, about: >> >> from 10 groups of data ?(namely from 1-84) find some pathway, or network. >> >> such as >> Group 1 (file 1): 1 3 8 5 7 4 >> Group 2 (file 2): 2 8 5 7 4 3 4 8 5 7 4 >> >> so we can see that the 8 -> 5 -> 7 -> 4 ?is a pathway. >> >> Thanks for any suggestions. > > I'm confused - ?what are you trying to do with this data? I can only guess > you're referring to a graph and you would like some way to visualize this > data? The data is the position, I wanted to see the pathway. a roadmap which connected those positions, but one-way, has direction, from 8 --> 5 Thanks, > It helps when you can show what you've tried to do as well. > -Wayne From jerry.scofield at gmail.com Thu Nov 10 15:12:50 2011 From: jerry.scofield at gmail.com (Jerry Zhang) Date: Thu, 10 Nov 2011 22:12:50 +0800 Subject: [Tutor] The python implementation of the "class relationship". In-Reply-To: <4EBBD7F7.6030007@pearwood.info> References: <4EBBD7F7.6030007@pearwood.info> Message-ID: Thanks for your reply. 2011/11/10 Steven D'Aprano > Jerry Zhang wrote: > >> As you know, there are several kinds of relationships between classes in >> the UML -- dependency, association, aggregation, composition. >> > > "As you know"... no, I'm afraid I don't know. Believe it or not, it is > possible to be an experienced, good programmer and still know nothing about > Unified Modeling Language. Yeah, but these kinds of relationship still exists in real word whatever UML is. For example, the relationship between Cls_arm and Cls_body could be composition, one arm instance only live with one body instance, and once this body die, this arm also die. All of this should be described by python if your application need. > > > > Q1. Is there any article or code example on its implementation in python? >> Q2. More specific, in composition model, the container object may be >> responsible for the handling of embedded objects' lifecycle. The common >> way >> would be adding __del__ to the container class or something else? >> > > If I have guessed correctly what you mean, no, containers are not > responsible for handling embedded objects' lifecycle in Python. Every > object is responsible for itself. Python objects are garbage collected when > there are no longer any references to that object, regardless of whether > those references are in the form of name bindings, containment inside a > container or attribute, closures, or any other reference. > Yeah, python objects garbage may be another story. Think about you have a ZODB running which stores your objects data, you will care their lifecycle. maybe because i did not make myself understood yet. Here is a more detail example question. I have a classes sets described by UML, which could be refered as Cls_A, Cls_B, CLs_C, Cls_D, Cls_E. There are four relationship between them--dependency, association, aggregation, composition. What i need to do is define all of the classes by python, and,of course, the class definition should describe there relationship correctly. For example, implement composition relationship between Cls_A and Cls_B, which may means a instance of Cls_B is created and destroyed by a Cls_A instance, My code may be like this(not sure since i am not quite familiar with python yet): Cls_a: def __init__(self): self.at1 = 1 Cls_b: def __init__(self): self.com1 = Cls_a() def __del__(self): del self.com1 Is it a right implementation for composition? and i need also do other relationship definition into class, like dependency, association, aggregation... Is there any article or code example on the relationships implementation? > > This list is for learning about the Python programming language, aimed > mostly at beginners. You might have better luck getting detailed answers on > the python-list at python.org mailing list, also available as > comp.lang.python on Usenet. > I am trying. > > > > -- > 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 lina.lastname at gmail.com Thu Nov 10 15:37:25 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 22:37:25 +0800 Subject: [Tutor] some ideas about some network In-Reply-To: References: Message-ID: On Thu, Nov 10, 2011 at 10:02 PM, Walter Prins wrote: > Hi Lina, > > On 10 November 2011 13:05, lina wrote: >> >> from 10 groups of data ?(namely from 1-84) find some pathway, or network. >> >> such as >> Group 1 (file 1): 1 3 8 5 7 4 >> Group 2 (file 2): 2 8 5 7 4 3 4 8 5 7 4 >> >> so we can see that the 8 -> 5 -> 7 -> 4 ?is a pathway. > > I'm sorry but I'm not really sure what you're asking.? Can you be more > specific?? How exactly do those 2 (or more) combine to form a pathway or > network, and what exactly do you mean by pathway? Actually there are 10 trajectories, or ten paths (road) for a person to travel 84 sites. and we don't have a specific map of this 84 sites. so I wish to find some common pathway, > > Also, your attachment zip is empty, so you might want to post that again. The tar.gz link: https://docs.google.com/open?id=0B93SVRfpVVg3N2E0ZWFhNWUtZTY4Ny00NWE0LWJlMmItODMwOTBiYjE4YzRi The .zip link: https://docs.google.com/open?id=0B93SVRfpVVg3NzE5ZWFiYmYtM2JmMS00ODM3LWIwMGEtNjBmN2Q1NmRhMWI2 > > Going out on a limb and guessing here, though:? Is the problem you're trying > to solve the same as this (the "longest common substring" problem)?: > http://is.gd/pc6zlk Thanks, I will try to understand it. Best regards, > > Walter > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From lina.lastname at gmail.com Thu Nov 10 15:43:27 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 22:43:27 +0800 Subject: [Tutor] some ideas about some network In-Reply-To: References: Message-ID: On Thu, Nov 10, 2011 at 10:02 PM, Walter Prins wrote: > Hi Lina, > > On 10 November 2011 13:05, lina wrote: >> >> from 10 groups of data ?(namely from 1-84) find some pathway, or network. >> >> such as >> Group 1 (file 1): 1 3 8 5 7 4 >> Group 2 (file 2): 2 8 5 7 4 3 4 8 5 7 4 >> >> so we can see that the 8 -> 5 -> 7 -> 4 ?is a pathway. > > I'm sorry but I'm not really sure what you're asking.? Can you be more > specific?? How exactly do those 2 (or more) combine to form a pathway or > network, and what exactly do you mean by pathway? > > Also, your attachment zip is empty, so you might want to post that again. > > Going out on a limb and guessing here, though:? Is the problem you're trying > to solve the same as this (the "longest common substring" problem)?: > http://is.gd/pc6zlk Thanks, this one is very helpful, something about the longest common substring. > > Walter > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From lina.lastname at gmail.com Thu Nov 10 16:06:56 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 10 Nov 2011 23:06:56 +0800 Subject: [Tutor] some ideas about some network In-Reply-To: References: Message-ID: My mistakes, the first generated-data has some problems: the newly uploaded tar.gz one is: https://docs.google.com/open?id=0B93SVRfpVVg3Mjk0YjYzYTMtNzgzZS00NDk4LWI1M2QtNGE5OGZlMjYyNmM5 zip one is https://docs.google.com/open?id=0B93SVRfpVVg3MDYwZWMzYzItYmI4ZC00MmIxLTg0NmMtMzM5MzZkZTAxZjJl The below code generated those data has problems in appending parts (reading mulitiple files), I don't know which parts was wrong: #!/usr/bin/python3 import os.path from itertools import groupby DICTIONARYFILE="dictionary.pdb" INFILEEXT=".out" OUTFILEEXT=".txt" mapping={} def generate_dict(dictionarysourcefile): for line in open(dictionarysourcefile,"r"): parts=line.strip().split() mapping[parts[2]]=parts[0] def fetchonefiledata(dictionary,infilename): with open(infilename,"r") as f: residues=[] residueID=[] residues=[dictionary[line.split()[2]] for line in f] print(residues) for i in range(len(residues)): residueID.append(residues[i][:-3]) remove_coming_dup(residueID) def remove_coming_dup(a_list): b_list=a_list[0:1] for x in a_list[1:]: if x != b_list[-1]: b_list.append(x) with open(base+OUTFILEEXT,"w") as f: for index, b in enumerate([b_list]): print(b,file=f) if __name__=="__main__": generate_dict(DICTIONARYFILE) for filename in os.listdir("."): base, ext = os.path.splitext(filename) if ext == INFILEEXT: fetchonefiledata(mapping,filename) From learner404 at gmail.com Thu Nov 10 16:20:05 2011 From: learner404 at gmail.com (learner404) Date: Thu, 10 Nov 2011 16:20:05 +0100 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: <4EBBCE4B.5030600@pearwood.info> References: <4EBBCE4B.5030600@pearwood.info> Message-ID: On Thu, Nov 10, 2011 at 2:14 PM, Steven D'Aprano wrote: > learner404 wrote: > >> Hello list! >> >> - myapp.py is in a "myfolder" folder that the "users" will be able to >> download and put anywhere on their Mac. >> > [...] > > In both cases OSX complains it can't find the file. >> > > Do you mean that AppleScript can't find the file, or that Python can't > find the file? > When I double click on the AppleScript the terminal opens with $ python myapp.py $ python: can't open file 'avcOsxLinux.py': [Errno 2] No such file or directory myapp.py and the AppleScript are both in the same directory. If I open manually a shell in this directory "python myapp.py" works. It all seems like the Python invoked in the AppleScript have his current directory in root (and not the folder where i'm executing the AppleScript). I don't see how I can change this from the AppleScript or simply find a general solution to execute a .py script on Mac within the constrains I mentioned above. > Please don't summarize or paraphrase errors. Please copy and paste the > EXACT error message that is shown. > > If this is a problem with AppleScript being unable to find the file, you > will be better off asking on an AppleScript mailing list. > > In general, on Unix-like systems (and that includes Mac OS X), you can't > expect a command like: > > python myapp.py > > to work unless myapp.py is in the current directory. > > > > -- > 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 roadierich at googlemail.com Thu Nov 10 16:33:37 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 10 Nov 2011 15:33:37 +0000 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: References: <4EBBCE4B.5030600@pearwood.info> Message-ID: On 10 Nov 2011, at 15:20, learner404 wrote: > > > On Thu, Nov 10, 2011 at 2:14 PM, Steven D'Aprano wrote: > learner404 wrote: > Hello list! > > - myapp.py is in a "myfolder" folder that the "users" will be able to > download and put anywhere on their Mac. > [...] > > In both cases OSX complains it can't find the file. > > Do you mean that AppleScript can't find the file, or that Python can't find the file? > > When I double click on the AppleScript the terminal opens with > > $ python myapp.py > $ python: can't open file 'avcOsxLinux.py': [Errno 2] No such file or directory > > myapp.py and the AppleScript are both in the same directory. If I open manually a shell in this directory "python myapp.py" works. > > It all seems like the Python invoked in the AppleScript have his current directory in root (and not the folder where i'm executing the AppleScript). I don't see how I can change this from the AppleScript or simply find a general solution to execute a .py script on Mac within the constrains I mentioned above. > > > Please don't summarize or paraphrase errors. Please copy and paste the EXACT error message that is shown. > > If this is a problem with AppleScript being unable to find the file, you will be better off asking on an AppleScript mailing list. > > In general, on Unix-like systems (and that includes Mac OS X), you can't expect a command like: > > python myapp.py > > to work unless myapp.py is in the current directory. > > > > -- > Steven > _______________________________________________ > 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 It looks like your script is being found fine, meaning the problem lies elsewhere - unless your actual app is called "avcOsxLinux.py, and you missed renaming it in the error message. Try adding a print statement as the very first line - before any imports - to test this. The only reference to that filename is a french audio-visual library, which might not be installed on your target system. Rich "RoadieRich" Lovely There are 10 types of people in the world: Those who know binary, Those who do not, And those who are off by one. From rhettnaxel at gmail.com Thu Nov 10 17:10:06 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Thu, 10 Nov 2011 11:10:06 -0500 Subject: [Tutor] Find all strings that.... Message-ID: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> Hi. My friend gave me a good wake up exercise which I do not want you to solve for me: find all strings which can be converted to alpha with at most two operations, where alpha is some string constant, and a substring of at least length three of alpha must be in the answers. So, my question is: is there a library or .txt dictionary ( not the data type, rather the merriam webster kind ) I can use to test my script on? I'd imagine this library/dictionary to contain thousands of words. Not random words. Thanks for reading, Alexander From mehgcap at gmail.com Thu Nov 10 17:14:53 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 10 Nov 2011 11:14:53 -0500 Subject: [Tutor] Find all strings that.... In-Reply-To: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> Message-ID: What about just grabbing a bit text file, such as from Project Gutenberg (sorry for the possibly incorrect spelling)? Or copying the text from a large webpage and pasting it into a text file? On 11/10/11, Alexander Etter wrote: > > > Hi. My friend gave me a good wake up exercise which I do not want you to > solve for me: find all strings which can be converted to alpha with at most > two operations, where alpha is some string constant, and a substring of at > least length three of alpha must be in the answers. > So, my question is: is there a library or .txt dictionary ( not the data > type, rather the merriam webster kind ) I can use to test my script on? I'd > imagine this library/dictionary to contain thousands of words. Not random > words. > Thanks for reading, > Alexander > _______________________________________________ > 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 lina.lastname at gmail.com Thu Nov 10 17:23:53 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 11 Nov 2011 00:23:53 +0800 Subject: [Tutor] longest common substring Message-ID: Hi, I tested the one from http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring mainly: #!/usr/bin/python3 a=['1','2','3','7'] b=['2','3','7'] def LongestCommonSubstring(S1, S2): M = [[0]*(1+len(S2)) for i in range(1+len(S1))] longest, x_longest = 0, 0 for x in range(1,1+len(S1)): for y in range(1,1+len(S2)): M[x][y] = M[x-1][y-1]+1 if M[x][y] > longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 return S1[x_longest-longest:x_longest] if __name__=="__main__": print(LongestCommonSubstring(a,b)) $ python3 LongestCommonSubstring.py ['1', '2', '3'] The results isn't right. Thanks for your suggestions and comments, Best regards, From roadierich at googlemail.com Thu Nov 10 17:28:22 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 10 Nov 2011 16:28:22 +0000 Subject: [Tutor] Find all strings that.... In-Reply-To: References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> Message-ID: <4A73089D-F715-40E0-8669-1EBF4C48B917@googlemail.com> If you're on linux or OSX, there's /usr/share/dict/words, which has a few thousand words. Although no plurals, which caught me out once. If you're on windows, it's not a hard file to find. On 10 Nov 2011, at 16:14, Alex Hall wrote: > What about just grabbing a bit text file, such as from Project > Gutenberg (sorry for the possibly incorrect spelling)? Or copying the > text from a large webpage and pasting it into a text file? > > On 11/10/11, Alexander Etter wrote: >> >> >> Hi. My friend gave me a good wake up exercise which I do not want you to >> solve for me: find all strings which can be converted to alpha with at most >> two operations, where alpha is some string constant, and a substring of at >> least length three of alpha must be in the answers. >> So, my question is: is there a library or .txt dictionary ( not the data >> type, rather the merriam webster kind ) I can use to test my script on? I'd >> imagine this library/dictionary to contain thousands of words. Not random >> words. >> Thanks for reading, >> Alexander >> _______________________________________________ >> 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 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Rich "RoadieRich" Lovely There are 10 types of people in the world: Those who know binary, Those who do not, And those who are off by one. From learner404 at gmail.com Thu Nov 10 17:43:30 2011 From: learner404 at gmail.com (learner404) Date: Thu, 10 Nov 2011 17:43:30 +0100 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: References: <4EBBCE4B.5030600@pearwood.info> Message-ID: On Thu, Nov 10, 2011 at 4:33 PM, Rich Lovely wrote: > > It looks like your script is being found fine, meaning the problem lies > elsewhere - unless your actual app is called "avcOsxLinux.py, and you > missed renaming it in the error message. Try adding a print statement as > the very first line - before any imports - to test this. > Sorry I missed replacing this one when I copy/pasted on the list; avcOsxLinux.py is "myapp.py" (I renamed it for clarity). Unfortunately the problem is still the same. $ python myapp.py $ python: can't open file 'myapp.py': [Errno 2] No such file or directory > The only reference to that filename is a french audio-visual library, > which might not be installed on your target system. > > Rich "RoadieRich" Lovely > > There are 10 types of people in the world: > Those who know binary, > Those who do not, > And those who are off by one. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hothottrott at gmail.com Thu Nov 10 18:09:02 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 10:09:02 -0700 Subject: [Tutor] getting ImportError: No module named beginners Message-ID: First I typed help() into the python 3.1.1 interpreter and then I typed modules to see if there was a beginners module and it wasn't there but when I went into the C:\Python31\Lib\site-packages\livewires folder I saw the file beginners.py right there in front of my face. So here is the program I am trying to run... # New Graphics Window # Demonstrates creating a graphics window from livewires import games games.init(sreen_width = 640, screen_height = 480, fps = 50) games.screen.mainloop() and here is the error message... Traceback (most recent call last): File "C:\Python31\new_graphics_window.py", line 4, in from livewires import games File "C:\Python31\lib\site-packages\livewires\__init__.py", line 30, in from beginners import * ImportError: No module named beginners Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Nov 10 18:21:54 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Nov 2011 18:21:54 +0100 Subject: [Tutor] longest common substring References: Message-ID: lina wrote: > Hi, > > I tested the one from > http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring > > mainly: > > #!/usr/bin/python3 > > a=['1','2','3','7'] > > b=['2','3','7'] > > def LongestCommonSubstring(S1, S2): > M = [[0]*(1+len(S2)) for i in range(1+len(S1))] > longest, x_longest = 0, 0 > for x in range(1,1+len(S1)): > for y in range(1,1+len(S2)): > M[x][y] = M[x-1][y-1]+1 > if M[x][y] > longest: > longest = M[x][y] > x_longest = x > else: > M[x][y] = 0 > return S1[x_longest-longest:x_longest] > > > if __name__=="__main__": > print(LongestCommonSubstring(a,b)) > > $ python3 LongestCommonSubstring.py > ['1', '2', '3'] > > The results isn't right. That's not the code from the site you quote. You messed it up when you tried to convert it to Python 3 (look for the suspicious 8-space indent) Hint: the function doesn't contain anything specific to Python 2 or 3, apart from the xrange builtin. If you add the line xrange = range to your code the unaltered version will run in Python 3 -- and produce the correct result: $ cat longest_common_substring3.py xrange = range def LongestCommonSubstring(S1, S2): M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] longest, x_longest = 0, 0 for x in xrange(1,1+len(S1)): for y in xrange(1,1+len(S2)): if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1] + 1 if M[x][y]>longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 return S1[x_longest-longest: x_longest] if __name__ == "__main__": a = ['1','2','3','7'] b = ['2','3','7'] print(LongestCommonSubstring(a, b)) $ python3 longest_common_substring3.py ['2', '3', '7'] From wprins at gmail.com Thu Nov 10 18:23:58 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 10 Nov 2011 17:23:58 +0000 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: Hi, On 10 November 2011 16:23, lina wrote: > def LongestCommonSubstring(S1, S2): > M = [[0]*(1+len(S2)) for i in range(1+len(S1))] > longest, x_longest = 0, 0 > for x in range(1,1+len(S1)): > for y in range(1,1+len(S2)): > M[x][y] = M[x-1][y-1]+1 > if M[x][y] > longest: > longest = M[x][y] > x_longest = x > else: > M[x][y] = 0 > return S1[x_longest-longest:x_longest] > This is not the same as the implementation given on wikibooks.... Have you tried reverting your changes and using the coe that was given on the site exactly as is? (I assume not, and if so, why not?) (Specifically, I notice most the likely culprit is a missing if statement just below the "for y in range..." line that's been deleted....) > The results isn't right. > Yes. You appear to have introduced a bug by not using the same code as what was given on the wiki page. (Why did you modify the code and then when the modified code didn't work assume the original solution was broken instead of checking first and/or suspecting that your changes may have broken it?) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Nov 10 18:37:21 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 10 Nov 2011 18:37:21 +0100 Subject: [Tutor] getting ImportError: No module named beginners References: Message-ID: Nathaniel Trujillo wrote: > First I typed help() into the python 3.1.1 interpreter and then I typed > modules to see if there was a beginners module and it wasn't there but > when I went into the > C:\Python31\Lib\site-packages\livewires folder I saw the file beginners.py > right there in front of my face. So here is the program I am trying to > run... > > # New Graphics Window > # Demonstrates creating a graphics window > from livewires import games > games.init(sreen_width = 640, screen_height = 480, fps = 50) > games.screen.mainloop() > and here is the error message... > > Traceback (most recent call last): > File "C:\Python31\new_graphics_window.py", line 4, in > from livewires import games > File "C:\Python31\lib\site-packages\livewires\__init__.py", line 30, in > > from beginners import * > ImportError: No module named beginners > > Thanks for the help. Are you talking about this software? http://www.livewires.org.uk/python/package Then you are trying to run it on an incompatible Python version. Quoting: """ The LiveWires package works with Python 2.x, but not (yet) with Python 3.x. """ From hothottrott at gmail.com Thu Nov 10 18:55:18 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 10:55:18 -0700 Subject: [Tutor] How do I get livewires for python version 3.1.1 ? Message-ID: Could you tell me where I can get a free download of livewires for python version 3.1.1 ? And one that does not have a trial period please. I looked and looked but all I found was the one for version 2.x. I thought I had the one for version 3.1.1 but I guess I was wrong. I don't know if I am directing this question to the right people so if not I apologize for any inconvenience. Thanks for your help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Nov 10 19:01:27 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 10 Nov 2011 12:01:27 -0600 Subject: [Tutor] How do I get livewires for python version 3.1.1 ? In-Reply-To: References: Message-ID: On Thu, Nov 10, 2011 at 11:55 AM, Nathaniel Trujillo wrote: > Could you tell me where I can get a free download of livewires for python > version 3.1.1 ? And one that does not have a trial period please. I looked > and looked but all I found was the one for version 2.x. I thought I had the > one for version 3.1.1 but I guess I was wrong. I don't know if I am > directing this question to the right people so if not I apologize for any > inconvenience. > You don't - as someone mentioned in reply to one of your previous emails, Livewires is only for version 2.x. Honestly, the experiences that I had with Livewires didn't give me an impression that it was that much easier to use that just your standard Pygame/Tkinter, both of which are available for Python 3. You would probably be better off picking up Pygame and Tkinter by themselves. I'm under the impression that Livewires isn't a terribly popular package, and there is plentiful documentation for both Pygame and Tkinter. Of course this also assumes that you're at least familiar enough with Python to be able to write the code you need. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From hothottrott at gmail.com Thu Nov 10 19:08:55 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 11:08:55 -0700 Subject: [Tutor] My response to How do I get livewires for python version 3.1.1 ? Message-ID: I actually am not familiar with python enough to know what code to use. Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Thu Nov 10 19:14:21 2011 From: rhettnaxel at gmail.com (Alexander) Date: Thu, 10 Nov 2011 13:14:21 -0500 Subject: [Tutor] Find all strings that.... In-Reply-To: <4A73089D-F715-40E0-8669-1EBF4C48B917@googlemail.com> References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> <4A73089D-F715-40E0-8669-1EBF4C48B917@googlemail.com> Message-ID: > On 11/10/11, Original Poster Alexander Etter wrote: >> >> Hi. My friend gave me a good wake up exercise which I do not want you to >> solve for me: find all strings which can be converted to alpha with at most >> two operations, where alpha is some string constant, and a substring of at >> least length three of alpha must be in the answers. >> So, my question is: is there a library or .txt dictionary ( not the data >> type, rather the merriam webster kind ) I can use to test my script on? I'd >> imagine this library/dictionary to contain thousands of words. Not random >> words. >> Thanks for reading, >> Alexander On 10 Nov 2011, at 16:14, Alex Hall wrote: > What about just grabbing a bit text file, such as from Project > Gutenberg (sorry for the possibly incorrect spelling)? Spelling is correct. No worries. Or copying the > text from a large web-page and pasting it into a text file? I will give this a try sometime, thanks for the suggestions. However, as a member of this mailing list, it is my duty to tell you both that you have top posted in reply to the initial question. Top posting is frowned upon. Consider when John Doe finds this thread, sees the subject line, finds it appealing and decides to read it; only to find the first thing he reads is a response from somebody and not the Original post. Now Mr. Doe is scrambling through the file confused about who sent what first and where the original question is. Maybe me typing in the middle of your reply is bad, but it is distinguishable from your email and I am finding it relevant. > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap ______________ On Thu, Nov 10, 2011 at 11:28 AM, Rich Lovely wrote: > If you're on linux or OSX, there's /usr/share/dict/words, which has a few > thousand words. Although no plurals, which caught me out once. If you're > on windows, it's not a hard file to find. > > > Rich "RoadieRich" Lovely > > There are 10 types of people in the world: > Those who know binary, > Those who do not, > And those who are off by one. > > Thanks Rich. I'm on Ubuntu 11.04 and Trisquel. And will make use of that file. It's an interesting collection of words, but certainly missing some of what I would want to see. Like "better" isn't in there, but "Bette" is. Anyway at least I can start coding with your suggestion. Thanks. And if you haven't seen above, please don't top post. Au revoir. Alexander E. -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From fal at libero.it Thu Nov 10 19:52:58 2011 From: fal at libero.it (Francesco Loffredo) Date: Thu, 10 Nov 2011 19:52:58 +0100 Subject: [Tutor] Find all strings that.... In-Reply-To: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> Message-ID: <4EBC1D8A.6000701@libero.it> Alexander Etter wrote: > > Hi. My friend gave me a good wake up exercise which I do not want you to solve for me: find all strings which can be converted to alpha with at most two operations, where alpha is some string constant, and a substring of at least length three of alpha must be in the answers. I'd like to try this exercise too; would you mind defining "operations" more specifically, please? Given a sufficiently broad meaning of "operations" (e.g. operation = any function call) then any word can be converted into any given word with at most ONE operation. > So, my question is: is there a library or .txt dictionary ( not the data type, rather the merriam webster kind ) I can use to test my script on? I'd imagine this library/dictionary to contain thousands of words. Not random words. http://www.cs.nmsu.edu/~hfugal/cs167/labs/words.txt > Thanks for reading, > Alexander More thanks for writing! Francesco ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 2012.0.1869 / Database dei virus: 2092/4606 - Data di rilascio: 09/11/2011 From waynejwerner at gmail.com Thu Nov 10 20:02:21 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 10 Nov 2011 13:02:21 -0600 Subject: [Tutor] How do I get livewires for python version 3.1.1 ? In-Reply-To: References: Message-ID: On Thu, Nov 10, 2011 at 12:01 PM, Wayne Werner wrote: > > On Thu, Nov 10, 2011 at 11:55 AM, Nathaniel Trujillo < > hothottrott at gmail.com> wrote: > >> Could you tell me where I can get a free download of livewires for python >> version 3.1.1 ? And one that does not have a trial period please. I looked >> and looked but all I found was the one for version 2.x. I thought I had the >> one for version 3.1.1 but I guess I was wrong. I don't know if I am >> directing this question to the right people so if not I apologize for any >> inconvenience. >> > > You don't - as someone mentioned in reply to one of your previous emails, > Livewires is only for version 2.x. > > Honestly, the experiences that I had with Livewires didn't give me an > impression that it was that much easier to use that just your standard > Pygame/Tkinter, both of which are available for Python 3. > > You would probably be better off picking up Pygame and Tkinter by > themselves. I'm under the impression that Livewires isn't a terribly > popular package, and there is plentiful documentation for both Pygame and > Tkinter. > > Of course this also assumes that you're at least familiar enough with > Python to be able to write the code you need. > On Thu, Nov 10, 2011 at 12:08 PM, Nathaniel Trujillo wrote: > I actually am not familiar with python enough to know what code to use. > Thanks for the help. Please don't create a new email or change the subject line, this makes it very difficult for those of us who use thread-based clients to keep the thread of the conversation. I see that your email address is gmail so I know that if you're using their web client that this is not the default behavior. You should definitely read this link http://catb.org/~esr/faqs/smart-questions.html that should have been sent in the email welcoming you to the tutor list. If you're interested in learning to program, there are several great tutorials out there. This one (http://inventwithpython.com/chapters/) uses game design as a way to teach programming concepts. Snake Wrangling for Kids is a great book that's geared towards a younger audience: http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ There are a variety of other tutorials out there, just pick one and get started! HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From hothottrott at gmail.com Thu Nov 10 19:58:07 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 11:58:07 -0700 Subject: [Tutor] sifting through a long program Message-ID: How do I get to line 362 of a program without counting each line ? Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Nov 10 20:35:04 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 10 Nov 2011 14:35:04 -0500 Subject: [Tutor] sifting through a long program In-Reply-To: References: Message-ID: if you are using vim type 262G This is a list for python tutoring. People use a variety of text editors. You should google 'how do I go to a specific line in On Thu, Nov 10, 2011 at 1:58 PM, Nathaniel Trujillo wrote: > How do I get to line 362 of a program without counting each line ? Thanks > for the help. > _______________________________________________ > 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 ranceh at gmail.com Thu Nov 10 20:37:32 2011 From: ranceh at gmail.com (Rance Hall) Date: Thu, 10 Nov 2011 13:37:32 -0600 Subject: [Tutor] Fwd: sifting through a long program In-Reply-To: References: Message-ID: I accidentally replied just to the OP, so I'm forwarding my comments to the list for the record. ---------- Forwarded message ---------- From: Rance Hall Date: Thu, Nov 10, 2011 at 1:36 PM Subject: Re: [Tutor] sifting through a long program To: Nathaniel Trujillo On Thu, Nov 10, 2011 at 12:58 PM, Nathaniel Trujillo wrote: > How do I get to line 362 of a program without counting each line ?? Thanks > for the help. Use an editor with line numbers visible? I've been a silent lurker on this list for awhile learning python as I read what other people were doing with it. The teacher in me wants you to get your questions answered, but the volunteer in me wants you to not waste my time and the time of other people on this list. This is clearly not a python question. It is a question on what tools are needed to write effective code regardless of language. Its starting to appear as if you are too lazy to even try to address your own problems on your own, and with Google at your fingertips there is no excuse for this. Perhaps you are trying, and it just appears as if you are not trying. Perhaps though, you really aren't trying. A word of warning, most of us have email clients that can silently delete messages from specific email addresses without having to read them. You don't want to be on the ignore list for people who can help you but don't want to spoon feed you in the process. Good luck learning python. Rance From maxskywalker1 at gmail.com Thu Nov 10 20:55:47 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Thu, 10 Nov 2011 14:55:47 -0500 Subject: [Tutor] sifting through a long program In-Reply-To: References: Message-ID: Alt+G, or Edit>Go To Line. On Thu, Nov 10, 2011 at 1:58 PM, Nathaniel Trujillo wrote: > How do I get to line 362 of a program without counting each line ? Thanks > for the help. > _______________________________________________ > 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 cranky.frankie at gmail.com Thu Nov 10 21:54:14 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Thu, 10 Nov 2011 15:54:14 -0500 Subject: [Tutor] positional output Message-ID: What is the easiest way in Python 3.x to write output positionally? For example I have one literal I want in column 1, the next one in column 40, the third one in column 50. I've tried usings tabs and I'm not getting what I want. Is it something to do with C style printf formatting? An example would be greatly appreciated. -- Frank L. "Cranky Frankie" Palmeri, Guilderland, NY, USA ? ? ? ? ? ? ?Risible Riding Raconteur & Writer Don't sweat the petty things, and don't pet the sweaty things. From d at davea.name Thu Nov 10 22:24:50 2011 From: d at davea.name (Dave Angel) Date: Thu, 10 Nov 2011 16:24:50 -0500 Subject: [Tutor] positional output In-Reply-To: References: Message-ID: <4EBC4122.6000900@davea.name> On 11/10/2011 03:54 PM, Cranky Frankie wrote: > What is the easiest way in Python 3.x to write output positionally? > For example I have one literal I want in column 1, the next one in > column 40, the third one in column 50. I've tried usings tabs and I'm > not getting what I want. Is it something to do with C style printf > formatting? An example would be greatly appreciated. > Narrow down your environment a bit. Where is this output going? To a file, to a printer, to the console? If the latter, in what environment? The only portable way to position yourself would be to pad with spaces. If you want to output a fixed width string, perhaps you'd want to use the format method of str. -- DaveA From hothottrott at gmail.com Thu Nov 10 22:27:33 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 14:27:33 -0700 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. Message-ID: I decided to try using python version 2.1.3 with pygame version 1.7.1 (I hope they're compatable) and the livewires version that was available at livewires.org.uk, I think it's version 2.1 . After getting the following error message I tried researching the problem myself at bing.com and then google.com. I typed the error into both search engines but the info that I got just led to more questions. For example, the suggestion that I thought most applied to me was to reset the PYTHONPATH to the directory that contains the module games.py but that led to the question how do I do that. So I tried typing help() but that doesn't work in version 2.1.3 so I went to google and typed "how to reset PYTHONPATH in python 2.1.3" and I also typed "how to reset PYTHONPATH" and didn't find much. I was told not to make a new email or change the subject line (which to me basically means to reply) but I was also told by someone not to reply and to make a new email so I didn't know what to do? Also, python is my first language and I started out knowing absolutely nothing about programming so please bare with me. Thanks. here is the code # New Graphics Window # Demonstrates creating a graphics window from livewires import games games.init(screen_width = 640, screen_height = 480, fps = 50) games.mainloop() and here is the error message. I appologize but the error message refered to above is not the same one I just got after running the program again to copy the error messge but here is the message anyway. Actually come to think of it, the first message was ImportError: cannot import name games and the one I just got is Traceback (most recent call last): File "", line 1, in ? File "C:\Python21\new_graphics_window.py", line 4, in ? from livewires import games File "C:\Python21\livewires\games.py", line 59, in ? import pygame, pygame.transform, pygame.draw ImportError: No module named pygame Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Thu Nov 10 22:28:32 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 10 Nov 2011 22:28:32 +0100 Subject: [Tutor] positional output In-Reply-To: References: Message-ID: <4EBC4200.8040204@gmx.net> On 2011-11-10 21:54, Cranky Frankie wrote: > What is the easiest way in Python 3.x to write output positionally? > For example I have one literal I want in column 1, the next one in > column 40, the third one in column 50. I've tried usings tabs and I'm > not getting what I want. Is it something to do with C style printf > formatting? An example would be greatly appreciated. Two ideas: 1) Using string formatting: >>> print("x{0}x{1}x".format(" " * 38, " " * 9)) 2) Using a helper list (assuming screen width = 80): >>> line = [" "] * 80 >>> line[0] = "x" >>> line[39] = "x" >>> line[49] = "x" >>> print("".join(line)) Bye, Andreas From rhettnaxel at gmail.com Thu Nov 10 22:40:22 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Thu, 10 Nov 2011 16:40:22 -0500 Subject: [Tutor] Find all strings that.... In-Reply-To: <4EBC1D8A.6000701@libero.it> References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> <4EBC1D8A.6000701@libero.it> Message-ID: <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> On Nov 10, 2011, at 13:52, Francesco Loffredo wrote: > Alexander Etter wrote: >> >> Hi. My friend gave me a good wake up exercise which I do not want you to solve for me: find all strings which can be converted to alpha with at most two operations, where alpha is some string constant, and a substring of at least length three of alpha must be in the answers. > I'd like to try this exercise too; would you mind defining "operations" more specifically, please? > Given a sufficiently broad meaning of "operations" (e.g. operation = any function call) > then any word can be converted into any given word with at most ONE operation. Consider an operation not as a function. A function could easily contain more than two operations. An operation would remove two letters. An operation would add one letter. Etc. Alexander > >> So, my question is: is there a library or .txt dictionary ( not the data type, rather the merriam webster kind ) I can use to test my script on? I'd imagine this library/dictionary to contain thousands of words. Not random words. > http://www.cs.nmsu.edu/~hfugal/cs167/labs/words.txt >> Thanks for reading, >> Alexander > More thanks for writing! > Francesco > > > ----- > Nessun virus nel messaggio. > Controllato da AVG - www.avg.com > Versione: 2012.0.1869 / Database dei virus: 2092/4606 - Data di rilascio: 09/11/2011 > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From ramit.prasad at jpmorgan.com Fri Nov 11 00:17:58 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 10 Nov 2011 23:17:58 +0000 Subject: [Tutor] positional output In-Reply-To: <4EBC4200.8040204@gmx.net> References: <4EBC4200.8040204@gmx.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF4740126AF@SCACMX008.exchad.jpmchase.net> >1) Using string formatting: > >>> print("x{0}x{1}x".format(" " * 38, " " * 9)) You can specify alignment and padding with string formatting too. It just requires you to know the formatting mini-language. >>> 'x{0:>40}x{1:^30}x{2:<40}'.format( 'right', 'center' , 'left' ) 'x rightx center xleft ' http://docs.python.org/library/string.html See 7.1.3.2 for examples Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Fri Nov 11 00:02:31 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 10 Nov 2011 23:02:31 +0000 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: References: <4EBBCE4B.5030600@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF47401261C@SCACMX008.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of learner404 Sent: Thursday, November 10, 2011 10:44 AM To: Rich Lovely Cc: Tutor Python Subject: Re: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) On Thu, Nov 10, 2011 at 4:33 PM, Rich Lovely wrote: It looks like your script is being found fine, meaning the problem lies elsewhere - unless your actual app is called "avcOsxLinux.py, and you missed renaming it in the error message. ?Try adding a print statement as the very first line - before any imports - to test this. Sorry I missed replacing this one when I copy/pasted on the list; ?avcOsxLinux.py is "myapp.py" (I renamed it for clarity). Unfortunately the problem is still the same.? $ python myapp.py $ python: can't open file 'myapp.py': [Errno 2] No such file or directory The only reference to that filename is a french audio-visual library, which might not be installed on your target system. Rich "RoadieRich" Lovely There are 10 types of people in the world: Those who know binary, Those who do not, And those who are off by one. ==================================================================== You can try using locate or find, but any usage of this is probably system specific and prone to bugs. If you have the option to "install" something you can try setting an environment variable with the location of myapp.py. It is probably easiest to keep myapp.py in the home directory (or subdirectory of it) and say "python ~/myapp.py" (or "python ~/.roadierich/myapp.py) from the applescript Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Fri Nov 11 01:06:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Nov 2011 11:06:58 +1100 Subject: [Tutor] Find all strings that.... In-Reply-To: <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> <4EBC1D8A.6000701@libero.it> <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> Message-ID: <4EBC6722.9000107@pearwood.info> Alexander Etter wrote: > On Nov 10, 2011, at 13:52, Francesco Loffredo wrote: > >> Alexander Etter wrote: >>> Hi. My friend gave me a good wake up exercise which I do not want >>> you to solve for me: find all strings which can be converted to >>> alpha with at most two operations, where alpha is some string >>> constant, and a substring of at least length three of alpha must >>> be in the answers. >> I'd like to try this exercise too; would you mind defining >> "operations" more specifically, please? Given a sufficiently broad >> meaning of "operations" (e.g. operation = any function call) then >> any word can be converted into any given word with at most ONE >> operation. > Consider an operation not as a function. A function could easily > contain more than two operations. An operation would remove two > letters. An operation would add one letter. Etc. Sounds to me like you're discussing edit distance, i.e. given only the three permissible edit operations: delete a letter insert a letter replace a letter with another letter what is the least number of edits needed to go from (say) "winner" to "whiner"? -- Steven From steve at pearwood.info Fri Nov 11 01:32:31 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Nov 2011 11:32:31 +1100 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. In-Reply-To: References: Message-ID: <4EBC6D1F.9050908@pearwood.info> Nathaniel Trujillo wrote: > I decided to try using python version 2.1.3 Nathaniel, that's SIX VERSIONS OLD. That's ancient history. Python 2.1 is missing a lot of important features. Please use at least Python 2.6, 2.7 would be better. I admire your perseverance in the face of adversity. Man, I would have given up by now! Well done. But honestly you're going at this like a bull in a china shop, just charging ahead trying to overcome all obstacles by sheer activity. Time to slow down and work smarter, not harder. Please start off by installing Python 2.6 or 2.7. Unless you have specific reason to use an old version, you should always stick to a recent version: either the newest, or the one before it. (Python 3.x is a bit of a special case.) Once you have installed Python, run this from the command line to test it: python -c "import sys; print sys.version" and tell us what it says. Please copy and paste the exact output, don't re-type it or summarize. It should say something like "2.7.3 blah blah blah...". If it does, launch the Python interactive interpreter by running: python from the command line (with no additional arguments), then when the prompt changes to >>> type this: import pygame If you get an error, please copy and paste the full output. Once you've done that, we'll see what happens next. -- Steven From alan.gauld at btinternet.com Fri Nov 11 01:49:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Nov 2011 00:49:44 +0000 Subject: [Tutor] The python implementation of the "class relationship". In-Reply-To: References: Message-ID: On 10/11/11 09:23, Jerry Zhang wrote: > As you know, there are several kinds of relationships between classes in > the UML -- dependency, association, aggregation, composition. There are several more besides, but lets not get carried away... :-) > Q1. Is there any article or code example on its implementation in python? Probably if you try using google, but the principles are simple. Dependencies are both loose and implicit in Python. If an object uses another object in its implementation there is a dependency relationship, but the dependency is only on the operations exposed by the object not necessarily on the object, or even on its type. Association is likewise loose. If an attribute refers to another object then there is an association. If the referenced object is part of a collection then it is a 1-M association. Aggregation is a form of association and nothing more. Composition is a form of aggregation/association. Because of the way Python variables work object attributes can only ever be references to other objects, they objects are never tightly bound together. The relationships implied by UML are relationships of logical intent. In Python it's up to you to "enforce" the intent by the way you write your code. UML provides a wide variety of modeling concepts which the modeler can use depending on the concept he wishes to convey and also based on the implementation language. If designing for a language like C++ or Java it may make sense to specify precisely which relationship to use. In a freer language, like Python, you may just model everything as associations and/or aggregation. UML does not require anything more specific any more than it requires that you include deployment designs or state machines. They are tools in the toolbox, that's all. If you are sculpting in plasticine you probably don't need your power chisel, if you are using granite it might be useful. Pick the tool for the job. > Q2. More specific, in composition model, the container object may be > responsible for the handling of embedded objects' lifecycle. The common > way would be adding __del__ to the container class or something else? That would be one way, and of course by having an __init__ method too. You might even go one step further and use a __new__ so that the relationship is already extant by the time the program hits __init__ -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Nov 11 02:00:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Nov 2011 01:00:31 +0000 Subject: [Tutor] sifting through a long program In-Reply-To: References: Message-ID: On 10/11/11 18:58, Nathaniel Trujillo wrote: > How do I get to line 362 of a program without counting each line ? > Thanks for the help. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor M-x goto-line If you are using emacs. But you hardly ever need to do that because most IDEs will take you there from an error message. And if they don't searching for the text on the line is often easier. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hothottrott at gmail.com Fri Nov 11 02:01:57 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 18:01:57 -0700 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. Message-ID: Okay, I typed into the command line of version 2.7.2, python -c "import sys; print sys.version". I tried it with and without the quotes. I tried copying the error messages from the command line but it wouldn't let me so I copied them from the python shell instead. here is what I got after typing it in with the quotes SyntaxError: invalid syntax and I got the same exact message when I typed it in without the quotes. This happened in both the command line and the shell. So that's what I got so far. Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 11 02:03:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Nov 2011 01:03:12 +0000 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. In-Reply-To: References: Message-ID: On 10/11/11 21:27, Nathaniel Trujillo wrote: > I decided to try using python version 2.1.3 with pygame version 1.7.1 Why so old? Python 2.1 was about 10 years ago! The current version of PyGame should work with Python v2.6 or 2.7 both readily available from python.org -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Nov 11 02:34:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 11 Nov 2011 12:34:58 +1100 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. In-Reply-To: References: Message-ID: <4EBC7BC2.6070603@pearwood.info> Nathaniel Trujillo wrote: > Okay, I typed into the command line of version 2.7.2, python -c "import > sys; print sys.version". I tried it with and without the quotes. I tried > copying the error messages from the command line but it wouldn't let me so > I copied them from the python shell instead. You're running that command from *inside* Python. I asked: Once you have installed Python, run this from the command line to test it: python -c "import sys; print sys.version" I'm sorry, I should have been more explicit that I meant from your system command line, the shell or command.exe or cmd.com, not from inside Python. You should see a prompt ending with % or possibly % but not Python's prompt >>>. My intention is to ensure that the bare python command is working correctly. Later on, I asked you to: launch the Python interactive interpreter by running: python which implies that you *hadn't* launched the interactive interpreter before this point. Sorry for the confusion. -- Steven From d at davea.name Fri Nov 11 02:47:43 2011 From: d at davea.name (Dave Angel) Date: Thu, 10 Nov 2011 20:47:43 -0500 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. In-Reply-To: References: Message-ID: <4EBC7EBF.40602@davea.name> On 11/10/2011 08:01 PM, Nathaniel Trujillo wrote: > Okay, I typed into the command line of version 2.7.2, python -c "import > sys; print sys.version". I tried it with and without the quotes. I tried > copying the error messages from the command line but it wouldn't let me so > I copied them from the python shell instead. > > here is what I got after typing it in with the quotes > > SyntaxError: invalid syntax > > and I got the same exact message when I typed it in without the quotes. > This happened in both the command line and the shell. > > So that's what I got so far. Thanks for the help. > You're apparently on Windows. You need to understand the difference between being at a cmd prompt, being at the python interpreter, and maybe being in whatever shell you're using. You also need to be able to copy & paste from the cmd window (console window, dos box, whatever). There are menu items that let you select a rectangular section of the console box and copy it to the clipboard. it's been too long for me to remember, but try right-click on the cmd window. Without pasting exactly what you're doing (and not just the error msg), people are going to continue being frustrated. -- DaveA From hothottrott at gmail.com Fri Nov 11 03:00:13 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 19:00:13 -0700 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. Message-ID: Okay, I typed in python -c "import sys; print sys.version" at the command prompt. I didn't see a prompt ending with %. Instead I saw a prompt ending with >. But here is the message I got. Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\net2010>python -c "import sys; print sys.version" 'python' is not recognized as an internal or external command, operable program or batch file. C:\Users\net2010> Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jerry.scofield at gmail.com Fri Nov 11 03:39:59 2011 From: jerry.scofield at gmail.com (Jerry Zhang) Date: Fri, 11 Nov 2011 10:39:59 +0800 Subject: [Tutor] The python implementation of the "class relationship". In-Reply-To: References: Message-ID: 2011/11/11 Alan Gauld > On 10/11/11 09:23, Jerry Zhang wrote: > >> As you know, there are several kinds of relationships between classes in >> the UML -- dependency, association, aggregation, composition. >> > > There are several more besides, but lets not get carried away... :-) > > > Q1. Is there any article or code example on its implementation in python? >> > > Probably if you try using google, but the principles are simple. > I tried and failed to find some code example. So i maybe i have to do such very carefully by myself. > > Dependencies are both loose and implicit in Python. > If an object uses another object in its implementation there is a > dependency relationship, but the dependency is only on the operations > exposed by the object not necessarily on the object, or even on > its type. > > Association is likewise loose. If an attribute refers to another object > then there is an association. If the referenced object is part of a > collection then it is a 1-M association. > > Aggregation is a form of association and nothing more. > > Composition is a form of aggregation/association. > > Because of the way Python variables work object attributes can only ever > be references to other objects, they objects are never tightly bound > together. > Very fair comments. It deserve a big thanks. > > The relationships implied by UML are relationships of logical intent. In > Python it's up to you to "enforce" the intent by the way you write your > code. UML provides a wide variety of modeling concepts which the modeler > can use depending on the concept he wishes to convey and also based on the > implementation language. If designing for a language like C++ or Java it > may make sense to specify precisely which relationship to use. In a freer > language, like Python, you may just model everything as associations and/or > aggregation. UML does not require anything more specific any more than it > requires that you include deployment designs or state machines. They are > tools in the toolbox, that's all. If you are sculpting in plasticine you > probably don't need your power chisel, if you are using granite it might be > useful. Pick the tool for the job. To my understand, python's feature such as "name-reference-object" and "garbage collection" system did some of work for you, it makes your life easier, but you still need to add your explicit application in your code. For example, Composition implementation: you may need to do 5 job with C++, but only 2 job with python, the other 3 job is done by python implicitly. association implementation: You need 3 job with C++, but 1 with python. it seems python's object's lifecycle handling has reached this level, all you should do is just "associating and de-association". Here is exactly of my question, for composition, the best code may be you do 2 job explicitly, 3 job done by python implicitly. Code_Zero. 1 job(by you) + 4(by python) does NOT work. Code_one. 2 job(by you) + 3(by python) works. That is the best one. Code_two. 3 job( by you) + 2 (by python) works too, Code_three. 4 job(by you) + 1(by python) works too. Since i am not familiar with python yet, my code most likely would gets into Code_two or Code_three(Code_Zero is also possible for new guys like me), though they also work, they are bad code. What i am looking for is the Code_one example, i thought many OOP application designer may have met this issue, so a good Code_one reference is the best choice to start this project. > > Q2. More specific, in composition model, the container object may be >> responsible for the handling of embedded objects' lifecycle. The common >> way would be adding __del__ to the container class or something else? >> > > That would be one way, and of course by having an __init__ method too. > You might even go one step further and use a __new__ so that the > relationship is already extant by the time the program hits __init__ > > -- > Alan G > 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 hothottrott at gmail.com Fri Nov 11 03:41:54 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Thu, 10 Nov 2011 19:41:54 -0700 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. Message-ID: Okay this time I think it worked because it said 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] then I typed python at the command prompt and the little >>> came up. Then I typed import pygame but I did not get an error, it just prompted me again like this >>>. Thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Nov 11 03:50:09 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 11 Nov 2011 10:50:09 +0800 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: On Fri, Nov 11, 2011 at 1:21 AM, Peter Otten <__peter__ at web.de> wrote: > lina wrote: > >> Hi, >> >> I tested the one from >> > http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring >> >> mainly: >> >> #!/usr/bin/python3 >> >> a=['1','2','3','7'] >> >> b=['2','3','7'] >> >> def LongestCommonSubstring(S1, S2): >> ? ? ? ? M = [[0]*(1+len(S2)) for i in range(1+len(S1))] >> ? ? ? ? longest, x_longest = 0, 0 >> ? ? ? ? for x in range(1,1+len(S1)): >> ? ? ? ? ? ? ? ? for y in range(1,1+len(S2)): >> ? ? ? ? ? ? ? ? ? ? ? ? M[x][y] = M[x-1][y-1]+1 >> ? ? ? ? ? ? ? ? ? ? ? ? if M[x][y] > longest: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? longest = M[x][y] >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? x_longest = x >> ? ? ? ? ? ? ? ? ? ? ? ? else: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? M[x][y] = 0 >> ? ? ? ? return S1[x_longest-longest:x_longest] >> >> >> if __name__=="__main__": >> ? ? ? ? print(LongestCommonSubstring(a,b)) >> >> $ python3 LongestCommonSubstring.py >> ['1', '2', '3'] >> >> The results isn't right. > > That's not the code from the site you quote. You messed it up when you tried > to convert it to Python 3 (look for the suspicious 8-space indent) > You are right. also correct it to 4-space indention now. Thanks. > Hint: the function doesn't contain anything specific to Python 2 or 3, apart > from the xrange builtin. If you add the line > > xrange = range Thanks, I did not realize I could substitute the xrange to range this way. cool. > > to your code the unaltered version will run in Python 3 -- and produce the > correct result: > > $ cat longest_common_substring3.py > xrange = range > > def LongestCommonSubstring(S1, S2): > ? ?M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] > ? ?longest, x_longest = 0, 0 > ? ?for x in xrange(1,1+len(S1)): > ? ? ? ?for y in xrange(1,1+len(S2)): > ? ? ? ? ? ?if S1[x-1] == S2[y-1]: I did not understand the code well, and the if S1[x-1] == S2[y-1]: was missing during I was typing ( I did not copy/paste, try to type to enhance the learning) > ? ? ? ? ? ? ? ?M[x][y] = M[x-1][y-1] + 1 > ? ? ? ? ? ? ? ?if M[x][y]>longest: > ? ? ? ? ? ? ? ? ? ?longest = M[x][y] > ? ? ? ? ? ? ? ? ? ?x_longest ?= x > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?M[x][y] = 0 > ? ?return S1[x_longest-longest: x_longest] > > if __name__ == "__main__": > ? ?a = ['1','2','3','7'] > ? ?b = ['2','3','7'] > > ? ?print(LongestCommonSubstring(a, b)) > $ python3 longest_common_substring3.py > ['2', '3', '7'] > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lina.lastname at gmail.com Fri Nov 11 04:24:54 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 11 Nov 2011 11:24:54 +0800 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: On Fri, Nov 11, 2011 at 1:23 AM, Walter Prins wrote: > Hi, > > On 10 November 2011 16:23, lina wrote: >> >> def LongestCommonSubstring(S1, S2): >> ? ? ? ?M = [[0]*(1+len(S2)) for i in range(1+len(S1))] >> ? ? ? ?longest, x_longest = 0, 0 >> ? ? ? ?for x in range(1,1+len(S1)): >> ? ? ? ? ? ? ? ?for y in range(1,1+len(S2)): >> ? ? ? ? ? ? ? ? ? ? ? ?M[x][y] = M[x-1][y-1]+1 >> ? ? ? ? ? ? ? ? ? ? ? ?if M[x][y] > longest: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?longest = M[x][y] >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?x_longest = x >> ? ? ? ? ? ? ? ? ? ? ? ?else: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?M[x][y] = 0 >> ? ? ? ?return S1[x_longest-longest:x_longest] > > This is not the same as the implementation given on wikibooks.... Have you > tried reverting your changes and using the coe that was given on the site > exactly as is?? (I assume not, and if so, why not?) I used python3, it showed me NameError: name 'xrange' is not defined so I made a little changes, before I even worried I might forget to import some modules to make the xrange work. > > (Specifically, I notice most the likely culprit is a missing if statement > just below the "for y in range..." line that's been deleted....) Thanks for that. adding this missing line, works. I am still lack of understanding how the code works, so made above mistake. > >> >> The results isn't right. > > Yes.? You appear to have introduced a bug by not using the same code as what > was given on the wiki page.? (Why did you modify the code and then when the > modified code didn't work assume the original solution was broken instead of > checking first and/or suspecting that your changes may have broken it?) Sorry. I did not assume the original code was broken, might a little unconsciously worry it might be out of date at that time. I checked by eyes, bad, and did not check carefully. Thanks with best regards, > > Walte > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From lina.lastname at gmail.com Fri Nov 11 05:14:33 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 11 Nov 2011 12:14:33 +0800 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: #!/usr/bin/python3 import os.path xrange = range c=['71', '82', '80', '70', '84', '56', '58', '34', '77', '76', '61', '76', '34', '76', '58', '34', '56', '61', '65', '82', '65', '80', '65', '82', '80', '82', '65', '82', '61', '80', '82', '65', '61', '63', '65', '70', '80', '71', '34', '71', '64', '34', '58', '61', '80', '34', '40', '72', '38', '4', '70', '72', '40', '72', '4', '72', '42', '69', '40', '70', '40', '61', '40', '34', '61', '33', '34', '61', '34', '35', '61', '35', '61', '70', '61', '34', '61', '34', '54', '34', '32', '35', '59', '55', '59', '34', '43', '32', '34', '32', '24', '34', '32', '35', '32', '43', '34', '32', '34', '45', '35', '32', '83', '61', '58', '32', '58', '83', '32', '34', '61', '52', '34', '32', '34', '84', '32', '52', '34', '57', '34', '52', '20', '58', '34', '32', '34', '58', '34', '58', '61', '34', '30', '35', '28', '52', '22', '21', '22', '30', '61', '79', '70', '80', '70', '65', '61', '80', '59', '52', '61', '20', '30', '20', '58', '20', '29', '74', '58', '20', '31', '20', '31', '57', '31', '34', '20', '58', '34', '52', '34', '20', '58', '83', '58', '34', '61', '34', '32', '76', '34', '35', '52', '77', '76', '74', '76', '58', '20', '57', '58', '33', '76', '58', '52', '74', '20', '36', '61', '36', '74', '61', '36', '83', '61', '83', '31', '61', '59', '33', '36', '61', '20', '34', '84', '70', '61', '36', '61', '36', '77', '20', '38', '36', '61', '59', '38', '10', '38', '36', '38', '77', '36', '39', '38', '36', '23', '26', '8', '36', '8', '19', '8', '19', '8', '19', '20', '8', '36', '34', '8', '21', '8', '28', '22', '18', '10', '20', '76', '36', '57', '20', '26', '10', '20', '28', '33', '35', '36', '34', '36', '20', '34', '10', '36', '76', '57', '76', '57', '16', '10', '59', '20', '19', '59', '20', '28', '20', '37', '23', '38', '21', '23', '79', '32', '29', '36', '29', '31', '29', '36', '20', '34', '79', '23', '20', '28', '20', '79', '74', '34', '20', '59', '32', '20', '23', '28', '20', '10', '56', '22', '56', '52', '57', '28', '76', '74', '20', '34', '77', '20', '36', '22', '61', '59', '22', '20', '22', '21', '23', '20', '61', '59', '77', '22', '34', '58', '20', '34', '28', '29', '22', '8', '22', '23', '20', '59', '22', '20', '57', '20', '57', '22', '77', '20', '76', '36', '20', '77', '23', '35', '77', '20', '8', '74', '10', '76', '20', '34', '10', '31', '20', '33', '59', '61', '42', '41'] d=['45', '64', '13', '5', '64', '45', '13', '15', '13', '16', '10', '7', '16', '10', '8', '16', '8', '10', '13', '64', '10', '45', '64', '43', '64', '47', '64', '43', '64', '45', '47', '45', '15', '43', '17', '64', '47', '64', '62', '75', '16', '60', '45', '64', '13', '64', '75', '45', '47', '64', '75', '64', '60', '64', '60', '64', '58', '60', '64', '45', '16', '64', '58', '16', '58', '60', '64', '7', '60', '64', '7', '64', '47', '10', '64', '58', '64', '60', '58', '64', '58', '75', '60', '64', '45', '64', '45', '58', '45', '60', '64', '58', '64', '45', '60', '58', '75', '58', '75', '45', '60', '58', '60', '58', '7', '13', '58', '49', '57', '64', '49', '63', '50', '63', '49', '50', '81', '61', '49', '69', '70', '49', '39', '48', '83', '29', '52', '39', '29', '52', '37', '52', '29', '52', '27', '83', '52', '83', '52', '39', '27', '39', '27', '39', '41', '27', '29', '39', '27', '83', '29', '39', '27', '29', '41', '39', '61', '28', '41', '81', '28', '41', '28', '41', '81', '36', '51', '61', '59', '53', '48', '53', '83', '59', '48', '59', '53', '57', '41', '83', '61', '42', '81', '61', '40', '79', '41', '28', '59', '27', '33', '28', '41', '83', '79', '81', '41', '61', '29', '39', '28', '61', '39', '28', '42', '41', '31', '41', '84', '82', '84', '61', '31', '41', '61', '41', '82', '28', '41', '57', '48', '59', '83', '48', '83', '48', '57', '61', '57', '83', '42', '48', '61', '46', '48', '51', '59', '51', '81', '51', '57', '51', '81', '51', '57', '48', '59', '48', '83', '61', '83', '48', '81', '60', '48', '51', '48', '57', '48', '51', '74', '53', '51', '53', '51', '81', '52', '51', '61', '51', '41', '61', '83', '81', '83', '61', '81', '39', '28', '41', '84', '42', '61', '36', '61', '63', '84', '83', '41', '72', '41', '37', '39', '41', '82', '41', '61', '28', '39', '28', '41', '39', '28', '41', '83', '41', '83', '61', '84', '83', '84', '83', '51', '61', '83', '40', '83', '63', '61', '59', '28', '84', '42', '28', '84', '61', '40', '41', '40', '41', '63', '84', '63', '59', '83', '61', '59', '61', '39', '84', '72', '61', '40', '84', '61', '83', '42', '59', '36', '40', '61', '63', '61', '59', '61', '40', '29', '61', '29', '61', '39', '61', '31', '61', '70', '61'] def LongestCommonSubstring(S1, S2): M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] ## creat 4*5 matrix longest, x_longest = 0, 0 for x in xrange(1,1+len(S1)): ## read each row for y in xrange(1,1+len(S2)): ## read each coloumn if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1]+1 if M[x][y] > longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 return S1[x_longest-longest:x_longest] if __name__=="__main__": a=open("atom-pair_4.txt","r").readline().strip() b=open("atom-pair_8.txt","r").readline().strip() print(LongestCommonSubstring(LongestCommonSubstring(a,a),LongestCommonSubstring(b,b))) print(LongestCommonSubstring(c,d)) $ python3 LongestCommonSubstring.py 2189 [' ['82'] The results are wrong. c, d are the string from file atom-pair_4,txt, exactly the same as a, d is the same as b. and even for (c,d) results are not correct, visually we can see some similar groups, not mention the longest groups. Thanks, P.S the 4 and 8 file are attached: zip one https://docs.google.com/open?id=0B93SVRfpVVg3ZWVmYWM5N2UtNzZjNy00M2NmLWI4ODYtYTVjMTQxZmQ3YjBh tar.gz one https://docs.google.com/open?id=0B93SVRfpVVg3MDY3NmI2NDQtOGJiMS00ODk4LWExMWEtZWIyODYyZGMxNTY3 Thanks again, From delegbede at dudupay.com Fri Nov 11 06:45:25 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Fri, 11 Nov 2011 05:45:25 +0000 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. In-Reply-To: References: Message-ID: <1375336573-1320990325-cardhu_decombobulator_blackberry.rim.net-1210955616-@b18.c12.bise7.blackberry> If you didn't get any error and you were returned to the prompt as you mentioned, it means pygame has been successfully imported. Try running a pygame command to confirm. If you type pygame at the prompt, it should tell you the location of pygame on your system. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Nathaniel Trujillo Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 10 Nov 2011 19:41:54 To: Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. _______________________________________________ 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 Nov 11 09:58:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 11 Nov 2011 08:58:23 +0000 Subject: [Tutor] The python implementation of the "class relationship". In-Reply-To: References: Message-ID: On 11/11/11 02:39, Jerry Zhang wrote: > Composition implementation: you may need to do 5 job with C++, but only > 2 job with python, the other 3 job is done by python implicitly. > association implementation: You need 3 job with C++, but 1 with python. > it seems python's object's lifecycle handling has reached this level, > all you should do is just "associating and de-association". I have no idea what you mean by that. What kind of "job" are you talking about? > Code_Zero. 1 job(by you) + 4(by python) does NOT work. > Code_one. 2 job(by you) + 3(by python) works. That is the best one. > Code_two. 3 job( by you) + 2 (by python) works too, > Code_three. 4 job(by you) + 1(by python) works too. > > Since i am not familiar with python yet, my code most likely would gets > into Code_two or Code_three(Code_Zero is also possible for new guys like > me), though they also work, they are bad code. Again, I don't understand your references to Code_one, Code_two etc? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Michael at shamirlens.co.uk Fri Nov 11 12:22:03 2011 From: Michael at shamirlens.co.uk (Michael M Mason) Date: Fri, 11 Nov 2011 11:22:03 +0000 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. In-Reply-To: References: Message-ID: <5378B081D0A21C45A6135E92E182BD7F4DC2BD76@Mail1-Shamir.shamir.org.il> On 11 November 2011 at 02:00 Nathaniel Trujillo wrote:- > Okay, I typed in python -c "import sys; print sys.version" at the command > prompt. I didn't see a prompt ending with %. Instead I saw a prompt ending > with >. But here is the message I got. > > Microsoft Windows [Version 6.1.7600] > Copyright (c) 2009 Microsoft Corporation.? All rights reserved. > C:\Users\net2010>python -c "import sys; print sys.version" > 'python' is not recognized as an internal or external command, > operable program or batch file. > C:\Users\net2010> This is normal with Python on Windows. The Python installer doesn't add the program directory to the PATH, so you have to include the full pathname to run Python from the command line, something like this:- C:\Python27\python -c "import sys; print sys.version" -- Michael This mail was sent via Mail-SeCure System. ************************************************************************************ This footnote confirms that this email message has been scanned by PineApp Mail-SeCure for the presence of malicious code, vandals & computer viruses. ************************************************************************************ From cwitts at compuscan.co.za Fri Nov 11 12:54:42 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 11 Nov 2011 13:54:42 +0200 Subject: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one. In-Reply-To: References: Message-ID: <4EBD0D02.1080304@compuscan.co.za> On 2011/11/11 04:00 AM, Nathaniel Trujillo wrote: > Okay, I typed in python -c "import sys; print sys.version" at the > command prompt. I didn't see a prompt ending with %. Instead I saw a > prompt ending with >. But here is the message I got. > Microsoft Windows [Version 6.1.7600] > Copyright (c) 2009 Microsoft Corporation. All rights reserved. > C:\Users\net2010>python -c "import sys; print sys.version" > 'python' is not recognized as an internal or external command, > operable program or batch file. > C:\Users\net2010> > Thanks for the help. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor R-Click on My Computer -> Properties -> Advanced -> Environment Variables -> Under "System Variables" find PATH, select it, and click Edit -> Add your Python path to the end eg. c:\python27 (you will need to seperate it from all the other entries using a semi-colon, like c:\program files;c:\windows;c:\python27) -> Click OK about 3 times till you've closed all the windows -> Open a new Command Prompt and run python -c "import sys; print sys.version" -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Fri Nov 11 13:59:25 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Fri, 11 Nov 2011 07:59:25 -0500 Subject: [Tutor] positional output Message-ID: Thank you for your help on this. Now for "the rest of the story." I'm trying to build a script to parse IBM AIX DB2 DDL to line up the data types (it drives me crazy when the column data types are not lined up). For example, typical create table DDL might be hundreds of lines long but will look like this: -- -- table create DDL -- CREATE TABLE FRANK.TEST ( COLUMN1 DECIMAL(8), COLUMN2 CHAR(20), COLUMN3 TIMESTAMP, COLUMN4 INTEGER, COLUMN5 DATE NOT NULL WITH DEFAULT, -- repeat for hundreds of columns ); COMMENT ON TABLE FRANK.TEST IS 'TEST TABLE'; This is just a small sample, there are many other possible lines, but I'm only concerned about the column lines like COLUMN1 through COLUMN5 above. I have a script on Windows that reads in the DDL file and writes out each line to a new file. What I'm doing is using the split() function to test for the presence of any DB2 standard data type, like CHAR, INTEGER, SMALINT, etc. If I find one I want to use positional output to make each like look like: COLUMN1 DECIMAL(8), COLUMN2 CHAR(20), COLUMN3 TIMESTAMP, COLUMN4 INTEGER, COLUMN5 DATE NOT NULL WITH DEFAULT, where all the COLUMNs would be in column 1 of the output file, the data types would be in column 40, and the comma would be next. The problem is handling lines that have NOT NULL WITH DEFAULT at the end. The thing is there could be other valid DDL in that position, and there may or may not be a comma after the data type. What I want to do is just take anything after the datatype, which would be element(1) in the split() output, and just write it out. I thought I could use rsplit() to do this, but you can't put the output of split() in rsplit() - I tried. I need to do something like, after verifying that element(1) is a valid DB2 datatype, just take everything else on the line after it, which may be a single comma, or NOT NULL WITH DEFAULT, or something else, and place it on the output line to be written out. So, to reiterate: I'm trying to build a script to line up the data types in a create table DDL file. Splitting each line into individual space separated elements, then checking for a valid data type, the rebuilding the line positionally seems to be the way to go. If there's an easyier way to do it I'm all ears. I don't have my script available at the moment but I could send it if it would be helpful. -- Frank L. "Cranky Frankie" Palmeri, Guilderland, NY, USA ? ? ? ? ? ? ?Risible Riding Raconteur & Writer Don't sweat the petty things, and don't pet the sweaty things. From andreas.perstinger at gmx.net Fri Nov 11 14:10:37 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 11 Nov 2011 14:10:37 +0100 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: <4EBD1ECD.7020806@gmx.net> On 2011-11-11 05:14, lina wrote: > def LongestCommonSubstring(S1, S2): > M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] ## creat 4*5 matrix > longest, x_longest = 0, 0 > for x in xrange(1,1+len(S1)): ## read each row > for y in xrange(1,1+len(S2)): ## read each coloumn > if S1[x-1] == S2[y-1]: > M[x][y] = M[x-1][y-1]+1 > if M[x][y]> longest: > longest = M[x][y] > x_longest = x > else: > M[x][y] = 0 > return S1[x_longest-longest:x_longest] That's still not the right version. If you compare your version to the one at wikibooks ( http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python ), you'll see that the else-branch is wrongly indented (one level too deep). It belongs to the first if-comparison: if S1 ... M[x][y] ... if M[x][y] ... ... else: ... > if __name__=="__main__": > > a=open("atom-pair_4.txt","r").readline().strip() > > b=open("atom-pair_8.txt","r").readline().strip() > > print(LongestCommonSubstring(LongestCommonSubstring(a,a),LongestCommonSubstring(b,b))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ??? What do you try to accomplish here ??? You call "LongestCommonSubstring" with identical strings, thus the result must be the same string. Why not print(LongestCommonSubstring(a, b)) as you did the line below with "c" and "d"? Further more I think that your problems start with bad data files. In every file there is just one very long line which looks like a string representation of a list of two-digits strings. This complicates further processing because you have to deal with all the unnecessary commas, blanks and single quotes between your numbers and the square brackets at the beginning and the end of the line. > $ python3 LongestCommonSubstring.py > 2189 > [' > ['82'] > > The results are wrong. > c, d are the string from file atom-pair_4,txt, exactly the same as a, > d is the same as b. > > and even for (c,d) results are not correct, visually we can see some > similar groups, not mention the longest groups. And even if you use the correct function from wikibooks I can anticipate another problem :-) The implementation from wikibooks just returns the first common substring which it finds in the first string: >>> WikibooksLongestCommonSubstring("ABAB","BABA") 'ABA' >>> WikibooksLongestCommonSubstring("BABA", "ABAB") 'BAB' If there are more possible substrings with the same length (as in the example above) only the first one is returned. But in your example there are at least two different pathways (I've found three) which have the same length, as changing the order of the parameters will show you: >>> WikibooksLongestCommonSubstring(c, d) ['61', '70', '61'] >>> WikibooksLongestCommonSubstring(d, c) ['83', '61', '83'] Bye, Andreas From lina.lastname at gmail.com Fri Nov 11 14:44:15 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 11 Nov 2011 21:44:15 +0800 Subject: [Tutor] longest common substring In-Reply-To: <4EBD1ECD.7020806@gmx.net> References: <4EBD1ECD.7020806@gmx.net> Message-ID: On Fri, Nov 11, 2011 at 9:10 PM, Andreas Perstinger wrote: > On 2011-11-11 05:14, lina wrote: >> >> def LongestCommonSubstring(S1, S2): >> ? ? M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] ## creat 4*5 matrix >> ? ? longest, x_longest = 0, 0 >> ? ? for x in xrange(1,1+len(S1)): ? ? ? ? ? ? ? ? ## read each row >> ? ? ? ? for y in xrange(1,1+len(S2)): ? ? ? ? ? ? ## read each coloumn >> ? ? ? ? ? ? if S1[x-1] == S2[y-1]: >> ? ? ? ? ? ? ? ? M[x][y] = M[x-1][y-1]+1 >> ? ? ? ? ? ? ? ? if M[x][y]> ?longest: >> ? ? ? ? ? ? ? ? ? ? longest = M[x][y] >> ? ? ? ? ? ? ? ? ? ? x_longest = x >> ? ? ? ? ? ? ? ? else: >> ? ? ? ? ? ? ? ? ? ? M[x][y] = 0 >> ? ? return S1[x_longest-longest:x_longest] > > That's still not the right version. > > If you compare your version to the one at wikibooks ( > http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python > ), you'll see that the else-branch is wrongly indented (one level too deep). > It belongs to the first if-comparison: > > if S1 ... > ? ? M[x][y] ... > ? ? if M[x][y] ... > ? ? ? ?... > else: ... Thanks, I was so careless and most important failure to give a deep understanding. > > >> if __name__=="__main__": >> >> ? ? a=open("atom-pair_4.txt","r").readline().strip() >> >> ? ? b=open("atom-pair_8.txt","r").readline().strip() >> >> >> print(LongestCommonSubstring(LongestCommonSubstring(a,a),LongestCommonSubstring(b,b))) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^^^^^^^^^^^^^^^^^^^^^^^^^^^ > ??? What do you try to accomplish here ??? > You call "LongestCommonSubstring" with identical strings, thus the result > must be the same string. Yes, the results is the same string, actually I want to remove the distractions of "," and as you noticed, the blanks and single quotes between numbers and the square brackets at the two terminal of the line. a=open("atom-pair_4.txt","r").readline().strip() read so many unnecessary and I have a trouble of removing those distractions. > Why not > > print(LongestCommonSubstring(a, b)) > > as you did the line below with "c" and "d"? > > Further more I think that your problems start with bad data files. In every > file there is just one very long line which looks like a string > representation of a list of two-digits strings. This complicates further > processing because you have to deal with all the unnecessary commas, blanks > and single quotes between your numbers and the square brackets at the > beginning and the end of the line. > > >> ?$ python3 LongestCommonSubstring.py >> 2189 >> [' >> ['82'] >> >> The results are wrong. >> c, d are the string from file atom-pair_4,txt, exactly the same as a, >> d is the same as b. >> >> and even for (c,d) results are not correct, visually we can see some >> similar groups, not mention the longest groups. > > And even if you use the correct function from wikibooks I can anticipate > another problem :-) > The implementation from wikibooks just returns the first common substring > which it finds in the first string: > >>>> WikibooksLongestCommonSubstring("ABAB","BABA") > 'ABA' >>>> WikibooksLongestCommonSubstring("BABA", "ABAB") > 'BAB' > > If there are more possible substrings with the same length (as in the > example above) only the first one is returned. You are right, I did not think of this parts before. and actually the initiative wish was to find possible paths, I mean, possible substrings, all possible substrings. not the longest one, but at least bigger than 3. > > But in your example there are at least two different pathways (I've found > three) which have the same length, as changing the order of the parameters > will show you: > >>>> WikibooksLongestCommonSubstring(c, d) > ['61', '70', '61'] >>>> WikibooksLongestCommonSubstring(d, c) > ['83', '61', '83'] > > Bye, Andreas Thanks for your time, Best regards, > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From cwitts at compuscan.co.za Fri Nov 11 14:59:38 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 11 Nov 2011 15:59:38 +0200 Subject: [Tutor] positional output In-Reply-To: References: Message-ID: <4EBD2A4A.6020008@compuscan.co.za> On 2011/11/11 02:59 PM, Cranky Frankie wrote: > Thank you for your help on this. Now for "the rest of the story." > > I'm trying to build a script to parse IBM AIX DB2 DDL to line up the > data types (it drives me crazy when the column data types are not > lined up). For example, typical create table DDL might be hundreds of > lines long but will look like this: > > Something like this ? I left out checking for valid types etc, just something rudimentary to maybe point you in the right direction. >>> a = """COLUMN1 DECIMAL(8), ... COLUMN2 CHAR(20), ... COLUMN3 TIMESTAMP, ... COLUMN4 INTEGER, ... COLUMN5 DATE NOT NULL WITH DEFAULT, ... COLUMN6 CHAR(40) ... """ >>> >>> for line in a.splitlines(): ... newline = line.split() ... col_name = newline[0] ... col_type = newline[1].replace(',', '') ... field_sep = ',' if ',' in line else '' ... print '%-40s%s%s' % (col_name, col_type, field_sep) ... COLUMN1 DECIMAL(8), COLUMN2 CHAR(20), COLUMN3 TIMESTAMP, COLUMN4 INTEGER, COLUMN5 DATE, COLUMN6 CHAR(40) If all you want to space it out nicely then .split(' ', 1) and '%-40s%s' % (part1, part2) should work fine for you. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Fri Nov 11 15:01:39 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 11 Nov 2011 15:01:39 +0100 Subject: [Tutor] positional output In-Reply-To: References: Message-ID: On Fri, Nov 11, 2011 at 1:59 PM, Cranky Frankie wrote: > Thank you for your help on this. Now for "the rest of the story." > > I'm trying to build a script to parse IBM AIX DB2 DDL to line up the > data types (it drives me crazy when the column data types are not > lined up). For example, typical create table DDL might be hundreds of > lines long but will look like this: > > -- > -- table create DDL > -- > CREATE TABLE FRANK.TEST ( > COLUMN1 ? ? DECIMAL(8), > COLUMN2 ? ? ? ? ? CHAR(20), > COLUMN3 ? ? ? ? ? ? ? ? ? ?TIMESTAMP, > COLUMN4 ? ? INTEGER, > COLUMN5 ? ? ? ? ?DATE NOT NULL WITH DEFAULT, > -- repeat for hundreds of columns > ); > COMMENT ON TABLE FRANK.TEST IS 'TEST TABLE'; > > This is just a small sample, there are many other possible lines, but > I'm only concerned about the column lines like COLUMN1 through COLUMN5 > above. > > I have a script on Windows that reads in the DDL file and writes out > each line to a new file. What I'm doing is using the split() function > to test for the presence of any DB2 standard data type, like CHAR, > INTEGER, SMALINT, etc. If I find one I want to use positional output > to make each like look like: > > COLUMN1 ? ? ? ? ? ? ? ? ? ? ? ?DECIMAL(8), > COLUMN2 ? ? ? ? ? ? ? ? ? ? ? ?CHAR(20), > COLUMN3 ? ? ? ? ? ? ? ? ? ? ? ?TIMESTAMP, > COLUMN4 ? ? ? ? ? ? ? ? ? ? ? ? INTEGER, > COLUMN5 ? ? ? ? ? ? ? ? ? ? ? ? DATE NOT NULL WITH DEFAULT, > > where all the COLUMNs would be in column 1 of the output file, the > data types would be in column 40, and the comma would be next. > > The problem is handling lines that have NOT NULL WITH DEFAULT at the > end. The thing is there could be other valid DDL in that position, and > there may or may not be a comma after the data type. What I want to do > is just take anything after the datatype, which would be element(1) in > the split() output, and just write it out. I thought I could use > rsplit() to do this, but you can't put the output of split() in > rsplit() - I tried. > > I need to do something like, after verifying that element(1) is a > valid DB2 datatype, just take everything else on the line after it, > which may be a single comma, or NOT NULL WITH DEFAULT, or something > else, and place it on the output line to be written out. > > So, to reiterate: I'm trying to build a script to line up the data > types in a create table DDL file. Splitting each line into individual > space separated elements, then checking for a valid data type, the > rebuilding the line positionally seems to be the way to go. If there's > an easyier way to do it I'm all ears. > > I don't have my script available at the moment but I could send it if > it would be helpful. > I would suggest using str.split(None, 1) to limit the amount of splits done to only 1, which means you get a list like ['COLUMN', 'DATA TYPE ETC']. Then you use the str.startswith function to check the second entry for data types, something like so (note startswith accepts a tuple of strings to look for: if splitted_line[1].startswith(data_types): print "%s %s" % (splitted_line[0].ljust(39), splitted_line[1]) HTH, Hugo From wprins at gmail.com Fri Nov 11 15:09:41 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 11 Nov 2011 14:09:41 +0000 Subject: [Tutor] positional output In-Reply-To: References: Message-ID: Hi Frankie, On 11 November 2011 12:59, Cranky Frankie wrote: > I'm trying to build a script to parse IBM AIX DB2 DDL to line up the > data types (it drives me crazy when the column data types are not > lined up). For example, typical create table DDL might be hundreds of > lines long but will look like this: > Just knocked this up: http://pastie.org/2847380 It reformats the example you posted, at least, and should leave lines that are not field definitions alone (thanks to looking for the start of the datatype after the space.) Hopefully you can get some inspiration form it. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Nov 11 15:18:03 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 11 Nov 2011 22:18:03 +0800 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> Message-ID: Based on former advice, I made a correction/modification on the below code. 1] the set and subgroup does not work, here I wish to put all the subgroup in a big set, the set like $ python3 LongestCommonSubstring.py | uniq {"1',"} {"1', "} {"1', '"} {"1', '8"} {"1', '82"} {"1', '82'"} {"1', '82',"} {"1', '82', "} {"1', '82', '"} {"6', '61', '6"} {"', '61', '63'"} {"', '61', '63',"} {"', '61', '63', "} {"', '61', '63', '"} {"', '61', '63', '6"} {"', '61', '70', '61"} {"', '61', '70', '61'"} {"', '83', '61', '83',"} {"', '83', '61', '83', "} {"', '83', '61', '83', '"} Please kindly notice I added a pipeline with uniq at the end, the true prints were lots of replications, I don't know how to handle it in the python code. 2] I still have trouble in reading files, mainly about not read "" etc. Thanks with best regards, #!/usr/bin/python3 import os.path xrange = range subgroups=[] subgroup=[] def LongestCommonSubstring(S1, S2): M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] longest, x_longest = 0, 0 for x in xrange(1,1+len(S1)): for y in xrange(1,1+len(S2)): if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1]+1 if M[x][y] > longest: longest = M[x][y] x_longest = x if longest >= 3: subgroup=S1[x_longest-longest:x_longest] subgroups=set([subgroup]) print(subgroups) else: M[x][y] = 0 return S1[x_longest-longest:x_longest] if __name__=="__main__": a=open("atom-pair_4.txt","r").readline().strip() b=open("atom-pair_8.txt","r").readline().strip() LongestCommonSubstring(a,b) From pankajjakhar5 at gmail.com Fri Nov 11 15:29:47 2011 From: pankajjakhar5 at gmail.com (Pankaj Jakhar) Date: Fri, 11 Nov 2011 19:59:47 +0530 Subject: [Tutor] Suggest Book Message-ID: Hello Please suggest me the best book for Python from which I can learn basics to advanced Python. Thank you. *____________ PankaJ **Jakhar** * -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdsimpson at gmail.com Fri Nov 11 15:37:43 2011 From: tdsimpson at gmail.com (Troy S) Date: Fri, 11 Nov 2011 09:37:43 -0500 Subject: [Tutor] Suggest Book In-Reply-To: References: Message-ID: I would recommend: Beginning Python: From Novice to Professional. See attached URL below. Website is also a good resource. http://trizpug.org/up-to-speed On Fri, Nov 11, 2011 at 9:29 AM, Pankaj Jakhar wrote: > Hello > > Please suggest me the best book for Python from which I can learn basics to > advanced Python. > > Thank you. > ____________ > PankaJ Jakhar > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Troy S From lina.lastname at gmail.com Fri Nov 11 15:32:00 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 11 Nov 2011 22:32:00 +0800 Subject: [Tutor] longest common substring In-Reply-To: <4EBD1ECD.7020806@gmx.net> References: <4EBD1ECD.7020806@gmx.net> Message-ID: On Fri, Nov 11, 2011 at 9:10 PM, Andreas Perstinger wrote: > On 2011-11-11 05:14, lina wrote: >> >> def LongestCommonSubstring(S1, S2): >> ? ? M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] ## creat 4*5 matrix >> ? ? longest, x_longest = 0, 0 >> ? ? for x in xrange(1,1+len(S1)): ? ? ? ? ? ? ? ? ## read each row >> ? ? ? ? for y in xrange(1,1+len(S2)): ? ? ? ? ? ? ## read each coloumn >> ? ? ? ? ? ? if S1[x-1] == S2[y-1]: >> ? ? ? ? ? ? ? ? M[x][y] = M[x-1][y-1]+1 >> ? ? ? ? ? ? ? ? if M[x][y]> ?longest: >> ? ? ? ? ? ? ? ? ? ? longest = M[x][y] >> ? ? ? ? ? ? ? ? ? ? x_longest = x >> ? ? ? ? ? ? ? ? else: >> ? ? ? ? ? ? ? ? ? ? M[x][y] = 0 >> ? ? return S1[x_longest-longest:x_longest] > > That's still not the right version. > > If you compare your version to the one at wikibooks ( > http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python > ), you'll see that the else-branch is wrongly indented (one level too deep). > It belongs to the first if-comparison: > > if S1 ... > ? ? M[x][y] ... > ? ? if M[x][y] ... > ? ? ? ?... > else: ... > > >> if __name__=="__main__": >> >> ? ? a=open("atom-pair_4.txt","r").readline().strip() >> >> ? ? b=open("atom-pair_8.txt","r").readline().strip() >> >> >> print(LongestCommonSubstring(LongestCommonSubstring(a,a),LongestCommonSubstring(b,b))) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?^^^^^^^^^^^^^^^^^^^^^^^^^^^ > ??? What do you try to accomplish here ??? > You call "LongestCommonSubstring" with identical strings, thus the result > must be the same string. > Why not > > print(LongestCommonSubstring(a, b)) > > as you did the line below with "c" and "d"? > > Further more I think that your problems start with bad data files. In every > file there is just one very long line which looks like a string > representation of a list of two-digits strings. This complicates further > processing because you have to deal with all the unnecessary commas, blanks > and single quotes between your numbers and the square brackets at the > beginning and the end of the line. > > >> ?$ python3 LongestCommonSubstring.py >> 2189 >> [' >> ['82'] >> >> The results are wrong. >> c, d are the string from file atom-pair_4,txt, exactly the same as a, >> d is the same as b. >> >> and even for (c,d) results are not correct, visually we can see some >> similar groups, not mention the longest groups. > > And even if you use the correct function from wikibooks I can anticipate > another problem :-) > The implementation from wikibooks just returns the first common substring > which it finds in the first string: > >>>> WikibooksLongestCommonSubstring("ABAB","BABA") > 'ABA' >>>> WikibooksLongestCommonSubstring("BABA", "ABAB") > 'BAB' > > If there are more possible substrings with the same length (as in the > example above) only the first one is returned. > > But in your example there are at least two different pathways (I've found > three) which have the same length, as changing the order of the parameters > will show you: > >>>> WikibooksLongestCommonSubstring(c, d) > ['61', '70', '61'] >>>> WikibooksLongestCommonSubstring(d, c) > ['83', '61', '83'] The residues of WikibooksLongestCommonSubstring(d, c) and WikibooksLongestCommonSubstring(c,d) is different very largely, I mean, it might be totally different. so the possible subgroups are the union of groups of (d,c) and (c,d)? I am really lack a programed-brain to think. Thanks again, > > Bye, Andreas > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From malaclypse2 at gmail.com Fri Nov 11 16:53:32 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 11 Nov 2011 10:53:32 -0500 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: There's nothing wrong with writing your own code to find the longest common substring, but are you aware that python has a module in the standard library that already does this? In the difflib module, the SequenceMatcher class can compare two sequences and extract the longest common sequence of elements from it, like this: Code: import difflib a = [1, 2, 3, 7] b = [2, 3, 7] seq_matcher = difflib.SequenceMatcher(None, a, b) print seq_matcher.find_longest_match(0, len(a), 0, len(b)) Outputs: Match(a=1, b=0, size=3) See http://docs.python.org/library/difflib.html#sequencematcher-objects for lots of details. The SequenceMatcher class can do a lot more than finding the common substrings, as you might expect. The Module of the Week article for difflib may also be of interest: http://www.doughellmann.com/PyMOTW/difflib/index.html -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Fri Nov 11 17:04:11 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Fri, 11 Nov 2011 11:04:11 -0500 Subject: [Tutor] Suggest Book In-Reply-To: References: Message-ID: On Nov 11, 2011, at 9:29, Pankaj Jakhar wrote: > Hello > > Please suggest me the best book for Python from which I can learn basics to advanced Python. > > Thank you. > ____________ > PankaJ Jakhar > I'm sure Alan or one of our veteran list members will have something to say, but at my school for a class called "intro to problem solving" or something like that CS1114, the book used is by T. Gaddis, "Introduction to Python". I think. I may be incorrect. I'll check it out on amazon. Alexander > _______________________________________________ > Tutor - 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 lina.lastname at gmail.com Fri Nov 11 17:41:43 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 00:41:43 +0800 Subject: [Tutor] how can I save it from "for" Message-ID: Hi, I don't know how to escape the if longest >= 3: subgroup=S1[x_longest-longest:x_longest] print(subgroup) form the loop. xrange = range subgroup=[] def LongestCommonSubstring(S1, S2): M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] longest, x_longest = 0, 0 subgroups=[] uniq={} for x in xrange(1,1+len(S1)): for y in xrange(1,1+len(S2)): if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1]+1 if M[x][y] > longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 if longest >= 3: subgroup=S1[x_longest-longest:x_longest] print(subgroup) return S1[x_longest-longest:x_longest] if __name__=="__main__": for i in range(97,107): for j in range(97,107): if i != j: LongestCommonSubstring(a,b) '''LongestCommonSubstring(chr(i),chr(j))''' Thanks ahead, From bodsda at googlemail.com Fri Nov 11 17:45:20 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Fri, 11 Nov 2011 16:45:20 +0000 Subject: [Tutor] how can I save it from "for" In-Reply-To: References: Message-ID: <1806651015-1321029922-cardhu_decombobulator_blackberry.rim.net-909691548-@b4.c12.bise7.blackberry> Look into the 'continue' and 'break' statements - both very handy when working with loops Or just increment/decrement the conditional until it evaluates to False Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: lina Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Sat, 12 Nov 2011 00:41:43 To: tutor Subject: [Tutor] how can I save it from "for" Hi, I don't know how to escape the if longest >= 3: subgroup=S1[x_longest-longest:x_longest] print(subgroup) form the loop. xrange = range subgroup=[] def LongestCommonSubstring(S1, S2): M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] longest, x_longest = 0, 0 subgroups=[] uniq={} for x in xrange(1,1+len(S1)): for y in xrange(1,1+len(S2)): if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1]+1 if M[x][y] > longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 if longest >= 3: subgroup=S1[x_longest-longest:x_longest] print(subgroup) return S1[x_longest-longest:x_longest] if __name__=="__main__": for i in range(97,107): for j in range(97,107): if i != j: LongestCommonSubstring(a,b) '''LongestCommonSubstring(chr(i),chr(j))''' Thanks ahead, _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From lina.lastname at gmail.com Fri Nov 11 17:02:31 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 00:02:31 +0800 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: I wrote a crazy one, to find the common group: Please jump to the end part of this code: https://docs.google.com/open?id=0B93SVRfpVVg3MDUzYzI1MDYtNmI5MS00MmZkLTlmMTctNmE3Y2EyYzIyZTk2 Thanks again, From lina.lastname at gmail.com Fri Nov 11 18:06:27 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 01:06:27 +0800 Subject: [Tutor] failed to load functions, Message-ID: Hi, sorry for the new post: if __name__=="__main__": for i in range(97,100): for j in range(97,100): if i != j: s1=chr(i)+"List" s2=chr(j)+"List" '''print(s1,s2)''' LongestCommonSubstring(s1,s2) I am surprised the results showed like below: $ python3 CommonSubstring.py Lis List Lis List Lis List Lis List Lis List Lis List and print(s1,s2) '''LongestCommonSubstring(s1,s2)''' showed me: aList bList aList cList bList aList bList cList cList aList cList bList exactly I wanted, but seems s1, s2 failed to go into functions. Thanks, From lina.lastname at gmail.com Fri Nov 11 18:09:24 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 01:09:24 +0800 Subject: [Tutor] failed to load functions, In-Reply-To: References: Message-ID: I attached the clumsy one as below: https://docs.google.com/open?id=0B93SVRfpVVg3YTNhNTMwODUtMDkyYi00ZTk4LThiOGYtMzdkNzI1ZmNhOWQ0 #!/usr/bin/python3 import os.path from collections import Counter aList=['55', '34', '77', '43', '58', '34', '77', '34', '76', '34', '77', '76', '32', '72', '34', '41', '34', '56', '70', '45', '43', '45', '34', '45', '34', '45', '76', '77', '76', '77', '76', '77', '76', '77', '76', '77', '76', '77', '82', '43', '77', '34', '77', '61', '59', '82', '65', '55', '71', '82', '80', '65', '71', '82', '65', '64', '65', '80', '84', '80', '82', '58', '74', '76', '58', '76', '74', '76', '57', '34', '57', '77', '34', '52', '84', '34', '57', '35', '34', '32', '55', '53', '34', '35', '34', '32', '54', '34', '54', '57', '54', '34', '57', '54', '57', '34', '54', '34', '54', '57', '54', '34', '57', '54', '34', '32', '34', '57', '34', '54', '35', '54', '34', '58', '77', '34', '77', '34', '53', '76', '58', '34', '56', '54', '58', '34', '57', '34', '56', '77', '54', '56', '34', '77', '76', '77', '76', '77', '53', '77', '56', '34', '32', '34', '54', '32', '54', '32', '34', '32', '54', '32', '34', '55', '61', '54', '34', '32', '54', '32', '54', '55', '34', '32', '34', '54', '34', '55', '32', '54', '34', '57', '54', '34', '54', '57', '34', '55', '59', '33', '59', '55', '34', '54', '59', '34', '55', '34', '54', '35', '57', '34', '54', '34', '55', '34', '54', '57', '55', '54', '34', '57', '34', '33', '34', '20', '54', '55', '54', '34', '54', '32', '54', '32', '34', '54', '32', '54', '32', '54', '34', '32', '34', '57', '34', '54', '35', '34', '32', '59', '34', '54', '34', '55', '33', '34', '55', '34', '35', '34', '54', '34', '32', '34', '35', '34', '54', '34', '54', '34', '54', '34', '53', '34', '57', '20', '58', '57', '76', '58', '74', '76', '55', '59', '57', '34', '57', '34', '77', '34', '54', '56', '34', '56', '54', '34', '56', '34', '54', '58', '32', '54', '76', '34', '76', '53', '34', '77', '32', '34', '77', '32', '54', '34', '32', '34', '57', '34', '32', '55', '32', '54', '32', '34', '54', '55', '54', '55', '56', '32', '76', '53', '76', '34', '53', '76', '57', '76', '53', '34', '58', '34', '54', '76', '77', '34', '76', '34', '32', '34', '35', '32', '34', '53', '76', '53', '57', '53', '34', '76', '53', '76', '34', '76', '53', '76', '57', '53', '76', '57', '76', '53', '76'] bList=['77', '34', '60', '84', '76', '34', '76', '34', '46', '59', '77', '34', '77', '82', '34', '33', '34', '82', '34', '77', '70', '58', '34', '49', '58', '49', '35', '49', '32', '61', '34', '58', '61', '58', '61', '35', '61', '70', '61', '70', '61', '34', '20', '61', '34', '58', '32', '34', '32', '58', '20', '35', '20', '34', '21', '59', '21', '34', '21', '34', '21', '34', '21', '34', '21', '34', '21', '34', '21', '34', '21', '34', '21', '34', '21', '34', '21', '59', '34', '21', '34', '21', '34', '21', '34', '21', '34', '32', '34', '61', '20', '61', '32', '34', '35', '34', '58', '34', '58', '32', '34', '58', '46', '20', '32', '61', '20', '34', '58', '34', '32', '58', '34', '32', '70', '32', '34', '30', '34', '32', '30', '61', '32', '35', '61', '32', '34', '30', '61', '58', '32', '20', '34', '20', '32', '61', '30', '20', '61', '20', '83', '35', '32', '34', '61', '34', '61', '34', '20', '32', '61', '32', '58', '32', '27', '32', '61', '59', '61', '70', '30', '59', '61', '32', '83', '30', '32', '34', '33', '80', '32', '35', '80', '59', '80', '70', '80', '81', '61', '81', '34', '32', '33', '30', '23', '27', '20', '33', '22', '27', '35', '22', '27', '22', '23', '22', '31', '22', '35', '22', '33', '22', '35', '33', '22', '31', '35', '22', '20', '2', '37', '34', '84', '33', '34', '33', '84', '36', '83', '33', '36', '69', '84', '38', '40', '38', '4', '37', '6', '1', '3', '35', '3', '38', '27', '3', '5', '3', '5', '27', '3', '27', '5', '27', '26', '3', '5', '28', '3', '28', '5', '28', '3', '28', '19', '28', '26', '37', '26', '37', '26', '37', '3', '37', '3', '26', '3', '26', '25', '19', '37', '24', '3', '5', '3', '1', '5', '1', '3', '23', '37', '24', '3', '24', '35', '23', '5', '3', '24', '3', '24', '1', '24', '3', '24', '3', '5', '3', '5', '2', '25', '5', '3', '24', '25', '5', '25', '3', '22', '3', '5', '3', '23', '3', '24', '3', '5', '3', '1', '5', '22', '1', '24', '3', '24', '3', '5', '3', '5'] cList=['19', '14', '39', '15', '43', '19', '43', '15', '13', '17', '14', '17', '43', '17', '1', '14', '2', '39', '1', '14', '39', '14', '13', '19', '14', '19', '14', '19', '39', '22', '39', '1', '39', '22', '39', '22', '39', '22', '39', '1', '17', '19', '39', '22', '14', '39', '22', '39', '1', '19', '4', '22', '14', '19', '17', '14', '19', '4', '22', '20', '1', '20', '22', '20', '1', '39', '1', '20', '38', '39', '20', '39', '22', '39', '1', '39', '1', '38', '22', '38', '39', '19', '14', '19', '3', '1', '3', '2', '3', '14', '3', '4', '14', '1', '14', '1', '14', '66', '14', '22', '14', '2', '14', '1', '14', '39', '14', '28', '14', '27', '19', '14', '29', '14', '21', '19', '43', '19', '23', '45', '29', '1', '21', '28', '8', '50', '53', '58', '46', '64', '58', '64', '62', '58', '52', '10', '13', '62', '13', '10', '75', '64', '58', '64', '75', '43', '13', '46', '64', '58', '64', '58', '52', '47', '52', '14', '20', '34', '47', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '76', '34', '48', '34', '46', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '34', '48', '76', '46', '48', '34', '52', '34', '48', '34', '48', '34', '48', '34', '48'] dList=['71', '82', '80', '70', '84', '56', '58', '34', '77', '76', '61', '76', '34', '76', '58', '34', '56', '61', '65', '82', '65', '80', '65', '82', '80', '82', '65', '82', '61', '80', '82', '65', '61', '63', '65', '70', '80', '71', '34', '71', '64', '34', '58', '61', '80', '34', '40', '72', '38', '4', '70', '72', '40', '72', '4', '72', '42', '69', '40', '70', '40', '61', '40', '34', '61', '33', '34', '61', '34', '35', '61', '35', '61', '70', '61', '34', '61', '34', '54', '34', '32', '35', '59', '55', '59', '34', '43', '32', '34', '32', '24', '34', '32', '35', '32', '43', '34', '32', '34', '45', '35', '32', '83', '61', '58', '32', '58', '83', '32', '34', '61', '52', '34', '32', '34', '84', '32', '52', '34', '57', '34', '52', '20', '58', '34', '32', '34', '58', '34', '58', '61', '34', '30', '35', '28', '52', '22', '21', '22', '30', '61', '79', '70', '80', '70', '65', '61', '80', '59', '52', '61', '20', '30', '20', '58', '20', '29', '74', '58', '20', '31', '20', '31', '57', '31', '34', '20', '58', '34', '52', '34', '20', '58', '83', '58', '34', '61', '34', '32', '76', '34', '35', '52', '77', '76', '74', '76', '58', '20', '57', '58', '33', '76', '58', '52', '74', '20', '36', '61', '36', '74', '61', '36', '83', '61', '83', '31', '61', '59', '33', '36', '61', '20', '34', '84', '70', '61', '36', '61', '36', '77', '20', '38', '36', '61', '59', '38', '10', '38', '36', '38', '77', '36', '39', '38', '36', '23', '26', '8', '36', '8', '19', '8', '19', '8', '19', '20', '8', '36', '34', '8', '21', '8', '28', '22', '18', '10', '20', '76', '36', '57', '20', '26', '10', '20', '28', '33', '35', '36', '34', '36', '20', '34', '10', '36', '76', '57', '76', '57', '16', '10', '59', '20', '19', '59', '20', '28', '20', '37', '23', '38', '21', '23', '79', '32', '29', '36', '29', '31', '29', '36', '20', '34', '79', '23', '20', '28', '20', '79', '74', '34', '20', '59', '32', '20', '23', '28', '20', '10', '56', '22', '56', '52', '57', '28', '76', '74', '20', '34', '77', '20', '36', '22', '61', '59', '22', '20', '22', '21', '23', '20', '61', '59', '77', '22', '34', '58', '20', '34', '28', '29', '22', '8', '22', '23', '20', '59', '22', '20', '57', '20', '57', '22', '77', '20', '76', '36', '20', '77', '23', '35', '77', '20', '8', '74', '10', '76', '20', '34', '10', '31', '20', '33', '59', '61', '42', '41'] eList=['45', '46', '47', '10', '16', '11', '45', '47', '44', '47', '46', '45', '16', '75', '64', '47', '43', '73', '43', '73', '47', '73', '62', '73', '62', '73', '16', '73', '43', '73', '47', '49', '43', '75', '73', '47', '13', '62', '73', '47', '75', '62', '73', '62', '73', '47', '73', '62', '73', '62', '73', '62', '73', '62', '73', '62', '73', '62', '73', '16', '73', '16', '48', '16', '45', '16', '45', '47', '64', '47', '8', '64', '16', '43', '10', '47', '49', '8', '47', '52', '49', '56', '49', '9', '49', '52', '10', '51', '56', '49', '57', '49', '57', '20', '45', '57', '10', '45', '56', '47', '49', '56', '44', '57', '52', '15', '49', '11', '52', '11', '52', '11', '77', '11', '48', '50', '11', '48', '11', '49', '52', '11', '13', '11', '48', '11', '48', '49', '48', '11', '52', '17', '52', '50', '48', '46', '48', '46', '17', '46', '17', '15', '10', '15', '16', '45', '17', '47', '10', '46', '43', '19', '43', '6', '47', '46', '43', '46', '6', '43', '76', '43', '44', '76', '6', '43', '76', '78', '43', '6', '46', '6', '76', '6', '46', '76', '46', '76', '44', '16', '6', '78', '44', '78', '10', '78', '76', '78', '43', '76', '78', '76', '46', '16', '44', '76', '43', '49', '48', '47', '49', '43', '49', '16', '10', '43', '76', '78', '76', '48', '16', '76', '43', '6', '15', '10', '50', '49', '50', '49', '10', '17', '46', '52', '50', '47', '48', '47', '6', '10', '48', '47', '6', '48', '47', '48', '47', '6', '47', '48', '47', '6', '48', '47', '6', '52', '45', '6', '52', '6', '10', '43', '17', '43', '52', '6', '76', '16', '50', '48', '16', '50', '16', '48', '50', '48', '46', '48', '16', '50', '52', '51', '48', '16', '48', '50', '48', '16', '48', '16', '48', '16', '48', '50', '62', '50', '58', '52', '50', '60', '52', '46', '50', '60', '50', '52', '76', '58', '52', '76', '50', '52', '50', '62', '46', '50', '60', '48', '50', '48', '52', '48'] fList=['77', '20', '76', '20', '30', '20', '76', '26', '61', '76', '46', '59', '34', '45', '34', '45', '34', '32', '45', '34', '45', '32', '45', '20', '10', '14', '15', '16', '14', '10', '14', '15', '10', '15', '10', '7', '18', '15', '14', '16', '15', '45', '16', '64', '75', '64', '47', '45', '64', '45', '47', '16', '7', '47', '44', '16', '10', '75', '10', '15', '64', '15', '76', '10', '15', '10', '15', '20', '23', '21', '26', '24', '28', '84', '28', '22', '29', '19', '27', '22', '37', '39', '28', '81', '84', '55', '22', '38', '84', '22', '84', '22', '28', '84', '55', '84', '22', '83', '22', '42', '84', '31', '40', '84', '39', '40', '84', '69', '42', '55', '61', '84', '28', '27', '42', '29', '42', '81', '42', '55', '27', '31', '27', '41', '28', '39', '20', '39', '1', '28', '83', '84', '55', '84', '27', '28', '84', '28', '53', '28', '42', '84', '22', '84', '28', '29', '28', '24', '83', '33', '31', '28', '84', '28', '83', '28', '19', '29', '33', '31', '33', '28', '39', '27', '42', '33', '28', '34', '28', '29', '39', '27', '31', '28', '27', '29', '28', '40', '42', '28', '55', '84', '31', '28', '39', '28', '27', '83', '2', '28', '31', '28', '81', '28', '36', '30', '40', '27', '33', '26', '25', '20', '22', '31', '22', '20', '22', '74', '34', '76', '34', '20', '22', '34', '45', '76', '45', '48', '60', '45', '48', '32', '48', '76', '45', '48', '76', '32', '34', '32', '34', '32', '76', '34', '32', '34', '48', '76', '34', '48', '34', '47', '45', '20', '56', '76', '46', '60', '48', '32', '58', '34', '45', '35', '34', '20', '34', '20', '34', '20', '19', '34', '32', '35', '34', '20', '34', '20', '31', '34', '20', '31', '34', '48', '57', '50', '57', '83', '48', '55', '59', '82', '58', '55', '41', '55', '41', '55', '70', '72', '70', '55', '70', '41', '55', '70', '55', '61', '55', '61', '55', '70', '42', '70', '58', '70', '55', '34', '70', '55', '70', '55', '70', '55', '70', '55', '41', '55', '58', '70', '55', '80'] gList=['59', '49', '56', '53', '61', '70', '80', '61', '84', '71', '84', '61', '55', '84', '82', '55', '59', '61', '65', '71', '70', '82', '84', '42', '70', '82', '70', '42', '69', '56', '69', '80', '84', '42', '82', '65', '56', '82', '56', '82', '71', '82', '42', '71', '82', '55', '61', '80', '84', '80', '82', '71', '84', '61', '84', '61', '84', '80', '61', '70', '82', '84', '56', '53', '82', '55', '84', '55', '53', '82', '53', '82', '53', '56', '82', '53', '55', '53', '41', '49', '84', '71', '56', '84', '61', '55', '65', '84', '65', '58', '65', '63', '82', '61', '65', '55', '63', '82', '55', '82', '80', '65', '80', '56', '82', '61', '53', '61', '82', '61', '53', '70', '55', '61', '53', '56', '70', '82', '42', '82', '61', '82', '61', '31', '33', '58', '52', '58', '57', '58', '51', '48', '58', '49', '57', '51', '48', '49', '51', '52', '51', '49', '52', '49', '47', '49', '58', '52', '49', '51', '60', '51', '57', '51', '49', '51', '49', '52', '49', '52', '49', '52', '48', '49', '52', '49', '51', '52', '49', '51', '49', '52', '49', '58', '49', '52', '49', '57', '52', '49', '53', '52', '57', '54', '52', '84', '52', '84', '57', '82', '57', '84', '82', '57', '84', '52', '58', '43', '15', '34', '31', '58', '76', '34', '32', '34', '35', '34', '60', '84', '60', '57', '58', '74', '34', '60', '34', '76', '34', '76', '34', '76', '34', '76', '34', '76', '34', '76', '34', '76', '34', '76', '34', '16', '34', '26', '11', '14', '26', '15', '20', '34', '59', '33', '74', '34', '26', '20', '26', '34', '60', '76', '60', '76', '34', '60', '34', '76', '34', '76', '60', '76', '32', '76', '32', '34', '76', '77', '34', '20', '60', '58', '52', '57', '60', '77', '34', '47', '77', '58', '77', '34', '47', '76', '74', '43', '46', '44', '43', '27', '43', '44', '5', '43', '5', '3', '48', '19', '3', '5', '64', '45', '5', '48', '5', '13', '5', '48', '47', '4', '47', '45', '19', '47', '4', '64', '19', '5', '47', '48', '47', '45', '47', '5', '64', '5', '47', '5', '48', '47', '5', '47', '5', '13', '46', '5', '64', '45', '5', '47', '48', '47', '5', '13', '48', '5', '64', '5', '48', '4', '5', '45', '48', '5', '64', '5'] hList=['45', '64', '13', '5', '64', '45', '13', '15', '13', '16', '10', '7', '16', '10', '8', '16', '8', '10', '13', '64', '10', '45', '64', '43', '64', '47', '64', '43', '64', '45', '47', '45', '15', '43', '17', '64', '47', '64', '62', '75', '16', '60', '45', '64', '13', '64', '75', '45', '47', '64', '75', '64', '60', '64', '60', '64', '58', '60', '64', '45', '16', '64', '58', '16', '58', '60', '64', '7', '60', '64', '7', '64', '47', '10', '64', '58', '64', '60', '58', '64', '58', '75', '60', '64', '45', '64', '45', '58', '45', '60', '64', '58', '64', '45', '60', '58', '75', '58', '75', '45', '60', '58', '60', '58', '7', '13', '58', '49', '57', '64', '49', '63', '50', '63', '49', '50', '81', '61', '49', '69', '70', '49', '39', '48', '83', '29', '52', '39', '29', '52', '37', '52', '29', '52', '27', '83', '52', '83', '52', '39', '27', '39', '27', '39', '41', '27', '29', '39', '27', '83', '29', '39', '27', '29', '41', '39', '61', '28', '41', '81', '28', '41', '28', '41', '81', '36', '51', '61', '59', '53', '48', '53', '83', '59', '48', '59', '53', '57', '41', '83', '61', '42', '81', '61', '40', '79', '41', '28', '59', '27', '33', '28', '41', '83', '79', '81', '41', '61', '29', '39', '28', '61', '39', '28', '42', '41', '31', '41', '84', '82', '84', '61', '31', '41', '61', '41', '82', '28', '41', '57', '48', '59', '83', '48', '83', '48', '57', '61', '57', '83', '42', '48', '61', '46', '48', '51', '59', '51', '81', '51', '57', '51', '81', '51', '57', '48', '59', '48', '83', '61', '83', '48', '81', '60', '48', '51', '48', '57', '48', '51', '74', '53', '51', '53', '51', '81', '52', '51', '61', '51', '41', '61', '83', '81', '83', '61', '81', '39', '28', '41', '84', '42', '61', '36', '61', '63', '84', '83', '41', '72', '41', '37', '39', '41', '82', '41', '61', '28', '39', '28', '41', '39', '28', '41', '83', '41', '83', '61', '84', '83', '84', '83', '51', '61', '83', '40', '83', '63', '61', '59', '28', '84', '42', '28', '84', '61', '40', '41', '40', '41', '63', '84', '63', '59', '83', '61', '59', '61', '39', '84', '72', '61', '40', '84', '61', '83', '42', '59', '36', '40', '61', '63', '61', '59', '61', '40', '29', '61', '29', '61', '39', '61', '31', '61', '70', '61'] iList=['3', '5', '3', '8', '5', '1', '5', '7', '4', '6', '68', '7', '8', '14', '6', '8', '7', '14', '39', '19', '14', '39', '19', '22', '14', '22', '2', '14', '22', '14', '22', '14', '22', '14', '22', '14', '2', '22', '14', '20', '14', '19', '14', '19', '14', '4', '14', '2', '14', '22', '2', '14', '19', '22', '14', '22', '14', '19', '20', '22', '14', '22', '14', '22', '14', '22', '14', '22', '14', '22', '14', '22', '14', '22', '14', '22', '14', '2', '14', '22', '14', '4', '22', '14', '22', '20', '22', '2', '14', '22', '14', '22', '14', '3', '64', '47', '65', '64', '65', '67', '65', '7', '3', '69', '68', '3', '7', '68', '5', '68', '69', '22', '68', '13', '12', '4', '6', '5', '6', '3', '69', '68', '13', '1', '3', '5', '6', '3', '9', '68', '8', '6', '4', '3', '26', '22', '26', '22', '26', '28', '77', '54', '76', '58', '76', '77', '58', '60', '58', '55', '58', '55', '53', '34', '56', '53', '56', '76', '55', '76', '58', '60', '34', '60', '77', '35', '76', '60', '76', '35', '34', '35', '34', '35', '34', '32', '60', '34', '32', '34', '76', '32', '76', '34', '33', '77', '20', '16', '14', '20', '32', '20', '28', '20', '19', '21', '20', '31', '34', '76', '34', '32', '34', '77', '76', '46', '76', '37', '20', '60', '74', '34', '20', '34', '31', '20', '15', '22', '1', '46', '76', '34', '32', '34', '32', '34', '76', '16', '46', '62', '46', '75', '64', '16', '62', '46', '65', '46', '43', '46', '67', '62', '46', '13', '43', '66', '67', '64', '69', '67', '69', '67', '65', '62', '46', '45', '13', '68', '46', '68', '13', '12', '13', '62', '66', '13', '10', '13', '65', '64', '68', '10', '13', '68', '10', '64', '65', '5', '68', '62', '8', '43', '46', '65', '64', '16', '46', '65', '62', '66', '16', '68', '13', '69', '16', '65', '62', '64', '68', '65', '75', '12', '65', '68', '65', '13', '68', '13', '5', '68', '13', '68', '64', '68', '13', '8', '9', '13', '65', '68', '65', '68', '5', '13', '66', '43', '8', '64', '68', '11', '64', '43', '69', '5', '68', '8', '67', '66', '13', '75', '64', '5', '64', '75', '64', '75', '62', '12', '68', '64', '5', '16', '68', '13', '66', '13', '66', '13'] jList=['7', '65', '42', '65', '46', '20', '10', '43', '50', '43', '47', '52', '46', '65', '70', '15', '6', '26', '1', '26', '28', '58', '50', '30', '28', '76', '43', '33', '45', '33', '43', '45', '33', '31', '29', '83', '31', '43', '20', '29', '31', '77', '29', '77', '31', '20', '31', '43', '31', '76', '45', '34', '46', '60', '46', '60', '75', '64', '46', '60', '13', '44', '13', '46', '64', '75', '60', '13', '75', '13', '64', '44', '62', '13', '64', '16', '75', '13', '66', '14', '65', '43', '5', '19', '7', '5', '7', '64', '5', '75', '5', '64', '14', '64', '14', '75', '14', '5', '13', '5', '14', '64', '1', '5', '1', '64', '4', '3', '64', '1', '16', '75', '15', '1', '15', '1', '10', '1', '64', '1', '15', '13', '58', '56', '1', '13', '62', '64', '58', '76', '75', '64', '62', '58', '65', '75', '64', '13', '75', '16', '65', '64', '13', '75', '13', '15', '64', '13', '75', '13', '64', '62', '13', '64', '75', '13', '55', '75', '62', '64', '62', '75', '16', '64', '75', '13', '75', '64', '73', '64', '34', '57', '55', '76', '34', '75', '34', '75', '57', '59', '57', '34', '57', '56', '75', '58', '75', '34', '74', '56', '57', '76', '34', '32', '62', '58', '76', '34', '76', '59', '34', '62', '75', '64', '73', '59', '58', '46', '62', '75', '46', '54', '58', '43', '48', '45', '58', '45', '46', '43', '65', '43', '14', '13', '62', '75', '60', '13', '75', '62', '46', '13', '58', '57', '16', '76', '77', '76', '77', '76', '52', '62', '53', '62', '53', '57', '76', '60', '53', '13', '64', '13', '58', '57', '13', '75', '13', '64', '13', '64', '13', '75', '62', '60', '13', '64', '13', '64', '58', '46', '32', '75', '13', '64', '16', '75', '13', '75', '16', '75', '16', '62', '75', '60', '75', '64', '13', '75', '62', '13', '64', '13', '64', '58', '64', '16', '43', '64', '75', '62', '13', '46', '13', '16', '64', '75', '64', '12', '64', '13', '64', '75', '16', '75', '64', '13', '16', '62', '67', '13', '64', '75', '64', '11', '64', '11', '64', '75', '64', '62', '64', '13', '64', '62', '13', '16', '64', '16', '64', '62', '13', '64', '13', '64', '75', '64', '62'] xrange = range def LongestCommonSubstring(S1, S2): '''print(S1,S2)''' M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] longest, x_longest = 0, 0 subgroups=[] subgroup=[] uniq={} for x in xrange(1,1+len(S1)): for y in xrange(1,1+len(S2)): if S1[x-1] == S2[y-1]: M[x][y] = M[x-1][y-1]+1 if M[x][y] > longest: longest = M[x][y] x_longest = x else: M[x][y] = 0 if longest >= 3: subgroup=S1[x_longest-longest:x_longest] print(subgroup) return S1[x_longest-longest:x_longest] if __name__=="__main__": for i in range(97,100): for j in range(97,100): if i != j: s1=chr(i)+"List" s2=chr(j)+"List" print(s1,s2) '''LongestCommonSubstring(s1,s2)''' From fal at libero.it Fri Nov 11 19:21:04 2011 From: fal at libero.it (Francesco Loffredo) Date: Fri, 11 Nov 2011 19:21:04 +0100 Subject: [Tutor] Find all strings that.... In-Reply-To: <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> <4EBC1D8A.6000701@libero.it> <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> Message-ID: <4EBD6790.7080306@libero.it> Alexander Etter wrote: > On Nov 10, 2011, at 13:52, Francesco Loffredo wrote: > >> Alexander Etter wrote: >>> Hi. My friend gave me a good wake up exercise ... >> I'd like to try this exercise too; would you mind defining "operations" more specifically, please? >> Given a sufficiently broad meaning of "operations" (e.g. operation = any function call) >> then any word can be converted into any given word with at most ONE operation. > Consider an operation not as a function. A function could easily contain more than two operations. An operation would remove two letters. An operation would add one letter. Etc. > Alexander Still, it seems to me too fuzzy a definition. Steven D'Aprano gave us a very thorough one in this thread, but you seem to allow many characters to be deleted in one operation... Anyway, taking for granted the rules contained in the edit distance definition (Thank you, Steven!), I think that finding in a given set S all words that can be converted into some given "target" with at most N such operations (better: the subset of all words in S with an edit distance from "target" <= N) is a very interesting and challenging task. Thank you (and your friend!) for this exercise, I'll give it a try. Francesco ----- Nessun virus nel messaggio. Controllato da AVG - www.avg.com Versione: 2012.0.1869 / Database dei virus: 2092/4608 - Data di rilascio: 10/11/2011 From malaclypse2 at gmail.com Fri Nov 11 19:38:57 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 11 Nov 2011 13:38:57 -0500 Subject: [Tutor] Find all strings that.... In-Reply-To: <4EBD6790.7080306@libero.it> References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> <4EBC1D8A.6000701@libero.it> <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> <4EBD6790.7080306@libero.it> Message-ID: On Fri, Nov 11, 2011 at 1:21 PM, Francesco Loffredo wrote: > Anyway, taking for granted the rules contained in the edit distance > definition (Thank you, Steven!), I think that finding in a given set S all > words that can be converted into some given "target" with at most N such > operations (better: the subset of all words in S with an edit distance > from "target" <= N) is a very interesting and challenging task. Thank you > (and your friend!) for this exercise, I'll give it a try. > There are some standard library tools that make this pretty easy. Take a look into difflib if you're interested. As always, there's nothing wrong with doing it yourself so that you understand it better, of course. -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Fri Nov 11 20:14:03 2011 From: rhettnaxel at gmail.com (Alexander) Date: Fri, 11 Nov 2011 14:14:03 -0500 Subject: [Tutor] Find all strings that.... In-Reply-To: References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> <4EBC1D8A.6000701@libero.it> <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> <4EBD6790.7080306@libero.it> Message-ID: On Fri, Nov 11, 2011 at 1:38 PM, Jerry Hill wrote: > On Fri, Nov 11, 2011 at 1:21 PM, Francesco Loffredo wrote: > >> Anyway, taking for granted the rules contained in the edit distance >> definition (Thank you, Steven!), I think that finding in a given set S all >> words that can be converted into some given "target" with at most N such >> operations (better: the subset of all words in S with an edit distance >> from "target" <= N) is a very interesting and challenging task. Thank you >> (and your friend!) for this exercise, I'll give it a try. >> > > There are some standard library tools that make this pretty easy. Take a > look into difflib if you're interested. As always, there's nothing wrong > with doing it yourself so that you understand it better, of course. > > -- > Jerry > > Hi Jerry. I'm checking out difflib. Thanks for the suggestion. Alexander Etter > _______________________________________________ > 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 fomcl at yahoo.com Fri Nov 11 20:20:49 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 11 Nov 2011 11:20:49 -0800 (PST) Subject: [Tutor] Find all strings that.... In-Reply-To: References: <6189639F-DD2E-4F8A-8E43-4E303380C2A4@gmail.com> <4EBC1D8A.6000701@libero.it> <52EB2134-BD4C-4432-B0B0-45C283B9AC97@gmail.com> <4EBD6790.7080306@libero.it> Message-ID: <1321039249.95775.YahooMailNeo@web110712.mail.gq1.yahoo.com> hi, this page contains interesting info about this topic. The algorithms that are discussed are all implemented in Python. http://cs.anu.edu.au/~Peter.Christen/Febrl/febrl-0.3/febrldoc-0.3/node38.html ? 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: Jerry Hill >To: "tutor at python.org" >Sent: Friday, November 11, 2011 7:38 PM >Subject: Re: [Tutor] Find all strings that.... > > >On Fri, Nov 11, 2011 at 1:21 PM, Francesco Loffredo wrote: > >Anyway, taking for granted the rules contained in the edit distance definition (Thank you, Steven!), I think that finding in a given set S all words that can be converted into some given "target" with at most N such operations (better: ?the subset of all words in S with an edit distance from "target" <= N) is a very interesting and challenging task. Thank you (and your friend!) for this exercise, I'll give it a try. >> >There are some standard library tools that make this pretty easy.? Take a look into difflib if you're interested.? As always, there's nothing wrong with doing it yourself so that you understand it better, of course. > >-- >Jerry > >_______________________________________________ >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 onyxtic at gmail.com Fri Nov 11 21:47:48 2011 From: onyxtic at gmail.com (Evans Anyokwu) Date: Fri, 11 Nov 2011 20:47:48 +0000 Subject: [Tutor] Suggest Book In-Reply-To: References: Message-ID: You really don't need a book. There are tons of free materials online including Alan's excellent tutorial. Spend some time working your way through some of these free tutorials, and once you're comfortable enough writing Python programs then buy one or two books as a reference material. Good luck, Evans -------------- next part -------------- An HTML attachment was scrubbed... URL: From bufsabres2007 at hotmail.com Fri Nov 11 22:40:31 2011 From: bufsabres2007 at hotmail.com (Nic Jaworski) Date: Fri, 11 Nov 2011 16:40:31 -0500 Subject: [Tutor] (no subject) Message-ID: python: v. 2.7.1Compiler: WING IDEOS: Windows 7 I am attempting to use a loop to output a 2D array for days and amount of pennies. I have it set to loop to do a penny times the day then to double the the penny and add a day. (the whole a penny doubles each day problem). However when I run my program I don't get anything, no output. #Nic 11/5/2011#Penny +=1 Each Day from math import *from numberTest import *from clearPause import *from locale import *#=============================================Main def main(): days=indays() salary = calc(days) #=========================== Days inputdef indays(): integer=0 while integer==0: salary = raw_input("how many days for your salary? ") integer,salary=testinteger(salary) if integer ==0: print 'the entry was not numeric - Please re-enter' pause() elif salary < 0: print 'please enter a number greater then 0' integer =0 else: integer=1 return salary #=================================Calculation def calc(days): n=0 d=1 while n>days: n+1 d**(n) d*2 x = array ([d,n]) print x main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Fri Nov 11 22:49:51 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 11 Nov 2011 22:49:51 +0100 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> Message-ID: <4EBD987F.60107@gmx.net> First, just a little rant :-) It doesn't help to randomly change some lines or introduce some new concepts you don't understand yet and then hope to get the right result. Your chances are very small that this will be succesful. You should try to understand some basic concepts first and build on them. From your postings the last weeks and especially from today I have the impression that you still don't understand how fundamental programming concepts work: for-loops, differences between data types (strings, lists, sets, ...) Honestly, have you already read any programming tutorial? (You'll find a big list at http://wiki.python.org/moin/BeginnersGuide/NonProgrammers )? At the moment it looks like you are just copying some code snippets from different places and then you hopelessly try to modify them to suit your needs. IMHO the problems you want to solve are a little too big for you right now. Nevertheless, here are some comments: > Based on former advice, I made a correction/modification on the below code. > > 1] the set and subgroup does not work, here I wish to put all the > subgroup in a big set, the set like That's a good idea, but you don't use the set correctly. > subgroups=[] > subgroup=[] > def LongestCommonSubstring(S1, S2): I think it's better to move "subgroups" and "subgroup" into the function. (I've noticed that in most of your scripts you are using a lot of global variables. IMHO that's not the best programming style. Do you know what "global/local variables", "namespace", "scope" mean?) You are defining "subgroups" as an empty list, but later you want to use it as a set. Thus, you should define it as an empty set: subgroups = set() You are also defining "subgroup" as an empty list, but later you assign a slice of "S1" to it. Since "S1" is a string, the slice is also a string. Therefore: subgroup = "" > M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] Peter told you already why "xrange" doesn't work in Python 3. But instead of using an alias like xrange = range IMHO it's better to change it in the code directly. > longest, x_longest = 0, 0 > for x in xrange(1,1+len(S1)): > for y in xrange(1,1+len(S2)): > if S1[x-1] == S2[y-1]: > M[x][y] = M[x-1][y-1]+1 > if M[x][y]> longest: > longest = M[x][y] > x_longest = x > if longest>= 3: > subgroup=S1[x_longest-longest:x_longest] > subgroups=set([subgroup]) Here you overwrite in the first iteration your original empty list "subgroups" with the set of the list which contains the string "subgroup" as its only element. Do you really understand this line? And in all the following iterations you are overwriting this one-element set with another one-element set (the next "subgroup"). If you want to add an element to an existing set instead of replacing it, you have to use the "add()"-method for adding an element to a set: subgroups.add(subgroup) This will add the string "subgroup" as a new element to the set "subgroups". > print(subgroups) > else: > M[x][y] = 0 > > return S1[x_longest-longest:x_longest] Here you probably want to return the set "subgroups": return subgroups > 2] I still have trouble in reading files, mainly about not read "" etc. The problem is that in your data files there is just this big one-line string. AFAIK you have produced these data files yourself, haven't you? In that case it would be better to change the way how you save the data (be it a well-formatted string or a list or something else) instead of trying to fix it here (in this script). Bye, Andreas From joel.goldstick at gmail.com Fri Nov 11 22:54:24 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 11 Nov 2011 16:54:24 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Fri, Nov 11, 2011 at 4:40 PM, Nic Jaworski wrote: > python: v. 2.7.1 > Compiler: WING IDE > OS: Windows 7 > > I am attempting to use a loop to output a 2D array for days and amount of > pennies. I have it set to loop to do a penny times the day then to double > the the penny and add a day. (the whole a penny doubles each day > problem). However when I run my program I don't get anything, no output. > > #Nic 11/5/2011 > #Penny +=1 Each Day > > from math import * > from numberTest import * > from clearPause import * > from locale import * > #=============================================Main > > > def main(): > days=indays() > salary = calc(days) > > #=========================== Days input > def indays(): > integer=0 > while integer==0: > salary = raw_input("how many days for your salary? ") > integer,salary=testinteger(salary) > if integer ==0: > print 'the entry was not numeric - Please re-enter' > pause() > elif salary < 0: > print 'please enter a number greater then 0' > integer =0 > else: > integer=1 > return salary > > #=================================Calculation > > def calc(days): > You are setting n = 0, then you loop only if n > days, and it never is. > n=0 > d=1 > while n>days: > n+1 > d**(n) > d*2 > x = array ([d,n]) > print x > > > main() > > > _______________________________________________ > 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 andreas.perstinger at gmx.net Fri Nov 11 23:17:15 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 11 Nov 2011 23:17:15 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4EBD9EEB.3010703@gmx.net> Please just post plain-text (no html) and use a meaningful subject! On 2011-11-11 22:40, Nic Jaworski wrote: > def calc(days): > n=0 > d=1 > while n>days: > n+1 > d**(n) > d*2 You are just calculating some expressions with "n" and "d" but you don't assign the results. Thus "n" and "d" will never change. > x = array ([d,n]) > print x In "main()" you have the line salary = calc(days) but you just return "None" (the default value for functions without a "return" statement) from "calc()". Is that what you want? > main() I don't know about windows but if you want to run the script from the command line you have to add: if __name__ == "__main__": main() See http://docs.python.org/py3k/tutorial/modules.html#executing-modules-as-scripts Bye, Andreas From alan.gauld at btinternet.com Sat Nov 12 01:47:48 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Nov 2011 00:47:48 +0000 Subject: [Tutor] Suggest Book In-Reply-To: References: Message-ID: On 11/11/11 14:29, Pankaj Jakhar wrote: > Please suggest me the best book for Python from which I can learn basics > to advanced Python. The "best" book will depend on you, some like informal chatty style with lots of examples other prefer a more formal approach. For me the O'Reilly books get it about right, although APress and Addison Wesley are usually safe bets too. It will also depend on your previous experience - do you already program in another language? Do you have any formal computer science or engineering or math background? These are all things that will affect your preference. Try browsing on Amazon and other web sites, use the previews where available... One other thing to consider os that "advanced" Python tends to be a case of a specialized subject area/library rather than advanced language usage., Python is pretty simple to use at any levels. You can write obscure python but its not often good Python and possibly not even advanced!.... So you might be better focusing on on-line tutorials to start with then choosing a specialized book to suit your interests - like networking, web, GUI, text processing, Games etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sat Nov 12 05:12:11 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 11 Nov 2011 23:12:11 -0500 Subject: [Tutor] My program gives no output (was (no subject) In-Reply-To: References: Message-ID: <4EBDF21B.405@gmail.com> Welcome to the Tutor list. Please provide a meaningful subbject as we track posts by subject On 11/11/2011 4:40 PM, Nic Jaworski wrote: > python: v. 2.7.1 > Compiler: WING IDE > OS: Windows 7 > > I am attempting to use a loop to output a 2D array for days and amount > of pennies. I have it set to loop to do a penny times the day then to > double the the penny and add a day. (the whole a penny doubles each > day problem). However when I run my program I don't get anything, no > output. IMHO you cannot get nothing. You should either get some error message or at least "how many days for your salary?" Exactly what do you do to run the program? > > #Nic 11/5/2011 > #Penny +=1 Each Day > > from math import * > from numberTest import * > from clearPause import * > from locale import * I highly recommend not using from... import * Instead import ... and qualify the imported items. I am not familiar with numberTest or clearPause. Where did you find them? > #=============================================Main > > > def main(): > days=indays() > salary = calc(days) > #=========================== Days input > def indays(): > integer=0 > while integer==0: > salary = raw_input("how many days for your salary? ") > integer,salary=testinteger(salary) > if integer ==0: > print 'the entry was not numeric - Please re-enter' > pause() > elif salary < 0: > print 'please enter a number greater then 0' > integer =0 > else: > integer=1 > return salary > > #=================================Calculation > > def calc(days): > n=0 > d=1 > while n>days: > n+1 > d**(n) > d*2 > x = array ([d,n]) > print x > main() > > > _______________________________________________ > 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 hothottrott at gmail.com Sat Nov 12 05:16:30 2011 From: hothottrott at gmail.com (Nathaniel Trujillo) Date: Fri, 11 Nov 2011 21:16:30 -0700 Subject: [Tutor] Hello again. Still the same problem, different question. Message-ID: I realize that one of you told me that there is no livewires for python v3.1.1 but the book that I am reading teaches v3.1.1 and the code that is presented in the book has a line that imports a module from the livewires package. Now since the book covers v3.1.1, I would have to conclude that the code containing the line "from livewires import games" should work in version 3.1.1. They gave me a website to go and download a version of livewires that would work (www.courseptr.com/downloads) and I went there but I could not find that download anywhere. I think the website might have changed since the book was written. If anybody knows where I can get the version of livewires I need I would be truly greatful. My book is entitled Python Programming for the Absolute Beginner Third Edition. Anyway, here is the code that my book insists should work. # New Graphics Window # Demonstrates creating a graphics window from livewires import games games.init(screen_width = 640, screen_height = 480, fps = 50) games.screen.mainloop() and here is the error message I keep getting Traceback (most recent call last): File "C:\Python27\new_graphics_window.py", line 6, in games.init(screen_width = 640, screen_height = 480, fps = 50) AttributeError: 'module' object has no attribute 'init' Someone there told me they would've given up by now but I am not giving up on this one or anything else. Just to give you a heads up, you will be getting questions about this until this program works. Thanks for your help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Sat Nov 12 07:00:28 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sat, 12 Nov 2011 06:00:28 +0000 Subject: [Tutor] Hello again. Still the same problem, different question. In-Reply-To: References: Message-ID: <1435637924-1321077629-cardhu_decombobulator_blackberry.rim.net-939847038-@b18.c12.bise7.blackberry> Can you kindly mail the author? That might be a better way to have this resolved. Its interesting you are sticking with python v3. Cheers. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Nathaniel Trujillo Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Fri, 11 Nov 2011 21:16:30 To: Subject: [Tutor] Hello again. Still the same problem, different question. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sat Nov 12 07:26:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 12 Nov 2011 17:26:48 +1100 Subject: [Tutor] Hello again. Still the same problem, different question. In-Reply-To: References: Message-ID: <4EBE11A8.4050309@pearwood.info> Nathaniel Trujillo wrote: > I realize that one of you told me that there is no livewires for python > v3.1.1 but the book that I am reading teaches v3.1.1 and the code that is > presented in the book has a line that imports a module from the livewires > package. Now since the book covers v3.1.1, I would have to conclude that > the code containing the line "from livewires import games" should work in > version 3.1.1. They gave me a website to go and download a version of > livewires that would work (www.courseptr.com/downloads) and I went there > but I could not find that download anywhere. I think the website might have > changed since the book was written. If anybody knows where I can get the > version of livewires I need I would be truly greatful. My book is entitled > Python Programming for the Absolute Beginner Third Edition. Anyway, here is > the code that my book insists should work. According to one of the reviews on Amazon, that's because the author of the book has written his own customized version of Livewires which you have to use. http://www.amazon.ca/Python-Programming-Absolute-Beginner-Second/dp/1598631128 The book quite clearly says so too: TRAP Although you're welcome to visit the web site of the LiveWires organization at http://www.livewires.org.uk , be aware that the livewires package used in this book is a modified version of the package that LiveWires created. > Someone there told me they would've given up by now but I am not giving up > on this one or anything else. Just to give you a heads up, you will be > getting questions about this until this program works. Thanks for your help. While I admire your persistence, we are all volunteers and may not appreciate being asked the same questions over and over and over again to no value. I'm just saying that at some point, you may have to expect that we'll stop answering questions if we think we're just wasting our time. If the author's custom version is not available, and the standard version doesn't work, then we're probably wasting our time. -- Steven From andreas.perstinger at gmx.net Sat Nov 12 07:30:13 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 12 Nov 2011 07:30:13 +0100 Subject: [Tutor] Hello again. Still the same problem, different question. In-Reply-To: References: Message-ID: <4EBE1275.40906@gmx.net> On 2011-11-12 05:16, Nathaniel Trujillo wrote: > They gave me a website to go and download a version of > livewires that would work (www.courseptr.com/downloads) and I went there > but I could not find that download anywhere. http://www.delmarlearning.com/companions/content/1435455002/downloads/index.asp?isbn=1435455002 If you click on "Book related software" you'll get a zip-file which includes "livewires". Bye, Andreas From lina.lastname at gmail.com Sat Nov 12 09:54:46 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 16:54:46 +0800 Subject: [Tutor] longest common substring In-Reply-To: <4EBD987F.60107@gmx.net> References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> Message-ID: On Sat, Nov 12, 2011 at 5:49 AM, Andreas Perstinger wrote: > First, just a little rant :-) > It doesn't help to randomly change some lines or introduce some new concepts > you don't understand yet and then hope to get the right result. Your chances > are very small that this will be succesful. > You should try to understand some basic concepts first and build on them. > From your postings the last weeks and especially from today I have the > impression that you still don't understand how fundamental programming > concepts work: for-loops, differences between data types (strings, lists, > sets, ...) > Honestly, have you already read any programming tutorial? (You'll find a big > list at http://wiki.python.org/moin/BeginnersGuide/NonProgrammers )? At the > moment it looks like you are just copying some code snippets from different > places and then you hopelessly try to modify them to suit your needs. IMHO > the problems you want to solve are a little too big for you right now. > > Nevertheless, here are some comments: Thanks, Those are very valuable comments. Since I read your post till the following hours, my mind was haunted by what you pointed out. The reflection went far away. I had/have a VERY BAD HABIT in learning and doing things. My father used to say I was the person did not know how to walk, but started to run. Later I realized in my life, such as I barely read a manual/usage/map, but started messing things up. (I did destory something I newly bought without spending 2 mins reading the usage, I could not forget because it's expensive, haha ...). In the past, for difficulty questions I could do pretty not bad, but for basic concepts or step by step detailed things I failed more than once. But also very honestly answering, that I did try to read some books, one is dive into python, another is learning python the hard way. and now I have programming python by Mark Lutz, and another python book on bedside. The mainly problems was that I felt nothing when I just read for reading. forget so easily what I read. ( Now I am a little worried, the bad habit I have had will affect me go far away or build something serious. Sigh ... ) In the past hours, I tried to read the basic concepts, but get lost (not lost, just mind becomes empty and inactive) in minutes. Thanks again for your pointing out. I will remind myself in future. > >> Based on former advice, I made a correction/modification on the belowba >> code. >> >> 1] the set and subgroup does not work, here I wish to put all the >> subgroup in a big set, the set like > > That's a good idea, but you don't use the set correctly. > >> subgroups=[] >> subgroup=[] >> def LongestCommonSubstring(S1, S2): > > I think it's better to move "subgroups" and "subgroup" into the function. > (I've noticed that in most of your scripts you are using a lot of global > variables. IMHO that's not the best programming style. Do you know what > "global/local variables", "namespace", "scope" mean?) > > You are defining "subgroups" as an empty list, but later you want to use it > as a set. Thus, you should define it as an empty set: > > subgroups = set() > > You are also defining "subgroup" as an empty list, but later you assign a > slice of "S1" to it. Since "S1" is a string, the slice is also a string. > Therefore: > > subgroup = "" > >> ? ? ?M = [[0]*(1+len(S2)) for i in xrange(1+len(S1))] > > Peter told you already why "xrange" doesn't work in Python 3. But instead of > using an alias like > > xrange = range > > IMHO it's better to change it in the code directly. > >> ? ? ?longest, x_longest = 0, 0 >> ? ? ?for x in xrange(1,1+len(S1)): >> ? ? ? ? ?for y in xrange(1,1+len(S2)): >> ? ? ? ? ? ? ?if S1[x-1] == S2[y-1]: >> ? ? ? ? ? ? ? ? ?M[x][y] = M[x-1][y-1]+1 >> ? ? ? ? ? ? ? ? ?if M[x][y]> ?longest: >> ? ? ? ? ? ? ? ? ? ? ?longest = M[x][y] >> ? ? ? ? ? ? ? ? ? ? ?x_longest = x >> ? ? ? ? ? ? ? ? ?if longest>= 3: >> ? ? ? ? ? ? ? ? ? ? ?subgroup=S1[x_longest-longest:x_longest] >> ? ? ? ? ? ? ? ? ? ? ?subgroups=set([subgroup]) > > Here you overwrite in the first iteration your original empty list > "subgroups" with the set of the list which contains the string "subgroup" as > its only element. Do you really understand this line? > And in all the following iterations you are overwriting this one-element set > with another one-element set (the next "subgroup"). > If you want to add an element to an existing set instead of replacing it, > you have to use the "add()"-method for adding an element to a set: > > subgroups.add(subgroup) > > This will add the string "subgroup" as a new element to the set "subgroups". > >> ? ? ? ? ? ? ? ? ? ? ?print(subgroups) >> ? ? ? ? ? ? ?else: >> ? ? ? ? ? ? ? ? ? ? ?M[x][y] = 0 >> >> ? ? ?return S1[x_longest-longest:x_longest] > > Here you probably want to return the set "subgroups": > > return subgroups I will return to this parts later. Based on your advice, I updated the code to below one (which is partially work); #!/usr/bin/python3 import os.path from collections import Counter INFILEEXT=".doc" def CommonSublist(L1, L2): sublist=[] sublists=[] result=[] M = [[0]*(1+len(L2)) for i in range(1+len(L1))] longest, x_longest = 0, 0 for x in range(1,1+len(L1)): for y in range(1,1+len(L2)): if L1[x-1] == L2[y-1]: M[x][y] = M[x-1][y-1]+1 if M[x][y] > longest: longest = M[x][y] x_longest = x if longest >= 2: sublist=L1[x_longest-longest:x_longest] if sublist not in sublists: sublists.append(sublist) else: M[x][y] = 0 return sublists if __name__=="__main__": for i in range(1,11): for j in range(1,11): if i != j: fileone="atom-pair_"+str(i)+".txt" filetwo="atom-pair_"+str(j)+".txt" a=open(fileone,"r").readline().strip().split(' ') b=open(filetwo,"r").readline().strip().split(' ') print(fileone,filetwo) print(CommonSublist(a,b)) The output results: atom-pair_10.txt atom-pair_8.txt [["'75',", "'64',"], ["'13',", "'64',", "'75',"], ["'64',", "'62',", "'75',", "'16',"]] atom-pair_10.txt atom-pair_9.txt [["'65',", "'46',"], ["'13',", "'75',", "'64',"]] Please feel free to give me the comments. Right now I am chocked in how to achieve build a final result, contains all the sublist (with duplication) in different files combinations, and later get those sublists concurrence. Frankly speaking, today I tried to figure out the name space and scope. The one I tried : if longest >= 2: sublist=L1[x_longest-longest:x_longest] result=result.append(sublist) if sublist not in sublists: sublists.append(sublist) the $ python3 CommonSublists.py atom-pair_1.txt atom-pair_2.txt Traceback (most recent call last): File "CommonSublists.py", line 47, in print(CommonSublist(a,b)) File "CommonSublists.py", line 24, in CommonSublist result=result.append(sublist) AttributeError: 'NoneType' object has no attribute 'append' in local domain I set the result=[] I don't know why it complains its NoneType, since the "result" is nearly the same as "sublists". > > >> 2] I still have trouble in reading files, mainly about not read "" etc. > > The problem is that in your data files there is just this big one-line > string. AFAIK you have produced these data files yourself, haven't you? In Yes. Those files were generated by myself. I have redone those things. > that case it would be better to change the way how you save the data (be it > a well-formatted string or a list or something else) instead of trying to > fix it here (in this script). > > Bye, Andreas Really thanks, P.S I attached the whole directory in below link: tar.gz one https://docs.google.com/open?id=0B93SVRfpVVg3Y2Q2OWI1N2EtY2VmMi00MTQxLTgyYTctYmM0NDFkNGY1YzIz zip one: https://docs.google.com/open?id=0B93SVRfpVVg3ODM3NjQ2ZmEtMzgyMy00ODIxLWIxMTUtMDhmYmU0MGQzOWZj > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lina.lastname at gmail.com Sat Nov 12 10:01:16 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 17:01:16 +0800 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> Message-ID: Sorry I finished last email in two different time, while: > INFILEEXT=".doc" > > > def CommonSublist(L1, L2): > ? ?sublist=[] > ? ?sublists=[] > ? ?result=[] > ? ?M = [[0]*(1+len(L2)) for i in range(1+len(L1))] > ? ?longest, x_longest = 0, 0 > ? ?for x in range(1,1+len(L1)): > ? ? ? ?for y in range(1,1+len(L2)): > ? ? ? ? ? ?if L1[x-1] == L2[y-1]: > ? ? ? ? ? ? ? ?M[x][y] = M[x-1][y-1]+1 > ? ? ? ? ? ? ? ?if M[x][y] > longest: > ? ? ? ? ? ? ? ? ? ?longest = M[x][y] > ? ? ? ? ? ? ? ? ? ?x_longest = x > ? ? ? ? ? ? ? ?if longest >= 2: > ? ? ? ? ? ? ? ? ? ?sublist=L1[x_longest-longest:x_longest] > ? ? ? ? ? ? ? ? ? ?if sublist not in sublists: > ? ? ? ? ? ? ? ? ? ? ? ? sublists.append(sublist) > > > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ?M[x][y] = 0 > > ? ?return sublists > > > > if __name__=="__main__": > > > ? ?for i in range(1,11): > ? ? ? ?for j in range(1,11): > ? ? ? ? ? ?if i != j: > ? ? ? ? ? ? ? ?fileone="atom-pair_"+str(i)+".txt" > ? ? ? ? ? ? ? ?filetwo="atom-pair_"+str(j)+".txt" correction: here not ".txt", it's ".doc" > ? ? ? ? ? ? ? ?a=open(fileone,"r").readline().strip().split(' ') > ? ? ? ? ? ? ? ?b=open(filetwo,"r").readline().strip().split(' ') > ? ? ? ? ? ? ? ?print(fileone,filetwo) > ? ? ? ? ? ? ? ?print(CommonSublist(a,b)) > > The output results: > the output is: atom-pair_10.doc atom-pair_8.doc [['75', '64'], ['13', '64', '75'], ['64', '62', '75', '16']] atom-pair_10.doc atom-pair_9.doc [['65', '46'], ['13', '75', '64']] seems a bit better than before. > atom-pair_10.txt atom-pair_8.txt > [["'75',", "'64',"], ["'13',", "'64',", "'75',"], ["'64',", "'62',", > "'75',", "'16',"]] > atom-pair_10.txt atom-pair_9.txt > [["'65',", "'46',"], ["'13',", "'75',", "'64',"]] > > the $ python3 CommonSublists.py > atom-pair_1.txt atom-pair_2.txt > Traceback (most recent call last): > ?File "CommonSublists.py", line 47, in > ? ?print(CommonSublist(a,b)) > ?File "CommonSublists.py", line 24, in CommonSublist > ? ?result=result.append(sublist) > AttributeError: 'NoneType' object has no attribute 'append' > > in local domain I set the result=[] > I don't know why it complains its NoneType, since the "result" is > nearly the same as "sublists". > Thanks with best regards, From alan.gauld at btinternet.com Sat Nov 12 10:33:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Nov 2011 09:33:58 +0000 Subject: [Tutor] (no subject) In-Reply-To: <4EBD9EEB.3010703@gmx.net> References: <4EBD9EEB.3010703@gmx.net> Message-ID: On 11/11/11 22:17, Andreas Perstinger wrote: > I don't know about windows but if you want to run the script from the > command line you have to add: > > if __name__ == "__main__": > main() No, you only need to do that if you plan on using the file as a module at some point. If you don't need a module then the OPs style will work just fine on any OS. But since having module facilities is so easy it is good practice to always use the if main clause... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From robert.sjoblom at gmail.com Sat Nov 12 10:41:45 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sat, 12 Nov 2011 10:41:45 +0100 Subject: [Tutor] Hello again. Still the same problem, different question. Message-ID: On 12 November 2011 07:27, wrote: > 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 Please have a useful subject line next time, the current subject doesn't tell us anything about your problem. > Someone there told me they would've given up by now but I am not giving up > on this one or anything else. Just to give you a heads up, you will be > getting questions about this until this program works. You can't force me to answer questions! Additionally; I, for one, will put you on ignore if you spam this list with questions that are about the same subject and are unsolvable because the standard version doesn't work. So just to give you a heads up: don't overextend your welcome. -- best regards, Robert S. From cmacleod170 at gmail.com Sat Nov 12 13:07:33 2011 From: cmacleod170 at gmail.com (Cameron Macleod) Date: Sat, 12 Nov 2011 12:07:33 +0000 Subject: [Tutor] Time subtractrion Message-ID: Hi, I've been trying to code a timer that tells you how long you've been on the net and I can't figure out how to produce a figure in hours, minutes and seconds that is constantly being updated. If anyone could point out a module with functions like this or built in functions, I'd be very grateful. Cameron -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Sat Nov 12 13:19:28 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 12 Nov 2011 13:19:28 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: <4EBD9EEB.3010703@gmx.net> Message-ID: <4EBE6450.7090103@gmx.net> On 2011-11-12 10:33, Alan Gauld wrote: > On 11/11/11 22:17, Andreas Perstinger wrote: > >> I don't know about windows but if you want to run the script from the >> command line you have to add: >> >> if __name__ == "__main__": >> main() > > No, you only need to do that if you plan on using the file as a module > at some point. If you don't need a module then the OPs style will work > just fine on any OS. Of course you're right. Sorry for the misinformation. It was probably too late in the evening when I wrote this yesterday :-(. Bye, Andreas From d at davea.name Sat Nov 12 14:22:16 2011 From: d at davea.name (Dave Angel) Date: Sat, 12 Nov 2011 08:22:16 -0500 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> Message-ID: <4EBE7308.7010408@davea.name> On 11/12/2011 03:54 AM, lina wrote: > > The one I tried : > if longest>= 2: > sublist=L1[x_longest-longest:x_longest] > result=result.append(sublist) > if sublist not in sublists: > sublists.append(sublist) > > the $ python3 CommonSublists.py > atom-pair_1.txt atom-pair_2.txt > Traceback (most recent call last): > File "CommonSublists.py", line 47, in > print(CommonSublist(a,b)) > File "CommonSublists.py", line 24, in CommonSublist > result=result.append(sublist) > AttributeError: 'NoneType' object has no attribute 'append' > > in local domain I set the result=[] > I don't know why it complains its NoneType, since the "result" is > nearly the same as "sublists". > Assuming this snippet is part of a loop, I see the problem: result = result.append(sublist) list.append() returns none. It modifies the list object in place, but it doesn't return anything. So that statement modifies the result object, appending the sublist to it, then it sets it to None. The second time around you see that error. In general, most methods in the standard library either modify the object they're working on, OR they return something. The append method is in the first category. -- DaveA From waynejwerner at gmail.com Sat Nov 12 14:39:37 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 12 Nov 2011 07:39:37 -0600 Subject: [Tutor] Time subtractrion In-Reply-To: References: Message-ID: On Sat, Nov 12, 2011 at 6:07 AM, Cameron Macleod wrote: > Hi, > > I've been trying to code a timer that tells you how long you've been on > the net and I can't figure out how to produce a figure in hours, minutes > and seconds that is constantly being updated. If anyone could point out a > module with functions like this or built in functions, I'd be very grateful. Have you looked at the time module? http://docs.python.org/library/time.html -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Sat Nov 12 15:48:16 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 22:48:16 +0800 Subject: [Tutor] longest common substring In-Reply-To: <4EBE7308.7010408@davea.name> References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> <4EBE7308.7010408@davea.name> Message-ID: On Sat, Nov 12, 2011 at 9:22 PM, Dave Angel wrote: > On 11/12/2011 03:54 AM, lina wrote: >> >> >> The one I tried : >> ? ? ? ? ? ? ? ? if longest>= 2: >> ? ? ? ? ? ? ? ? ? ? sublist=L1[x_longest-longest:x_longest] >> ? ? ? ? ? ? ? ? ? ? result=result.append(sublist) >> ? ? ? ? ? ? ? ? ? ? if sublist not in sublists: >> ? ? ? ? ? ? ? ? ? ? ? ? ?sublists.append(sublist) >> >> the $ python3 CommonSublists.py >> atom-pair_1.txt atom-pair_2.txt >> Traceback (most recent call last): >> ? File "CommonSublists.py", line 47, in >> ? ? print(CommonSublist(a,b)) >> ? File "CommonSublists.py", line 24, in CommonSublist >> ? ? result=result.append(sublist) >> AttributeError: 'NoneType' object has no attribute 'append' >> >> in local domain I set the result=[] >> I don't know why it complains its NoneType, since the "result" is >> nearly the same as "sublists". >> > Assuming this snippet is part of a loop, I see the problem: > > result ?= result.append(sublist) > > list.append() returns none. ?It modifies the list object in place, but it > doesn't return anything. ?So that statement modifies the result object, > appending the sublist to it, then it sets it to None. ?The second time > around you see that error. I am sorry. haha ... still lack of understanding above sentence. >>> a ['3', '5', '7', '8', '9'] >>> d.append(a) >>> d [['3', '5', '7', '8', '9']] >>> type(a) Sorry and thanks, best regards, lina > > In general, most methods in the standard library either modify the object > they're working on, OR they return something. ? The append method is in the > first category. > > > -- > > DaveA > > From d at davea.name Sat Nov 12 15:57:10 2011 From: d at davea.name (Dave Angel) Date: Sat, 12 Nov 2011 09:57:10 -0500 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> <4EBE7308.7010408@davea.name> Message-ID: <4EBE8946.5050905@davea.name> On 11/12/2011 09:48 AM, lina wrote: > On Sat, Nov 12, 2011 at 9:22 PM, Dave Angel wrote: >> On 11/12/2011 03:54 AM, lina wrote: >>> >>> >>> The one I tried : >>> if longest>= 2: >>> sublist=L1[x_longest-longest:x_longest] >>> result=result.append(sublist) >>> if sublist not in sublists: >>> sublists.append(sublist) >>> >>> the $ python3 CommonSublists.py >>> atom-pair_1.txt atom-pair_2.txt >>> Traceback (most recent call last): >>> File "CommonSublists.py", line 47, in >>> print(CommonSublist(a,b)) >>> File "CommonSublists.py", line 24, in CommonSublist >>> result=result.append(sublist) >>> AttributeError: 'NoneType' object has no attribute 'append' >>> >>> in local domain I set the result=[] >>> I don't know why it complains its NoneType, since the "result" is >>> nearly the same as "sublists". >>> >> Assuming this snippet is part of a loop, I see the problem: >> >> result = result.append(sublist) >> >> list.append() returns none. It modifies the list object in place, but it >> doesn't return anything. So that statement modifies the result object, >> appending the sublist to it, then it sets it to None. The second time >> around you see that error. > > I am sorry. haha ... still lack of understanding above sentence. > >>>> a > ['3', '5', '7', '8', '9'] >>>> d.append(a) >>>> d > [['3', '5', '7', '8', '9']] >>>> type(a) > > > Sorry and thanks, best regards, > > lina > >> >> In general, most methods in the standard library either modify the object >> they're working on, OR they return something. The append method is in the >> first category. >> >> To keep it simple, I'm using three separate variables. d and a are as you tried to show above. Now what happens when I append? Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d = [] >>> a = [3, 5, 7] >>> xxx = d.append(a) >>> print(repr(xxx)) None >>> print d [[3, 5, 7]] Notice that d does change as we expected. But xxx, the return value, is None. The append() method doesn't return any useful value, so don't assign it to anything. The statement in your code that's wrong is result = result.append(sublist) The final value that goes into result is None, no matter what the earlier values of result and sublist were. -- DaveA From lina.lastname at gmail.com Sat Nov 12 16:24:20 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 12 Nov 2011 23:24:20 +0800 Subject: [Tutor] longest common substring In-Reply-To: <4EBE8946.5050905@davea.name> References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> <4EBE7308.7010408@davea.name> <4EBE8946.5050905@davea.name> Message-ID: On Sat, Nov 12, 2011 at 10:57 PM, Dave Angel wrote: > On 11/12/2011 09:48 AM, lina wrote: >> >> On Sat, Nov 12, 2011 at 9:22 PM, Dave Angel ?wrote: >>> >>> On 11/12/2011 03:54 AM, lina wrote: >>>> >>>> >>>> The one I tried : >>>> ? ? ? ? ? ? ? ? if longest>= 2: >>>> ? ? ? ? ? ? ? ? ? ? sublist=L1[x_longest-longest:x_longest] >>>> ? ? ? ? ? ? ? ? ? ? result=result.append(sublist) >>>> ? ? ? ? ? ? ? ? ? ? if sublist not in sublists: >>>> ? ? ? ? ? ? ? ? ? ? ? ? ?sublists.append(sublist) >>>> >>>> the $ python3 CommonSublists.py >>>> atom-pair_1.txt atom-pair_2.txt >>>> Traceback (most recent call last): >>>> ? File "CommonSublists.py", line 47, in >>>> ? ? print(CommonSublist(a,b)) >>>> ? File "CommonSublists.py", line 24, in CommonSublist >>>> ? ? result=result.append(sublist) >>>> AttributeError: 'NoneType' object has no attribute 'append' >>>> >>>> in local domain I set the result=[] >>>> I don't know why it complains its NoneType, since the "result" is >>>> nearly the same as "sublists". >>>> >>> Assuming this snippet is part of a loop, I see the problem: >>> >>> result ?= result.append(sublist) >>> >>> list.append() returns none. ?It modifies the list object in place, but it >>> doesn't return anything. ?So that statement modifies the result object, >>> appending the sublist to it, then it sets it to None. ?The second time >>> around you see that error. >> >> I am sorry. ?haha ... still lack of understanding above sentence. >> >>>>> a >> >> ['3', '5', '7', '8', '9'] >>>>> >>>>> d.append(a) >>>>> d >> >> [['3', '5', '7', '8', '9']] >>>>> >>>>> type(a) >> >> >> >> Sorry and thanks, best regards, >> >> lina >> >>> >>> In general, most methods in the standard library either modify the object >>> they're working on, OR they return something. ? The append method is in >>> the >>> first category. >>> >>> > > To keep it simple, I'm using three separate variables. ?d and a are as you > tried to show above. ?Now what happens when I append? > > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> d = [] >>>> a = [3, 5, 7] >>>> xxx = d.append(a) >>>> print(repr(xxx)) > None >>>> print d > [[3, 5, 7]] > > Notice that d does change as we expected. ?But xxx, the return value, is > None. The append() method doesn't return any useful value, so don't assign > it to anything. Thanks, ^_^, now better. I checked, the sublist (list) here can't be as a key of the results (dict). actually I also wish to get the occurence of those sublist in the script, except using external one in command line as uniq -c. ^_^ Have a nice weekend, > > The statement in your code that's wrong is > ? ?result = result.append(sublist) > > The final value that goes into result is None, no matter what the earlier > values of result and sublist were. > > -- > > DaveA > From andreas.perstinger at gmx.net Sat Nov 12 17:40:38 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 12 Nov 2011 17:40:38 +0100 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> <4EBE7308.7010408@davea.name> <4EBE8946.5050905@davea.name> Message-ID: <4EBEA186.2030400@gmx.net> On 2011-11-12 16:24, lina wrote: > Thanks, ^_^, now better. No, I'm afraid you are still not understanding. > I checked, the sublist (list) here can't be as a key of the results (dict). "result" isn't a dictionary. It started as an empty list and later becomes a null object ("NoneType"). You must not forget that you are inside a for-loop. Simplified your situation is like this: >>> result = [] >>> for i in range(1,10): ... print("Iteration {0}, result = {1}".format(i, result)) ... result = result.append(i) ... Iteration 1, result = [] Iteration 2, result = None Traceback (most recent call last): File "", line 3, in AttributeError: 'NoneType' object has no attribute 'append' As you see the error happens in the *second* iteration, because result is no list any more. Dave gave you already the explanation: functions and method always return a value in Python. If the don't have a return statement they return "None". Another simple example: >>> a = print("Test") Test "print" is a function which prints out the text you passed to it and you usually aren't interested in its return value. But every function/method in Python returns something. You save this value in "a" >>> print(a) None As you see the return value of "print" is "None". >>> a.append(x) Traceback (most recent call last): File "", line 1, in AttributeError: 'NoneType' object has no attribute 'append' Same error as above, because "NoneType" objects (null objects) don't have a method "append". I also think you mix two different ways to add an element to a list: result.append(x) is equivalent to result = result + [x] (that's what you will use in other languages) HTH, Andreas From bikashkits at gmail.com Sat Nov 12 18:54:19 2011 From: bikashkits at gmail.com (Bikash Sahoo) Date: Sat, 12 Nov 2011 23:24:19 +0530 Subject: [Tutor] [off-topic] Any thread for linux troubleshooting Message-ID: Hi All : Sorry guys , i know this is not the right thread. Just wanted to bump off a question . I am new to python and have just installed linux(new to linux as well :) ) on my system. It has both the Windows 7 and Ubuntu 11.0 now. Can you please refer some threads for linux troubleshooting queries ?? Thanks in advance Bikash P.S :- Posting the query , just in case. I am getting the following as the initial command line in the terminal when i open it after installation . Can i change it ? is there any error in the installation ? "dinesh at dinesh-Invalid-entry-length-0-DMI-table-is-broken-Stop:~$ " i want to make it just dinesh . -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sat Nov 12 19:27:14 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 12 Nov 2011 13:27:14 -0500 Subject: [Tutor] longest common substring In-Reply-To: <4EBEA186.2030400@gmx.net> References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> <4EBE7308.7010408@davea.name> <4EBE8946.5050905@davea.name> <4EBEA186.2030400@gmx.net> Message-ID: On Sat, Nov 12, 2011 at 11:40 AM, Andreas Perstinger < andreas.perstinger at gmx.net> wrote: > On 2011-11-12 16:24, lina wrote: > >> Thanks, ^_^, now better. >> > > No, I'm afraid you are still not understanding. > > > I checked, the sublist (list) here can't be as a key of the results >> (dict). >> > > "result" isn't a dictionary. It started as an empty list and later becomes > a null object ("NoneType"). > > You must not forget that you are inside a for-loop. Simplified your > situation is like this: > > >>> result = [] > >>> for i in range(1,10): > ... print("Iteration {0}, result = {1}".format(i, result)) > ... result = result.append(i) > ... > Iteration 1, result = [] > Iteration 2, result = None > > Traceback (most recent call last): > File "", line 3, in > > AttributeError: 'NoneType' object has no attribute 'append' > > As you see the error happens in the *second* iteration, because result is > no list any more. > Dave gave you already the explanation: functions and method always return > a value in Python. If the don't have a return statement they return "None". > > Another simple example: > > >>> a = print("Test") > Test > > "print" is a function which prints out the text you passed to it and you > usually aren't interested in its return value. But every function/method in > Python returns something. You save this value in "a" > > >>> print(a) > None > > As you see the return value of "print" is "None". > > >>> a.append(x) > > Traceback (most recent call last): > File "", line 1, in > > AttributeError: 'NoneType' object has no attribute 'append' > > Same error as above, because "NoneType" objects (null objects) don't have > a method "append". > > I also think you mix two different ways to add an element to a list: > > result.append(x) > > is equivalent to > > result = result + [x] (that's what you will use in other languages) > > HTH, Andreas > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > This is a fascinating thread in the same way that people can't help slowing down and looking at a car crash on the side of the road is fascinating. The original poster it seems is new to programming and has offered that he likes to run before he learns to walk. That doesn't seem like a good proclamation to make when you are asking people to help you. Anyway, this particular piece of code is pretty tricky stuff. It involves understanding list comprehensions, multidimensional lists, and slices. All things that take more than a passing interest in to grasp. Furthermore, the algorithm itself is pretty tricky. If you follow the link to the wikipedia article: http://en.wikipedia.org/wiki/Longest_common_substring you learn that understanding the algorithm requires understanding of trees (Generalized suffix trees at that!). I copied the code from the original article and played around with it for an hour or so to understand it. I didn't get the answers that I expected either. If you are learning coding in general and python in particular this exercise seems unproductive. Work through basic concepts. If you don't like one set of tutorials, find a different one. if you don't like to read, check out google videos for learning python, or youtube for that matter. But taking on a concise algorithm that solves a problem that would challenge a 3rd year CS student doesn't seem like a good idea -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From 0101amt at gmail.com Sat Nov 12 22:24:38 2011 From: 0101amt at gmail.com (amt) Date: Sat, 12 Nov 2011 23:24:38 +0200 Subject: [Tutor] Suggest Book In-Reply-To: References: Message-ID: Hi Pankaj! Have a look at : http://wiki.python.org/moin/BeginnersGuide http://norvig.com/21-days.html I'm currently learning from this book: http://learnpythonthehardway.org/book/ Have a look. It's a good book for starting out. Just pick one that you like and start learning. I wish you good luck! Regards, amt. On Fri, Nov 11, 2011 at 4:29 PM, Pankaj Jakhar wrote: > Hello > > Please suggest me the best book for Python from which I can learn basics > to advanced Python. > > Thank you. > *____________ > PankaJ **Jakhar** > * > > _______________________________________________ > 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 Sun Nov 13 00:07:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 12 Nov 2011 23:07:46 +0000 Subject: [Tutor] [off-topic] Any thread for linux troubleshooting In-Reply-To: References: Message-ID: On 12/11/11 17:54, Bikash Sahoo wrote: > Can you please refer some threads for linux troubleshooting queries ?? Not so much a thread but the Ubuntu web forum is a good starting place and there are tons of Linux news groups. Try a search on Google groups as your starting point. Also the Linux Documentation Project www.ldp.org has loads of how-to docs. I've been using Linux on and off since 1993 but only made the total switch to it this July. So far I'm loving it except for the lack of a decent Video editor and Visio clone. Fortunately Serif Movieplus and SmartDraw 6 work under Wine so I'm a happy bunny :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From beachkidken at gmail.com Sun Nov 13 04:29:28 2011 From: beachkidken at gmail.com (Ken G.) Date: Sat, 12 Nov 2011 22:29:28 -0500 Subject: [Tutor] [off-topic] Any thread for linux troubleshooting Message-ID: <4EBF3998.7010105@gmail.com> > On 12/11/11 17:54, Bikash Sahoo wrote: > >> Can you please refer some threads for linux troubleshooting queries ?? > > Not so much a thread but the Ubuntu web forum is a good starting place and thereare tons of Linux news groups. Try a search on Google groups as your starting point. > > Also the Linux Documentation Project www.ldp.org has loads of how-to docs. > > I've been using Linux on and off since 1993 but only made the total switch to it this July. So far I'm loving it except for the lack of a decent Video editor and Visio clone. Fortunately Serif Movieplus and SmartDraw 6 work under Wine so I'm a happy bunny > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ I checked the above website and I was linked to a foreign political blog. The correct link is: tldp.org/ for The Linux Documentation Project. Ken From alan.gauld at btinternet.com Sun Nov 13 10:24:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 13 Nov 2011 09:24:38 +0000 Subject: [Tutor] [off-topic] Any thread for linux troubleshooting In-Reply-To: <4EBF3998.7010105@gmail.com> References: <4EBF3998.7010105@gmail.com> Message-ID: On 13/11/11 03:29, Ken G. wrote: > I checked the above website and I was linked to a foreign political > blog. The correct link is: tldp.org/ for The Linux Documentation Project. Oops, sorry about that. Amazing the difference a single letter makes! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Sun Nov 13 14:06:01 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 13 Nov 2011 21:06:01 +0800 Subject: [Tutor] longest common substring In-Reply-To: <4EBEA186.2030400@gmx.net> References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> <4EBE7308.7010408@davea.name> <4EBE8946.5050905@davea.name> <4EBEA186.2030400@gmx.net> Message-ID: On Sun, Nov 13, 2011 at 12:40 AM, Andreas Perstinger wrote: > On 2011-11-12 16:24, lina wrote: >> >> Thanks, ^_^, now better. > > No, I'm afraid you are still not understanding. > >> I checked, the sublist (list) here can't be as a key of the results >> (dict). > > "result" isn't a dictionary. It started as an empty list and later becomes a > null object ("NoneType"). > > You must not forget that you are inside a for-loop. Simplified your > situation is like this: > >>>> result = [] >>>> for i in range(1,10): > ... ? ? print("Iteration {0}, result = {1}".format(i, result)) > ... ? ? result = result.append(i) > ... > Iteration 1, result = [] > Iteration 2, result = None > Traceback (most recent call last): > ?File "", line 3, in > AttributeError: 'NoneType' object has no attribute 'append' > > As you see the error happens in the *second* iteration, because result is no > list any more. > Dave gave you already the explanation: functions and method always return a > value in Python. If the don't have a return statement they return "None". > > Another simple example: > >>>> a = print("Test") > Test > > "print" is a function which prints out the text you passed to it and you > usually aren't interested in its return value. But every function/method in > Python returns something. You save this value in "a" > >>>> print(a) > None > > As you see the return value of "print" is "None". > >>>> a.append(x) > Traceback (most recent call last): > ?File "", line 1, in > AttributeError: 'NoneType' object has no attribute 'append' > > Same error as above, because "NoneType" objects (null objects) don't have a > method "append". > > I also think you mix two different ways to add an element to a list: > > result.append(x) > > is equivalent to > > result = result + [x] (that's what you will use in other languages) Finally, if I am not wrong again, I feel I am kinda of starting figuring out what's going on. Why it's None. The main mistake here I use result = result.append(something) the "=" I checked the print(id(result)) and print(id(result.append()), For the NoneType they shared the same id 8823392 in my laptop. is it temporary address? > > HTH, Andreas Really helps, Thanks again. haha ...for the emails from the list I used to read several times, again and again to understand. Best regards, > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From d at davea.name Sun Nov 13 14:27:31 2011 From: d at davea.name (Dave Angel) Date: Sun, 13 Nov 2011 08:27:31 -0500 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> <4EBD987F.60107@gmx.net> <4EBE7308.7010408@davea.name> <4EBE8946.5050905@davea.name> <4EBEA186.2030400@gmx.net> Message-ID: <4EBFC5C3.1070502@davea.name> On 11/13/2011 08:06 AM, lina wrote: > > Finally, if I am not wrong again, I feel I am kinda of starting > figuring out what's going on. Why it's None. > > The main mistake here I use result = result.append(something) > the "=" > > I checked the print(id(result)) and print(id(result.append()), > > For the NoneType they shared the same id 8823392 in my laptop. is it > temporary address? > None is a unique object, deliberately. No matter how many times people create None, it'll always be the same object. So a= None b = x.append(y) a is b #(true) id(a) == id(b) #(true) Similarly True and False are unique objects. Other objects which are equal to each other may or may not have the same ID; you should not count on it. For example, x = 45+3 y = 6*8 Checking (x==y) is true, of course. But checking (x is y) is indeterminate. It may be true for the first ten tests you do, and false next time -- DaveA From andreas.perstinger at gmx.net Sun Nov 13 23:28:45 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 13 Nov 2011 23:28:45 +0100 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> Message-ID: <4EC0449D.1080603@gmx.net> On 2011-11-11 14:44, lina wrote: > You are right, I did not think of this parts before. and actually the > initiative wish was to find possible paths, I mean, possible > substrings, all possible substrings. not the longest one, but at > least bigger than 3. I had some time today and since you have changed your initial task (from finding the longest common path to finding all common paths with a minimum length) I've modified the code and came up with the following solution: def AllCommonPaths(list1, list2, minimum=3): """ finds all common paths with a minimum length (default = 3)""" # First we have to initialize the necessary variables: # M is an empty table where we will store all found matches # (regardless of their length) M = [[0] * (len(list2)) for i in range(len(list1))] # length is a dictionary where we store the length of each common # path. The keys are the starting positions ot the paths in list1. length = {} # result will be a list of of all found paths result =[] # Now the hard work begins: # Each element of list1 is compared to each element in list2 # (x is the index for list1, y is the index for list2). # If we find a match, we store the distance to the starting point # of the matching block. If we are in the left-most column (x == 0) # or in the upper-most row (y == 0) we have to set the starting # point ourself because we would get negative indexes if we look # for the predecessor cell (M[x - 1][y - 1]). Else, we are one # element farther away as the element before, so we add 1 to its # value. for x in range(len(list1)): for y in range(len(list2)): if list1[x] == list2[y]: if (x == 0) or (y == 0): M[x][y] = 1 else: M[x][y] = M[x - 1][y - 1] + 1 # To get everything done in one pass, we update the length of # the found path in our dictionary if it is longer than the minimum # length. Thus we don't have to get through the whole table a # second time to get all found paths with the minimum length (we # don't know yet if we are already at the end of the matching # block). if M[x][y] >= minimum: length[x + 1 - M[x][y]] = M[x][y] # We now have for all matching blocks their starting # position in list1 and their length. Now we cut out this parts # and create our resulting list for pos in length: result.append(list1[pos:pos + length[pos]]) return result I've tried to explain what I have done, but I'm sure you will still have questions :-). Is this close to what you want? Bye, Andreas PS: Here's the function again without comments: def AllCommonPaths(list1, list2, minimum=3): """ finds all common paths with a minimum length (default = 3)""" M = [[0] * (len(list2)) for i in range(len(list1))] length = {} result =[] for x in range(len(list1)): for y in range(len(list2)): if list1[x] == list2[y]: if (x == 0) or (y == 0): M[x][y] = 1 else: M[x][y] = M[x - 1][y - 1] + 1 if M[x][y] >= minimum: length[x + 1 - M[x][y]] = M[x][y] for pos in length: result.append(list1[pos:pos + length[pos]]) return result From andreas.perstinger at gmx.net Sun Nov 13 23:31:32 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 13 Nov 2011 23:31:32 +0100 Subject: [Tutor] longest common substring In-Reply-To: References: Message-ID: <4EC04544.8020002@gmx.net> On 2011-11-11 16:53, Jerry Hill wrote: > There's nothing wrong with writing your own code to find the longest common > substring, but are you aware that python has a module in the standard > library that already does this? In the difflib module, the SequenceMatcher > class can compare two sequences and extract the longest common sequence of > elements from it, like this: Thanks for the tip. I've played around with it, but I think it doesn't help in the OP's situation. "SequenceMatcher.find_longest_match()" just finds the first common block: Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import difflib >>> first = [0, 1, 2, 3, 0, 4, 5, 6, 0] >>> second = [1, 2, 3, 4, 5, 6] >>> match = difflib.SequenceMatcher(None, first, second) >>> match.find_longest_match(0, len(first), 0, len(second)) Match(a=1, b=0, size=3) Here it returns just [1, 2, 3] but misses [4, 5, 6]. So you would have to adjust the lower limits to get it. "SequenceMatcher.get_matching_blocks()" seems to be a better choice: >>> match.get_matching_blocks() [Match(a=1, b=0, size=3), Match(a=5, b=3, size=3), Match(a=9, b=6, size=0)] Now you get [1, 2, 3] and [4, 5, 6]. But if the two blocks are in the reversed order, there is no longest common subsequence [1, 2, 3, 4, 5, 6] any more and "SequenceMatcher" only finds one part (apparently it chooses the first it comes across in the first list if both have the same length): >>> first = [0, 1, 2, 3, 0, 4, 5, 6, 0] >>> second = [4, 5, 6, 1, 2, 3] >>> match = difflib.SequenceMatcher(None, first, second) >>> match.find_longest_match(0, len(first), 0, len(second)) Match(a=1, b=3, size=3) >>> match.get_matching_blocks() [Match(a=1, b=3, size=3), Match(a=9, b=6, size=0)] From both methods you get [1, 2, 3]. As I've learnt during this tests, there is a difference between subsequences and substrings: http://en.wikipedia.org/wiki/Subsequence#Substring_vs._subsequence If I've understood the OP right, he/she wants to find all common substrings with a minimum length regardless of their order in the strings. Bye, Andreas From lina.lastname at gmail.com Mon Nov 14 04:56:47 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 14 Nov 2011 11:56:47 +0800 Subject: [Tutor] longest common substring In-Reply-To: <4EC0449D.1080603@gmx.net> References: <4EBD1ECD.7020806@gmx.net> <4EC0449D.1080603@gmx.net> Message-ID: On Mon, Nov 14, 2011 at 6:28 AM, Andreas Perstinger wrote: > On 2011-11-11 14:44, lina wrote: >> >> You are right, I did not think of this parts before. and actually the >> initiative wish was to find possible paths, I mean, possible >> substrings, all possible substrings. not the longest one, but at >> least bigger than 3. > > I had some time today and since you have changed your initial task (from > finding the longest common path to finding all common paths with a minimum > length) I've modified the code and came up with the following solution: > > def AllCommonPaths(list1, list2, minimum=3): > """ finds all common paths with a minimum length (default = 3)""" > > ? ?# First we have to initialize the necessary variables: > ? ?# M is an empty table where we will store all found matches > ? ?# (regardless of their length) > > ? ?M = [[0] * (len(list2)) for i in range(len(list1))] > > ? ?# length is a dictionary where we store the length of each common > ? ?# path. The keys are the starting positions ot the paths in list1. > > ? ?length = {} > > ? ?# result will be a list of of all found paths > > ? ?result =[] > > ? ?# Now the hard work begins: > ? ?# Each element of list1 is compared to each element in list2 > ? ?# (x is the index for list1, y is the index for list2). > ? ?# If we find a match, we store the distance to the starting point > ? ?# of the matching block. If we are in the left-most column (x == 0) > ? ?# or in the upper-most row (y == 0) we have to set the starting > ? ?# point ourself because we would get negative indexes if we look > ? ?# for the predecessor cell (M[x - 1][y - 1]). Else, we are one > ? ?# element farther away as the element before, so we add 1 to its > ? ?# value. > > ? ?for x in range(len(list1)): > ? ? ? ?for y in range(len(list2)): > ? ? ? ? ? ?if list1[x] == list2[y]: > ? ? ? ? ? ? ? ?if (x == 0) or (y == 0): > ? ? ? ? ? ? ? ? ? ?M[x][y] = 1 > ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ?M[x][y] = M[x - 1][y - 1] + 1 > > ? ?# To get everything done in one pass, we update the length of > ? ?# the found path in our dictionary if it is longer than the minimum > ? ?# length. Thus we don't have to get through the whole table a > ? ?# second time to get all found paths with the minimum length (we > ? ?# don't know yet if we are already at the end of the matching > ? ?# block). > > ? ? ? ? ? ? ? ?if M[x][y] >= minimum: > ? ? ? ? ? ? ? ? ? ?length[x + 1 - M[x][y]] = M[x][y] > > > ? ?# We now have for all matching blocks their starting > ? ?# position in list1 and their length. Now we cut out this parts > ? ?# and create our resulting list This is a very smart way to store their starting position as a key. My mind was choked about how to save the list as a key before. > > ? ?for pos in length: > ? ? ? ?result.append(list1[pos:pos + length[pos]]) > > ? ?return result > > I've tried to explain what I have done, but I'm sure you will still have > questions :-). I am confused myself with this matrix/array, about how to define x-axis, y-axis. I must understand some parts wrong, for the following: > > Is this close to what you want? > > Bye, Andreas > > PS: Here's the function again without comments: > > def AllCommonPaths(list1, list2, minimum=3): > ? ?""" finds all common paths with a minimum length (default = 3)""" > > ? ?M = [[0] * (len(list2)) for i in range(len(list1))] is it correct that the list2 as the x-axis, the list1 as y-axis:? > ? ?length = {} > ? ?result =[] > > ? ?for x in range(len(list1)): Here for each row , > ? ? ? ?for y in range(len(list2)): This loop go through each column of certain row then, > ? ? ? ? ? ?if list1[x] == list2[y]: > ? ? ? ? ? ? ? ?if (x == 0) or (y == 0): > ? ? ? ? ? ? ? ? ? ?M[x][y] = 1 Here M[x][y] actually means the x-row? y-column, seems conflicts with the x-axis and y-axis. they took y-axis as x row, x-axis as y column. > ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ?M[x][y] = M[x - 1][y - 1] + 1 > ? ? ? ? ? ? ? ?if M[x][y] >= minimum: > ? ? ? ? ? ? ? ? ? ?length[x + 1 - M[x][y]] = M[x][y] > > ? ?for pos in length: > ? ? ? ?result.append(list1[pos:pos + length[pos]]) > > ? ?return result I have no problem understanding the other parts, except the array and axis entangled in my mind. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lina.lastname at gmail.com Mon Nov 14 05:17:40 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 14 Nov 2011 12:17:40 +0800 Subject: [Tutor] longest common substring In-Reply-To: References: <4EBD1ECD.7020806@gmx.net> <4EC0449D.1080603@gmx.net> Message-ID: On Mon, Nov 14, 2011 at 11:56 AM, lina wrote: > On Mon, Nov 14, 2011 at 6:28 AM, Andreas Perstinger > wrote: >> On 2011-11-11 14:44, lina wrote: >>> >>> You are right, I did not think of this parts before. and actually the >>> initiative wish was to find possible paths, I mean, possible >>> substrings, all possible substrings. not the longest one, but at >>> least bigger than 3. >> >> I had some time today and since you have changed your initial task (from >> finding the longest common path to finding all common paths with a minimum >> length) I've modified the code and came up with the following solution: >> >> def AllCommonPaths(list1, list2, minimum=3): >> """ finds all common paths with a minimum length (default = 3)""" >> >> ? ?# First we have to initialize the necessary variables: >> ? ?# M is an empty table where we will store all found matches >> ? ?# (regardless of their length) >> >> ? ?M = [[0] * (len(list2)) for i in range(len(list1))] >> >> ? ?# length is a dictionary where we store the length of each common >> ? ?# path. The keys are the starting positions ot the paths in list1. >> >> ? ?length = {} >> >> ? ?# result will be a list of of all found paths >> >> ? ?result =[] >> >> ? ?# Now the hard work begins: >> ? ?# Each element of list1 is compared to each element in list2 >> ? ?# (x is the index for list1, y is the index for list2). >> ? ?# If we find a match, we store the distance to the starting point >> ? ?# of the matching block. If we are in the left-most column (x == 0) >> ? ?# or in the upper-most row (y == 0) we have to set the starting >> ? ?# point ourself because we would get negative indexes if we look >> ? ?# for the predecessor cell (M[x - 1][y - 1]). Else, we are one >> ? ?# element farther away as the element before, so we add 1 to its >> ? ?# value. >> >> ? ?for x in range(len(list1)): >> ? ? ? ?for y in range(len(list2)): >> ? ? ? ? ? ?if list1[x] == list2[y]: >> ? ? ? ? ? ? ? ?if (x == 0) or (y == 0): >> ? ? ? ? ? ? ? ? ? ?M[x][y] = 1 >> ? ? ? ? ? ? ? ?else: >> ? ? ? ? ? ? ? ? ? ?M[x][y] = M[x - 1][y - 1] + 1 >> >> ? ?# To get everything done in one pass, we update the length of >> ? ?# the found path in our dictionary if it is longer than the minimum >> ? ?# length. Thus we don't have to get through the whole table a >> ? ?# second time to get all found paths with the minimum length (we >> ? ?# don't know yet if we are already at the end of the matching >> ? ?# block). >> >> ? ? ? ? ? ? ? ?if M[x][y] >= minimum: >> ? ? ? ? ? ? ? ? ? ?length[x + 1 - M[x][y]] = M[x][y] >> >> >> ? ?# We now have for all matching blocks their starting >> ? ?# position in list1 and their length. Now we cut out this parts >> ? ?# and create our resulting list How silly I was, it's nothing to do with x,y, since I used i and j, it's crystal clear. Thanks again for your time, Best regards, lina > > This is a very smart way to store their starting position as a key. My > mind was choked about how to save the list as a key before. > >> >> ? ?for pos in length: >> ? ? ? ?result.append(list1[pos:pos + length[pos]]) >> >> ? ?return result >> >> I've tried to explain what I have done, but I'm sure you will still have >> questions :-). > > I am confused myself with this matrix/array, about how to define > x-axis, y-axis. > > I must understand some parts wrong, for the following: >> >> Is this close to what you want? >> >> Bye, Andreas >> >> PS: Here's the function again without comments: >> >> def AllCommonPaths(list1, list2, minimum=3): >> ? ?""" finds all common paths with a minimum length (default = 3)""" >> >> ? ?M = [[0] * (len(list2)) for i in range(len(list1))] > > is it correct that the list2 as the x-axis, the list1 as y-axis:? > >> ? ?length = {} >> ? ?result =[] >> >> ? ?for x in range(len(list1)): > > Here for each row , > >> ? ? ? ?for y in range(len(list2)): > > This loop go through each column of certain row then, > >> ? ? ? ? ? ?if list1[x] == list2[y]: >> ? ? ? ? ? ? ? ?if (x == 0) or (y == 0): >> ? ? ? ? ? ? ? ? ? ?M[x][y] = 1 > > Here M[x][y] actually means the x-row? y-column, seems conflicts with > the x-axis and y-axis. they took y-axis as x row, x-axis as y column. > >> ? ? ? ? ? ? ? ?else: >> ? ? ? ? ? ? ? ? ? ?M[x][y] = M[x - 1][y - 1] + 1 >> ? ? ? ? ? ? ? ?if M[x][y] >= minimum: >> ? ? ? ? ? ? ? ? ? ?length[x + 1 - M[x][y]] = M[x][y] >> >> ? ?for pos in length: >> ? ? ? ?result.append(list1[pos:pos + length[pos]]) >> >> ? ?return result > > I have no problem understanding the other parts, except the array and > axis entangled in my mind. > >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > From lina.lastname at gmail.com Mon Nov 14 13:39:00 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 14 Nov 2011 20:39:00 +0800 Subject: [Tutor] plot Message-ID: Hi, I have not experienced in "plot a figure" with python. Just wonder: Try python-pygraphviz is a good choice? http://pzwart3.wdka.hro.nl/wiki/PythonGraphviz another question: pygrphviz can achieve a better effect than the one on the wikipage, such as can I change the round circle into something a bit "processed", I mean, pentagon or something, or color the edge. Thanks with best regards, From learner404 at gmail.com Mon Nov 14 14:40:29 2011 From: learner404 at gmail.com (learner404) Date: Mon, 14 Nov 2011 14:40:29 +0100 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47401261C@SCACMX008.exchad.jpmchase.net> References: <4EBBCE4B.5030600@pearwood.info> <5B80DD153D7D744689F57F4FB69AF47401261C@SCACMX008.exchad.jpmchase.net> Message-ID: On Fri, Nov 11, 2011 at 12:02 AM, Prasad, Ramit wrote: It is probably easiest to keep myapp.py in the home directory (or > subdirectory of it) and say "python ~/myapp.py" (or "python > ~/.roadierich/myapp.py) from the applescript > > I will go with that for now. My python script is using a bunch of relative paths so I added this before the script: if sys.platform=="darwin": os.chdir(os.path.expanduser("~/myfolder/")) I will try to see if there's something like "inno setup" to make an installer. If anyone have something to recommend for this i'm interested. Thanks Ramit and all. > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Nov 14 15:12:57 2011 From: wprins at gmail.com (Walter Prins) Date: Mon, 14 Nov 2011 14:12:57 +0000 Subject: [Tutor] plot In-Reply-To: References: Message-ID: Hi Lina, On 14 November 2011 12:39, lina wrote: > I have not experienced in "plot a figure" with python. > Try python-pygraphviz is a good choice? > Graphviz is a library to help visualize graphs in the computer science sense. (See http://en.wikipedia.org/wiki/Graph_%28data_structure%29 or the shoreted version: http://is.gd/AKiiMA) So unless by "plot a figure" you actually mean "visualize a graph" in that sense, then the answer would be no I don't think it's a good choice, and instead I'd suggest you want something a bit more general. Google returned this page on stackoverflow which offers several suggestions: http://stackoverflow.com/questions/326300/python-best-library-for-drawing or the shortened version: http://is.gd/vrDTjf >From the above, I'd probably suggest along with one of answers above, that you stick with the TK Canvas for now as this is included with Python. Thus you won't have to get into installing 3rd party packages/libraries/modules to get going. If however you really are trying to visualize a graph of some sort then the question likely needs to be revisited, and then pygrahpviz would probably be a good choice. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From cl2dlope at gmail.com Mon Nov 14 15:35:15 2011 From: cl2dlope at gmail.com (=?ISO-8859-1?Q?Dario_Lopez=2DK=E4sten?=) Date: Mon, 14 Nov 2011 15:35:15 +0100 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: References: <4EBBCE4B.5030600@pearwood.info> <5B80DD153D7D744689F57F4FB69AF47401261C@SCACMX008.exchad.jpmchase.net> Message-ID: Try PyInstaller http://www.pyinstaller.org/ /dario On Nov 14, 2011 2:43 PM, "learner404" wrote: > > On Fri, Nov 11, 2011 at 12:02 AM, Prasad, Ramit > wrote: > > It is probably easiest to keep myapp.py in the home directory (or >> subdirectory of it) and say "python ~/myapp.py" (or "python >> ~/.roadierich/myapp.py) from the applescript >> >> > I will go with that for now. My python script is using a bunch of relative > paths so I added this before the script: > > if sys.platform=="darwin": > > os.chdir(os.path.expanduser("~/myfolder/")) > I will try to see if there's something like "inno setup" to make an > installer. If anyone have something to recommend for this i'm interested. > > Thanks Ramit and all. > > >> >> >> Ramit >> >> >> Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology >> 712 Main Street | Houston, TX 77002 >> work phone: 713 - 216 - 5423 >> >> -- >> This email is confidential and subject to important disclaimers and >> conditions including on offers for the purchase or sale of >> securities, accuracy and completeness of information, viruses, >> confidentiality, legal privilege, and legal entity disclaimers, >> available at http://www.jpmorgan.com/pages/disclosures/email. >> > > > _______________________________________________ > 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 lina.lastname at gmail.com Mon Nov 14 16:30:55 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 14 Nov 2011 23:30:55 +0800 Subject: [Tutor] plot In-Reply-To: References: Message-ID: On Mon, Nov 14, 2011 at 10:12 PM, Walter Prins wrote: > Hi Lina, > > On 14 November 2011 12:39, lina wrote: >> >> I have not experienced in "plot a figure" with python. >> Try python-pygraphviz is a good choice? > > Graphviz is a library to help visualize graphs in the computer science > sense.? (See? http://en.wikipedia.org/wiki/Graph_%28data_structure%29 or the > shoreted version: http://is.gd/AKiiMA)? So unless by "plot a figure" you > actually mean "visualize a graph" in that sense, then the answer would be no > I don't think it's a good choice, and instead I'd suggest you want something > a bit more general.? Google returned this page on stackoverflow which offers > several suggestions: > http://stackoverflow.com/questions/326300/python-best-library-for-drawing > or the shortened version: > http://is.gd/vrDTjf > > From the above, I'd probably suggest along with one of answers above, that > you stick with the TK Canvas for now as this is included with Python.? Thus > you won't have to get into installing 3rd party packages/libraries/modules > to get going. Thanks for your suggestions, I have installed this package before posting, it's supported by python2x, but not 3. I was interested cause it could (hopefully) give a better way of draw the pathway than what I did by hands, I spent whole afternoon trying to draw by hands ... lol ... On the left part of page, the set should be 1-42, and the right page is supposed to be 43-84. parts of those data: 39 20 39 34 48 76 34 34 48 76 34 48 34 48 76 34 48 34 77 20 76 34 32 76 34 15 10 15 34 76 34 76 34 32 34 were generated from last post. for each line, it's the set accrodingly to be 39->20-> and back to 39, another path is 34->48->76-> and back to 34 and following another path. I checked by eyes, and the 34 and 76 should be centered on the left and right part of the page. The connection directional lines are a bit entangled, even I tried arranged the different 2D positions of those data. I don't want to choose above way, so wonder whether I can do a try by python. Based on the links provided above, the nodes and paths seems have already fixed. well... Thanks again, I will try and see. Best regards, > > If however you really are trying to visualize a? graph of some sort then the > question likely needs to be revisited, and then pygrahpviz would probably be > a good choice. > > Walter > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From lina.lastname at gmail.com Mon Nov 14 17:32:09 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 15 Nov 2011 00:32:09 +0800 Subject: [Tutor] plot In-Reply-To: References: Message-ID: May I ask something I met during reading the graph links provided? For the case I faced now, ... [['76', '34', '76'], ['1', '5', '1']] [['64', '62', '58'], ['64', '58', '64'], ['13', '46', '64']] ... [['64', '75', '64'], ['62', '46', '13'], ['64', '75', '64'], ['64', '75', '62'], ['64', '75', '64'], ['64', '75', '64'], ['76', '34', '32'], ['13', '75', '64']] ... I don't know which algorithms I should look up into it. It's directed graph, but not a network flow, cause there is no certain source or sink, neither there is no capacity limit, but it would be wonderful to get the "flow" among those paths (strictly speaking, not flow, just the load of each edge, the occurence of the path). Sorry I don't have CS backgrounds, so it's a bit hard for me to get start. Thanks for any suggestions, Best regards, From cranky.frankie at gmail.com Mon Nov 14 19:58:54 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 14 Nov 2011 13:58:54 -0500 Subject: [Tutor] interesting behaviour with postional output Message-ID: I'm working on writing out postional output. When I use this statement: print('%-40s%s' % (element_list[0], element_list[1])) I get nice, lined up columns on the screen. When I write to a file like this: new_line = ('%-40s%s%s' % (element_list[0], element_list[1],'\n')) file_out.write(new_line) a very funny thing happens. When I open the file in Notepad, the columns are not lined up, however when I switch the font to Courier, they * are* lined up. So what's happening is the output statement is working correctly - the second column starts in the 41st postion - but you have to use a non-proportional font to see it. I was hoping to not have the font be an issue. Very interesting. -- Frank L. "Cranky Frankie" Palmeri, Guilderland, NY, USA ? ? ? ? ? ? ?Risible Riding Raconteur & Writer Don't sweat the petty things, and don't pet the sweaty things. From alan.gauld at btinternet.com Mon Nov 14 20:28:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Nov 2011 19:28:06 +0000 Subject: [Tutor] interesting behaviour with postional output In-Reply-To: References: Message-ID: On 14/11/11 18:58, Cranky Frankie wrote: > I'm working on writing out postional output. When I use this statement: > > print('%-40s%s' % (element_list[0], element_list[1])) ... > a very funny thing happens. When I open the file in Notepad, the > columns are not lined up, however when I switch the font to Courier, > they * are* lined up. So what's happening The data in the file is simply a set of characters. How that is represented visually depends on the display device settinghs, especially the font. Some fonts (like courier) are mono-spaced which means every character takes up the same amount of horizontal space, thus your output aligns correctly. But other fonts are proportionately spaced which means than an 'i' takes up less room than an 'm'. This is more visually appealing for free text but it messes up the spacing for your type of output. If you want to display the data nicely after processing then you are better off using a markup language such as HTML and creating a table. Then it can be displayed in any browser using any font you like and the table structure will ensure it all lines up. But, it's more work to create the output than simple a single print operation! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Nov 14 20:31:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 14 Nov 2011 19:31:00 +0000 Subject: [Tutor] [OSX] "Executable" .py or pyc script (stuck at Applescript) In-Reply-To: References: <4EBBCE4B.5030600@pearwood.info> <5B80DD153D7D744689F57F4FB69AF47401261C@SCACMX008.exchad.jpmchase.net> Message-ID: On 14/11/11 13:40, learner404 wrote: > I will try to see if there's something like "inno setup" to make an > installer. If anyone have something to recommend for this i'm interested. I'm no Mac/Python expert but I seem to recall the MacPython web page had info on how to create a Mac App bundle that avoided the need to use AppleScript etc. It was all about the file structure and the config information. But it was a wee while ago and I may be imagining it... :-) Alan G From cfuller084 at thinkingplanet.net Mon Nov 14 20:26:00 2011 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 14 Nov 2011 13:26:00 -0600 Subject: [Tutor] interesting behaviour with postional output In-Reply-To: References: Message-ID: <201111141326.03779.cfuller084@thinkingplanet.net> Fonts can be categorized as "fixed" or "proportional" widths. Proportional width fonts have different widths depending on the character. If you want to line up text, you must use fixed width fonts like courier, or use tabs, but that can be unreliable. You can get fancy and measure the width of a string in some font (if you have an API that allows it), but that is rarely worthwhile. Cheers On Monday 14 November 2011, Cranky Frankie wrote: > I'm working on writing out postional output. When I use this statement: > > print('%-40s%s' % (element_list[0], element_list[1])) > > I get nice, lined up columns on the screen. When I write to a file like > this: > > new_line = ('%-40s%s%s' % (element_list[0], element_list[1],'\n')) > file_out.write(new_line) > > a very funny thing happens. When I open the file in Notepad, the > columns are not lined up, however when I switch the font to Courier, > they * are* lined up. So what's happening is the output statement is > working correctly - the second column starts in the 41st postion - but > you have to use a non-proportional font to see it. > > I was hoping to not have the font be an issue. > > Very interesting. From deshpande.jaidev at gmail.com Mon Nov 14 21:30:20 2011 From: deshpande.jaidev at gmail.com (Jaidev Deshpande) Date: Tue, 15 Nov 2011 02:00:20 +0530 Subject: [Tutor] Cython vs Python-C API Message-ID: Hi I need to perform cubic spline interpolation over a range of points, and I have written the code for the same in C and in Python. The interpolation is part of a bigger project. I want to front end for the project to be Python. Ideally I want Python only to deal with data visualization and i/o, and I'll leave the computationally expensive part of the project to C extensions, which can be imported as functions into Python. To this end, the interpolation can be handled in two ways: 1. I can either compile the C code into a module using the Python-C/C++ API, through which I can simple 'import' the required function. 2. I can use the Python code and extend it using Cython. Which will give me a better performance? Thanls -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranceh at gmail.com Mon Nov 14 21:49:28 2011 From: ranceh at gmail.com (Rance Hall) Date: Mon, 14 Nov 2011 14:49:28 -0600 Subject: [Tutor] going big (in terms of code base) Message-ID: Ive just finished a major project with python and database connectivity. It was cool, and the friend I wrote it for was happy. It was strictly a terminal based app. To GUI of any sort. Because I like to write cross platform apps as much as possible, tools like python and os common widget sets like tk/tcl are my first choice. So Ive started studying tkinter (from python 3.x) I'm pleased with the flexibility. So far Ive been a very procedural based coder. Ive not cared much for Object Oriented stuff because I didn't learn to think/program that way. (think Fortran/Pascal, etc) GUIs add a lot of code bloat and lots of chances for bugs that have nothing to do with the logic of your program. I'm looking for a way to manage large projects (large in terms of code size) There are lots of new concepts to grasp here: From basic GUI stuff like event handlers to understanding class layout and what things go in this class and what things go in that one. Before proceeding I need to understand how best to break up a large file into several smaller files and not break anything. I assume that "import" will be part of the solution but it only "imports" complete python modules. Much different than a php include for short code snippets. I'm guessing that means I have to learn how to create my own modules as well. And then how to manage them. The hard part I'm struggling with at this point is understanding what python calls the things I need to understand. This makes sense in terms of being able to go back and fix something later and know where it is to find it. What I would like to do is create a basic app framework that I can use/reuse on future projects. What else to I need to know about to make my idea a reality? In what order would you suggest I learn these things so I can interconnect them properly. For example. OOP before tkinter? Thanks for your time. Rance From joel.goldstick at gmail.com Mon Nov 14 22:16:27 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 14 Nov 2011 16:16:27 -0500 Subject: [Tutor] interesting behaviour with postional output In-Reply-To: <201111141326.03779.cfuller084@thinkingplanet.net> References: <201111141326.03779.cfuller084@thinkingplanet.net> Message-ID: On Mon, Nov 14, 2011 at 2:26 PM, Chris Fuller wrote: > > Fonts can be categorized as "fixed" or "proportional" widths. Proportional > width fonts have different widths depending on the character. > > If you want to line up text, you must use fixed width fonts like courier, > or > use tabs, but that can be unreliable. You can get fancy and measure the > width > of a string in some font (if you have an API that allows it), but that is > rarely worthwhile. > > Cheers > > On Monday 14 November 2011, Cranky Frankie wrote: > > I'm working on writing out postional output. When I use this statement: > > > > print('%-40s%s' % (element_list[0], element_list[1])) > > > > I get nice, lined up columns on the screen. When I write to a file like > > this: > > > > new_line = ('%-40s%s%s' % (element_list[0], element_list[1],'\n')) > > file_out.write(new_line) > > > > a very funny thing happens. When I open the file in Notepad, the > > columns are not lined up, however when I switch the font to Courier, > > they * are* lined up. So what's happening is the output statement is > > working correctly - the second column starts in the 41st postion - but > > you have to use a non-proportional font to see it. > > > > I was hoping to not have the font be an issue. > > > > Very interesting. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Tabs will cause several kinds of problems. First, tabs on lines with other characters will do the same thing as spaces will do. The same problem will exist. Second, if tabs are set for say every 4 spaces, and you have 3 characters of text in your first column, then tab to will go to the 8th column. If you have 8 characters of text, you will go to the 12 column. So they won't line up even if you use a mono spaced font. So, as was stated, best to use mono space if you are writing to a terminal. If you are writing web pages, of course you have lots of formatting options -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranceh at gmail.com Mon Nov 14 22:27:54 2011 From: ranceh at gmail.com (Rance Hall) Date: Mon, 14 Nov 2011 15:27:54 -0600 Subject: [Tutor] interesting behaviour with postional output In-Reply-To: References: <201111141326.03779.cfuller084@thinkingplanet.net> Message-ID: On Mon, Nov 14, 2011 at 3:16 PM, Joel Goldstick wrote: > So, as was stated, best to use mono space if you are writing to a terminal. > If you are writing web pages, of course you have lots of formatting options > > -- > Joel Goldstick One option I've used in the past for issues such as this is enscript. You can have python call enscript with some formatting options, including font, and pipe the output of enscript into ps2pdf and you have a pdf file that you can email/upload to a web server, etc. The OP didn't say what the intended output was supposed to do, but just that it was different between screen and other output modes. The OP now knows that because of the difference between fixed width and proportional fonts, but my suspicion is that that piece of information while it fully explains and answers the OP, there is more forthcoming. From tony.pelletier at gmail.com Mon Nov 14 22:43:13 2011 From: tony.pelletier at gmail.com (Tony Pelletier) Date: Mon, 14 Nov 2011 16:43:13 -0500 Subject: [Tutor] Handling a Unicode Return using Pyodbc Message-ID: Good Afternoon, I'm writing a program that is essentially connecting to MS SQL Server and dumping all the contents of the tables to separate csv's. I'm almost complete, but now I'm running into a Unicode issue and I'm not sure how to resolve it. I have a ridiculous amount of tables but I managed to figure out it was my Contact and a contact named Robert Bock. Here's what I caught. (127, None, u'Robert', None, u'B\xf6ck', 'uCompany Name', None, 1, 0, 327, 0) The u'B\xf6ck' is actually B?ck. Notice the ? My problem is I'm not really sure how to handle it and whether or not it's failing on the query or the insert to the csv. The Exception is: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128) Thanks Tony -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Mon Nov 14 23:02:02 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 14 Nov 2011 17:02:02 -0500 Subject: [Tutor] Cython vs Python-C API In-Reply-To: References: Message-ID: On Mon, Nov 14, 2011 at 3:30 PM, Jaidev Deshpande < deshpande.jaidev at gmail.com> wrote: > Hi > > I need to perform cubic spline interpolation over a range of points, and I > have written the code for the same in C and in Python. > > The interpolation is part of a bigger project. I want to front end for the > project to be Python. Ideally I want Python only to deal with data > visualization and i/o, and I'll leave the computationally expensive part of > the project to C extensions, which can be imported as functions into Python. > > To this end, the interpolation can be handled in two ways: > > 1. I can either compile the C code into a module using the Python-C/C++ > API, through which I can simple 'import' the required function. > 2. I can use the Python code and extend it using Cython. > > Which will give me a better performance? > Aren't you, right now, in the ideal position to answer that question for yourself? You have the same algorithm implemented both in C and in Python. Can't you compile that python code with Cython, then just test the two to see which is faster? -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Nov 14 23:05:51 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Nov 2011 14:05:51 -0800 Subject: [Tutor] Handling a Unicode Return using Pyodbc In-Reply-To: References: Message-ID: On Mon, Nov 14, 2011 at 1:43 PM, Tony Pelletier wrote: > Good Afternoon, > > I'm writing a program that is essentially connecting to MS SQL Server and > dumping all the contents of the tables to separate csv's. I'm almost > complete, but now I'm running into a Unicode issue and I'm not sure how to > resolve it. > > I have a ridiculous amount of tables but I managed to figure out it was my > Contact and a contact named Robert Bock. Here's what I caught. > > (127, None, u'Robert', None, u'B\xf6ck', 'uCompany Name', None, 1, 0, 327, > 0) > > The u'B\xf6ck' is actually B?ck. Notice the ? > > My problem is I'm not really sure how to handle it and whether or not it's > failing on the query or the insert to the csv. The Exception is: > > 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in > range(128) > > We'd be able to help a lot better if you post the _entire_ error message/traceback; for one thing, the traceback ought to give enough info to determine which operation is throwing the error (query or insert). That being said, when you do figure out where it's happening, the solution will be change how you're handling the string: you'll need to explicitly run it through the .encode() method, using either a Unicode-aware codec OR the default ASCII codec with errors="replace" or errors="ignore" (my vote would be for Unicode, of course, but it's your data.) Here's a page you might find useful: http://docs.python.org/howto/unicode.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Nov 14 23:08:06 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 14 Nov 2011 14:08:06 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) Message-ID: <4EC19146.7080900@sbcglobal.net> I had py 2.5.2 installed (Yes, I know it's old) on my Win 7 64-bit PC earlier this year, but it began to fail back in June. I tried a uninstall/install, but that got me nowhere. I tried again yesterday. Uninstalled, then puzzled over whether I should delete the remaining python25 folder. There were a few files in it. Nothing that looked relevant of use any longer. I did notice several Remove....exe files for numpy, scipy and others. Rather than chance messing up python25, I renamed it, then installed 2.5.2. I found that every time I tried to activate a py file, or open it in IDLE, I would get an error that said something like this: c:\Users\blah\...\junk.py is not a valid Win 32 app. (or idle.pyw) Comments? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "My suspicion is that the universe is not only queerer than we suppose, but queerer than we can suppose." -- Physiologist and Geneticist J.B.S. Haldane 1860-1936 (Maybe not, Dr. Haldane. We have an amazing imagination) Web Page: From marc.tompkins at gmail.com Mon Nov 14 23:18:42 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Nov 2011 14:18:42 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC19146.7080900@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> Message-ID: On Mon, Nov 14, 2011 at 2:08 PM, Wayne Watson wrote: > I had py 2.5.2 installed (Yes, I know it's old) on my Win 7 64-bit PC > earlier this year, but it began to fail back in June. I tried a > uninstall/install, but that got me nowhere. I tried again yesterday. > Uninstalled, then puzzled over whether I should delete the remaining > python25 folder. There were a few files in it. Nothing that looked > relevant of use any longer. I did notice several Remove....exe files for > numpy, scipy and others. Rather than chance messing up python25, I renamed > it, then installed 2.5.2. > > I found that every time I tried to activate a py file, or open it in IDLE, > I would get an error that said something like this: > c:\Users\blah\...\junk.py is not a valid Win 32 app. (or idle.pyw) > > Comments? > > Sounds like a problem with Windows' file associations / default programs settings. Go to Control Panel / Programs / Default Programs / Set your default programs. I'm guessing that ".py" and ".pyw" are still set to be opened by a Python installation that isn't there anymore. Fix that, and you should be golden. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Nov 14 23:25:32 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 14 Nov 2011 16:25:32 -0600 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC19146.7080900@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> Message-ID: On Mon, Nov 14, 2011 at 4:08 PM, Wayne Watson wrote: > I had py 2.5.2 installed (Yes, I know it's old) on my Win 7 64-bit PC > earlier this year, but it began to fail back in June. I tried a > uninstall/install, but that got me nowhere. I tried again yesterday. > Uninstalled, then puzzled over whether I should delete the remaining > python25 folder. There were a few files in it. Nothing that looked > relevant of use any longer. I did notice several Remove....exe files for > numpy, scipy and others. Rather than chance messing up python25, I renamed > it, then installed 2.5.2. > > I found that every time I tried to activate a py file, or open it in IDLE, > I would get an error that said something like this: > c:\Users\blah\...\junk.py is not a valid Win 32 app. (or idle.pyw) > > Comments? Not specifically a Python program - more Windows-related than anything. That being said, it sounds an awful lot like the python.exe isn't in your path. To get it there you can open windows explorer (WIN+E) right click on computer > properties then click advanced system settings. In the window that pops up, click the "environment variables" button. In the "system variables" portion, find the path variable and click the "Edit..." button. Assuming that your new installation was placed in C:\Python25\ you will want to add ";C:\Python25\" (the semicolon is important!) to the end of your path. Then you should be able to open the .py files. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Nov 15 00:01:20 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 14 Nov 2011 17:01:20 -0600 Subject: [Tutor] going big (in terms of code base) In-Reply-To: References: Message-ID: On Mon, Nov 14, 2011 at 2:49 PM, Rance Hall wrote: > So far Ive been a very procedural based coder. Ive not cared much > for Object Oriented stuff because I didn't learn to think/program that > way. (think Fortran/Pascal, etc) > There's always room for growth! I think that if you can understand programming in general, starting to learn OOP isn't that much of a stretch - but it is still a stretch. And since you've been using Python, I think that gives you a leg up because everything you've been using are objects, even if they allow you to ignore their object-ness most of the time. > GUIs add a lot of code bloat and lots of chances for bugs that have > nothing to do with the logic of your program. > I'm not sure that I would entirely agree with this statement. I think that GUIs definitely increase the likelihood of code bloat, they don't necessarily create it. Bloat is unnecessary cruft that could (and should) be removed from your program. If you want a graphical interface it's very difficult to do that without a nice framework ;) > > I'm looking for a way to manage large projects (large in terms of code > size) > > There are lots of new concepts to grasp here: From basic GUI stuff > like event handlers to understanding class layout and what things go > in this class and what things go in that one. > > Before proceeding I need to understand how best to break up a large > file into several smaller files and not break anything. > > I assume that "import" will be part of the solution but it only > "imports" complete python modules. Much different than a php include > for short code snippets. > Modules are definitely what you're looking for - but you can use modules in a strictly procedural sense. Heck, if you wanted to make some pretty un-Pythonic code you could throw imports all over your program in a very strictly procedural fashion. But don't do that. > > I'm guessing that means I have to learn how to create my own modules > as well. And then how to manage them. > > Yes indeed. If you're planning to do a lot of things with modules, and trying to deploy them to other people, I'd highly recommend learning virtualenv - it will save you a lot of headaches in the long run. > The hard part I'm struggling with at this point is understanding what > python calls the things I need to understand. > That's something we're fairly good at, and probably more than happy to point you in the direction of. If you can say "I need a thingy that does this other thing", there's probably someone here who knows what you need. > > This makes sense in terms of being able to go back and fix something > later and know where it is to find it. > > What I would like to do is create a basic app framework that I can > use/reuse on future projects. > > Depending on what you need, this may be premature optimization because there already exists basic frameworks (like Tkinter). If you find that there are a lot of duplication/customization things that you're doing, then it makes sense to automate that and create some type of framework... but in the several Tkinter programs that I've created I've never said "Huh. This is just clunky, I wish I had X". Well, except for the H/VBoxes from GTK - but I created my own wrappers around the Frame class and got exactly what I wanted. What else to I need to know about to make my idea a reality? In what > order would you suggest I learn these things so I can interconnect > them properly. For example. OOP before tkinter? > I'm not sure that OOP or Tkinter would make learning one or the other any easier, but I suspect that if there is a best order that OOP might be on the better side. But then again, it might not be necessary. Even though I've written classes for my programs it's hardly required, but I do like to think that it makes some things easier. Actually, that's pretty much my criteria for using classes or anything else. "Will it make this problem easier?" is the question that I ask myself. In the case of some program hitting a database, maybe I have a table of "people" and it stores the people that I know. So maybe I'll make a People class that has the following attributes: firstname lastname phone email address And since in my mind, real people already have those things, it's easier for me to think of myself as: wayne = People() wayne.firstname = "Wayne" wayne.lastname = "Werner" wayne.phone = "555-555-5555" wayne.email = "waynejwerner (at) gmail com" wayne.address = "The Castle Arrrrgggh!" than to think of myself as: ("Wayne", "Werner", "555-555-5555", "waynejwerner (at) gmail com", "The Castle Arrrrrggggh!") Plus if I'm passing myself to a function: def reverse_lastname(person): person.lastname = person.lastname[::-1] it's a lot easier to tell what person.lastname means, than person[1]. If I was writing the procedural code, I'd honestly probably write a function get_lastname(person) or something similar. If you think that it will be easier for you to maintain your programs using the OOP-paradigm, go ahead and learn it. But you are also perfectly capable of creating a procedural program using modules and Tkinter without ever writing a class definition. Of course, someone else who ends out maintaining your program might not feel that way ;) Good luck! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 15 00:18:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Nov 2011 10:18:25 +1100 Subject: [Tutor] Cython vs Python-C API In-Reply-To: References: Message-ID: <4EC1A1C1.5000401@pearwood.info> Jaidev Deshpande wrote: > 1. I can either compile the C code into a module using the Python-C/C++ > API, through which I can simple 'import' the required function. > 2. I can use the Python code and extend it using Cython. > > Which will give me a better performance? The only way to be sure is to do both, measure the speed of each, and compare. But in *principle* hand-written C may be faster, but in *practice* Cython is likely to be as fast and possibly faster. It's certainly easier: you can afford to try Cython and only bother with the pure C code if you actually need it. A more interesting question is "which will give you sufficiently fast performance for the least development time?" Some further options: 3. Just write it in pure Python, and don't worry about speeding it up unless you actually need to. Unless you have actually *measured* the time taken, how do you know which (if any) bits are too slow? Perhaps it is already fast enough, and making it faster just throws away developer time for no benefit. If the cubic spline interpolation is too slow, you still have additional options: 4. If you only need to support Python 2 on 32-bit platforms, use the Psyco JIT compiler to speed it up. This only works on the standard CPython version (not to be confused with Cython), not IronPython or Jython compilers. 5. Use PyPy, which is an optimizing compiler for Python. This is likely to be ten times as fast as CPython. PyPy is fast enough to do some video processing tasks in real-time, so it likely will be fast enough for cubic splines. http://morepypy.blogspot.com/2011/07/realtime-image-processing-in-python.html 6. Extend the Python code with Cython, and see if that is sufficiently fast enough for your needs. 7. And finally, if the Cython code is too slow, re-write in C by hand. -- Steven From steve at pearwood.info Tue Nov 15 00:32:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 15 Nov 2011 10:32:56 +1100 Subject: [Tutor] interesting behaviour with postional output In-Reply-To: References: Message-ID: <4EC1A528.7010306@pearwood.info> Cranky Frankie wrote: > I'm working on writing out postional output. When I use this statement: > > print('%-40s%s' % (element_list[0], element_list[1])) > > I get nice, lined up columns on the screen. When I write to a file like this: > > new_line = ('%-40s%s%s' % (element_list[0], element_list[1],'\n')) > file_out.write(new_line) > > a very funny thing happens. When I open the file in Notepad, the > columns are not lined up, however when I switch the font to Courier, > they * are* lined up. So what's happening is the output statement is > working correctly - the second column starts in the 41st postion - but > you have to use a non-proportional font to see it. Well duh :) No offense intended, but what you're describing isn't "a very funny thing". It's perfectly natural. You're lining text up in columns according to the *character position*, which naturally assumes that each character is the same width. If characters vary in width, you need to calculate *pixel widths* of each character, and align them according to the actual pixels used -- and that will depend on the precise details of which font face, size and style are being used, the font rendering algorithm used, and the resolution of the display device (printer or screen). One alternative is to line up each column using tabs, written in Python as '\t', but that doesn't entirely solve the problem, because while it will eliminate small differences in pixel width, sufficiently large differences will throw your tabs out too. And you will be dependent on the viewer's tab settings: what they will see will vary according to the application's handling of tabs and where the user sets their tab stops. A particularly stupid text editor may treat each tab as if it were a single space; a programmer's editor will cause the tab to align to the next multiple of 8 spaces, or 4, or possibly some other value as set by the user; another editor may treat each tab as *exactly* 8 spaces, regardless of where the tab falls; a word processor application will probably allow the user to set custom tab stops rather than assume each tab is 8 spaces; etc. If you expect the user to use a proper programmer's editor like vi or emacs, you can embed display instructions at the end of the file to instruct the editor which tab stops to use, and whether to use a proportional or non-proportional font. But if the user uses Notepad, or Microsoft Word, you have no control over the display format. One sensible approach is to simply pass the responsibility for setting the display settings to the user. "Use a monospaced font" is not particularly hard for experienced computer users to follow. "Use Courier New" is simple enough for even the average user. Another is to use something is a CSV file, and instruct them to open the file in a spreadsheet program like Excel instead of a text editor. Or if you're really keen, you can generate a presentation format like PDF. That's basically the only way to be completely independent of the user's settings. -- Steven From sierra_mtnview at sbcglobal.net Tue Nov 15 01:00:11 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 14 Nov 2011 16:00:11 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> Message-ID: <4EC1AB8B.8080602@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Nov 15 01:04:52 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Nov 2011 16:04:52 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC1AB8B.8080602@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> Message-ID: On Mon, Nov 14, 2011 at 4:00 PM, Wayne Watson wrote: > I do not see Python listed there. I see Word Pad, Winamp, Paint, ... > > I'm at CP/All CP Items/Default prgrms/Set Defaults > > My bad. It's Control Panel\Programs\Default Programs\Set Associations. (I could be wrong, but wasn't this all in one place in previous versions...?) Anyway, scroll down to .py/.pyc/.pyo/.pyw, and I bet you'll find it pointing to a no-longer-valid installation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 15 01:17:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Nov 2011 00:17:11 +0000 Subject: [Tutor] going big (in terms of code base) In-Reply-To: References: Message-ID: On 14/11/11 20:49, Rance Hall wrote: > There are lots of new concepts to grasp here: From basic GUI stuff > like event handlers to understanding class layout and what things go > in this class and what things go in that one. Try the "event driven programming" and OOP topics in my tutor... > Before proceeding I need to understand how best to break up a large > file into several smaller files and not break anything. Try the modules & functions topic in my tutor (emphasising the modules bit) > The hard part I'm struggling with at this point is understanding what > python calls the things I need to understand. My tutor covers that, but so will some posts here :-) > What I would like to do is create a basic app framework that I can > use/reuse on future projects. For the most basic GUII stiff my GUI tiopic may help, but it sounds like you may already be up to speed there. Most GUIs (although not Tkinter) proivide a basic framework. But its fairly easy to do one yourself in tkinter, Programming Python by Lutz for example, has one such. The best pattern for GUI development is one file per window/major dialog and separate the app logic from the presentation. (A step towards the Model/View/Controller GUI design pattern) > What else to I need to know about to make my idea a reality? In what > order would you suggest I learn these things so I can interconnect > them properly. For example. OOP before tkinter? I'd definitely go event-driven, followed by OOP, followed by GUI. Thats why its in that order in my tutor :-) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Tue Nov 15 01:55:26 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 14 Nov 2011 16:55:26 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> Message-ID: <4EC1B87E.2020103@sbcglobal.net> An HTML attachment was scrubbed... URL: From ranceh at gmail.com Tue Nov 15 02:01:49 2011 From: ranceh at gmail.com (Rance Hall) Date: Mon, 14 Nov 2011 19:01:49 -0600 Subject: [Tutor] going big (in terms of code base) In-Reply-To: References: Message-ID: On Mon, Nov 14, 2011 at 5:01 PM, Wayne Werner wrote: > On Mon, Nov 14, 2011 at 2:49 PM, Rance Hall wrote: >> >> GUIs add a lot of code bloat and lots of chances for bugs that have >> nothing to do with the logic of your program. > > I'm not sure that I would entirely agree with this statement. I think that > GUIs definitely increase the likelihood of code bloat, they don't > necessarily create it. Bloat is unnecessary cruft that could (and should) be > removed from your program. If you want a graphical interface it's very > difficult to do that without a nice framework ;) > Yea, you are right. I didn't say that well. I think we were thinking the same thing, but you said it better than I did. >> >> I'm looking for a way to manage large projects (large in terms of code >> size) >> >> There are lots of new concepts to grasp here: From basic GUI stuff >> like event handlers to understanding class layout and what things go >> in this class and what things go in that one. >> >> Before proceeding I need to understand how best to break up a large >> file into several smaller files and not break anything. >> >> I assume that "import" will be part of the solution but it only >> "imports" complete python modules. ?Much different than a php include >> for short code snippets. > > Modules are definitely what you're looking for - but you can use modules in > a strictly procedural sense. Heck, if you wanted to make some pretty > un-Pythonic code you could throw imports all over your program in a very > strictly procedural fashion. But don't do that. > >> >> I'm guessing that means I have to learn how to create my own modules >> as well. ?And then how to manage them. >> > > Yes indeed. If you're planning to do a lot of things with modules, and > trying to deploy them to other people, I'd highly recommend learning > virtualenv - it will save you a lot of headaches in the long run. > Thanks for this, I looked it up, and it at least looks like something I could make use of. >> >> This makes sense in terms of being able to go back and fix something >> later and know where it is to find it. >> >> What I would like to do is create a basic app framework that I can >> use/reuse on future projects. >> > > Depending on what you need, this may be premature optimization because there > already exists basic frameworks (like Tkinter). > If you find that there are a lot of duplication/customization things that > you're doing, then it makes sense to automate that and create some type of > framework... but in the several Tkinter programs that I've created I've > never said "Huh. This is just clunky, I wish I had X". Well, except for the > H/VBoxes from GTK - but I created my own wrappers around the Frame class and > got exactly what I wanted. I think perhaps we are talking past each other here. I'm thinking a sort of skeleton directory that already has the basic code to create a basic main window, with a menubar and status message box at the bottom. That includes basic functions of db connectivity. Sort of like a template in a larger IDE. >> >> What else to I need to know about to make my idea a reality? ?In what >> order would you suggest I learn these things so I can interconnect >> them properly. ?For example. OOP before tkinter? > > I'm not sure that OOP or Tkinter would make learning one or the other any > easier, but I suspect that if there is a best order that OOP might be on the > better side. But then again, it might not be necessary. Even though I've > written classes for my programs it's hardly required, but I do like to think > that it makes some things easier. Relearning the way I think in terms of being a coder certainly does not qualify under "easier," but if I'm to write code that's maintainable for the long term then I need to switch to OOP > Actually, that's pretty much my criteria for using classes or anything else. > "Will it make this problem easier?" is the question that I ask myself. In > the case of some program hitting a database, maybe I have a table of > "people" and it stores the people that I know. So maybe I'll make a People > class that has the following attributes: > firstname > lastname > phone > email > address > And since in my mind, real people already have those things, it's easier for > me to think of myself as: > wayne = People() > wayne.firstname = "Wayne" > wayne.lastname = "Werner" > wayne.phone = "555-555-5555" > wayne.email = "waynejwerner (at) gmail com" > wayne.address = "The Castle Arrrrgggh!" > than to think of myself as: > ("Wayne", "Werner", "555-555-5555", "waynejwerner (at) gmail com", > "The Castle Arrrrrggggh!") > Plus if I'm passing myself to a function: > def reverse_lastname(person): > ? ? person.lastname = person.lastname[::-1] > it's a lot easier to tell what person.lastname means, than person[1]. If I > was writing the procedural code, I'd honestly probably write a function > get_lastname(person) or something similar. > If you think that it will be easier for you to maintain your programs using > the OOP-paradigm, go ahead and learn it. But you are also perfectly capable > of creating a procedural program using modules and Tkinter without ever > writing a class definition. Of course, someone else who ends out maintaining > your program might not feel that way ;) This is my chief interest in OOP in a nutshell. If I take the time to learn OOP then it may take longer and be "harder" (at least for awhile) in the beginning, but changes and long term maintenance should be much, much easier. If I reconsider your Person example and entertain a request to restructure the "address" to "city", "state", "zip" for US addresses is something that previously has been very difficult. where in OOP seems to make that change very easily. This is where I'm hoping to gain from OOP. Rance From alan.gauld at btinternet.com Tue Nov 15 02:26:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Nov 2011 01:26:16 +0000 Subject: [Tutor] going big (in terms of code base) In-Reply-To: References: Message-ID: On 15/11/11 01:01, Rance Hall wrote: > I think perhaps we are talking past each other here. I'm thinking a > sort of skeleton directory that already has the basic code to create a > basic main window, with a menubar and status message box at the > bottom. That includes basic functions of db connectivity. Sort of > like a template in a larger IDE. And thats exactly where OOP comes in because you can easily create a class that has that structure. Then you just create new applications as a subclass of your template. Then add the extras that this particular instance needs (menu items, window controls etc). Finally provide the event handlers to link it to your business logic/objects. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Tue Nov 15 02:25:19 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 14 Nov 2011 17:25:19 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> Message-ID: <4EC1BF7F.40205@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Nov 15 03:17:33 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 14 Nov 2011 18:17:33 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC1B87E.2020103@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> Message-ID: On Mon, Nov 14, 2011 at 4:55 PM, Wayne Watson wrote: > > > On 11/14/2011 4:04 PM, Marc Tompkins wrote: > > On Mon, Nov 14, 2011 at 4:00 PM, Wayne Watson < > sierra_mtnview at sbcglobal.net> wrote: > >> I do not see Python listed there. I see Word Pad, Winamp, Paint, ... >> >> I'm at CP/All CP Items/Default prgrms/Set Defaults >> >> > My bad. It's Control Panel\Programs\Default Programs\Set Associations. > > (I could be wrong, but wasn't this all in one place in previous > versions...?) Anyway, scroll down to .py/.pyc/.pyo/.pyw, and I bet you'll > find it pointing to a no-longer-valid installation. > > py is listed as idle.pyw > This is NOT the default behavior (the default is python.exe) - I suspect you must have changed this for convenience when you first installed your old version of Python. > pyw as pythonw.exe (no console) > pyc/pyo as python.exe. > It's stupid and irritating, but Windows only gives you the executable name - not the path. Out of curiosity, does it show you the correct icons, or does it show you some generic Windows program icon, or something broken? In any case, click "Change program...", then "Browse" to the current proper locations, and click OK. This should (finally) fix your problem... The uninstall/install should have fixed this, but there are a lot of things that could interfere - perhaps you didn't run it as Administrator, perhaps it tripped over your previously-modified setting, perhaps the installer is buggy, perhaps gremlins are trying to mess with your head...? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Nov 15 04:09:42 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 14 Nov 2011 19:09:42 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> Message-ID: <4EC1D7F6.5000004@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Nov 15 04:13:24 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 14 Nov 2011 19:13:24 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> Message-ID: <4EC1D8D4.5090004@sbcglobal.net> Note that I did not install some libraries like numpy before uninstall/install. From stefan_ml at behnel.de Tue Nov 15 09:09:05 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 15 Nov 2011 09:09:05 +0100 Subject: [Tutor] Cython vs Python-C API In-Reply-To: References: Message-ID: Jaidev Deshpande, 14.11.2011 21:30: > I need to perform cubic spline interpolation over a range of points, and I > have written the code for the same in C and in Python. > > The interpolation is part of a bigger project. I want to front end for the > project to be Python. Ideally I want Python only to deal with data > visualization and i/o, and I'll leave the computationally expensive part of > the project to C extensions, which can be imported as functions into Python. > > To this end, the interpolation can be handled in two ways: > > 1. I can either compile the C code into a module using the Python-C/C++ > API, through which I can simple 'import' the required function. > 2. I can use the Python code and extend it using Cython. 3. use the existing C code and wrap it with Cython, likely using NumPy to pass the data, I guess. Why write yet another version of your code? I would strongly suggest not to put C-API calls into your C code. It will just make it less versatile (e.g. no longer usable outside of CPython) and generally harder to maintain. Stefan From cl2dlope at gmail.com Tue Nov 15 09:33:19 2011 From: cl2dlope at gmail.com (=?ISO-8859-1?Q?Dario_Lopez=2DK=E4sten?=) Date: Tue, 15 Nov 2011 09:33:19 +0100 Subject: [Tutor] Cython vs Python-C API In-Reply-To: References: Message-ID: Hi, just a thought - have you looked at NumPy/SciPy? Perhaps there already is an API in C that does what you need, sufficiently well/fast? http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html It is part of the NumPy/SciPy package(s). http://www.scipy.org/ /dario On Tue, Nov 15, 2011 at 9:09 AM, Stefan Behnel wrote: > cubic spline interpolation -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Nov 15 10:16:56 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Nov 2011 09:16:56 +0000 Subject: [Tutor] Handling a Unicode Return using Pyodbc In-Reply-To: References: Message-ID: <4EC22E08.3060808@timgolden.me.uk> On 14/11/2011 21:43, Tony Pelletier wrote: > Good Afternoon, > > I'm writing a program that is essentially connecting to MS SQL Server > and dumping all the contents of the tables to separate csv's. I'm > almost complete, but now I'm running into a Unicode issue and I'm not > sure how to resolve it. > > I have a ridiculous amount of tables but I managed to figure out it was > my Contact and a contact named Robert Bock. Here's what I caught. > > (127, None, u'Robert', None, u'B\xf6ck', 'uCompany Name', None, 1, 0, > 327, 0) > > The u'B\xf6ck' is actually B?ck. Notice the ? > > My problem is I'm not really sure how to handle it and whether or not > it's failing on the query or the insert to the csv. The Exception is: > > 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not > in range(128) Thanks for producing a thinned-down example. If I may take this at face value, I assume you're doing something like this: import csv # # Obviously from database, but for testing... # data = [ (127, None, u'Robert', None, u'B\xf6ck', 'uCompany Name', None, 1, 0, 327, 0), ] with open ("temp.csv", "wb") as f: writer = csv.writer (f) writer.writerows (data) which gives the error you describe. In short, the csv module in Python 2.x (not sure about 3.x) is unicode-unaware. You're passing it a unicode object and it's got no way of knowing what codec to use to encode it. So it doesn't try to guess: it just uses the default (ascii) and fails. And this is where it gets just a little bit messy. Depending on how much control you have over your data and how important the unicodeiness of it is, you need to encode things explicitly before they get to the csv module. One (brute force) option is this: def encoded (iterable_of_stuff): return tuple ( (i.encode ("utf8") if isinstance (i, unicode) else i) for i in iterable_of_stuff ) # # ... other code # writer.writerows ([encoded (row) for row in data]) This will encode anything unicode as utf8 and leave everything else untouched. It will slow down your csv generation, but that might well not matter (especially if you're basically IO-bound). TJG From stefan_ml at behnel.de Tue Nov 15 10:26:03 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 15 Nov 2011 10:26:03 +0100 Subject: [Tutor] Cython vs Python-C API In-Reply-To: References: Message-ID: Dario Lopez-K?sten, 15.11.2011 09:33: > On Tue, Nov 15, 2011 at 9:09 AM, Stefan Behnel wrote: > >> cubic spline interpolation No, I didn't. Stefan From cl2dlope at gmail.com Tue Nov 15 10:44:50 2011 From: cl2dlope at gmail.com (=?ISO-8859-1?Q?Dario_Lopez=2DK=E4sten?=) Date: Tue, 15 Nov 2011 10:44:50 +0100 Subject: [Tutor] Cython vs Python-C API In-Reply-To: References: Message-ID: On Tue, Nov 15, 2011 at 10:26 AM, Stefan Behnel wrote: > Dario Lopez-K?sten, 15.11.2011 09:33: > >> On Tue, Nov 15, 2011 at 9:09 AM, Stefan Behnel wrote: >> >> cubic spline interpolation >>> >> > No, I didn't. > > Stefan > > Oops, apologies. My reply was meant for Jaidev (OP), but I got the quoting wrong. /dario -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Nov 15 11:52:52 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 15 Nov 2011 02:52:52 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC1D7F6.5000004@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> Message-ID: On Mon, Nov 14, 2011 at 7:09 PM, Wayne Watson wrote: > > On 11/14/2011 6:17 PM, Marc Tompkins wrote: > > On Mon, Nov 14, 2011 at 4:55 PM, Wayne Watson < > sierra_mtnview at sbcglobal.net> wrote: > >> >> On 11/14/2011 4:04 PM, Marc Tompkins wrote: >> >> On Mon, Nov 14, 2011 at 4:00 PM, Wayne Watson < >> sierra_mtnview at sbcglobal.net> wrote: >> >>> I do not see Python listed there. I see Word Pad, Winamp, Paint, ... >>> >>> I'm at CP/All CP Items/Default prgrms/Set Defaults >>> >> >> My bad. It's Control Panel\Programs\Default Programs\Set Associations. >> >> (I could be wrong, but wasn't this all in one place in previous >> versions...?) Anyway, scroll down to .py/.pyc/.pyo/.pyw, and I bet you'll >> find it pointing to a no-longer-valid installation. >> >> py is listed as idle.pyw >> > This is NOT the default behavior (the default is python.exe) - I suspect > you must have changed this for convenience when you first installed your > old version of Python. > > >> pyw as pythonw.exe (no console) >> pyc/pyo as python.exe. >> > > Whoops, pyo/c are compiled python file. > "Compiled" doesn't mean "standalone". They still have to be opened with the Python interpreter (python.exe). > > It's stupid and irritating, but Windows only gives you the executable name > - not the path. Out of curiosity, does it show you the correct icons, or > does it show you some generic Windows program icon, or something broken? > > The icons look python-ish. I just used Win7 magnifier. Py looks like a > window with a red spot on the left and blue one on the right. pyc looks > like a blue and a yellow snake of some sort one top of one another. > It was just curiosity - having normal-looking icons is no guarantee of success... > > I tried adding python25 to the path as suggested by Wayne Werner. It had > no affect. > "Path" can refer to the location of a particular file, or to the "search path." The sense I intended means the actual location of that file; on my machine I have several versions of python.exe in different places (C:\cygwin\bin, C:\Program Files (x86)\Inkscape\python, C:\Python27) but the only one that matters for our current purpose is the one pointed to by the entry in Default Programs - and the path to that one is "C:\Python27\python.exe". Wayne was referring to the "search path" - also usually shortened to just "path". When you type something at the command prompt, Windows (or DOS, or Linux, or whatever) tries to match it against its list of built-in commands; if it's not a match, then it looks for matching executable files in each of the folders in the search path*, and runs the first match it finds; if it doesn't find a match, you get an error message. *In DOS and Windows, the current working directory is tried before the search path; in *nixes, you need to prepend "./" if you want to run a file in the current folder. If you can open a command prompt and go to C:\Temp (or some other arbitrary folder), type "python", and get the Python prompt, then your search path is working properly. The default program/file association in Windows short-circuits the search path; you specify exactly which executable, in what specific location, you want Windows to use to open certain types of files. That's why Wayne's advice had no effect. > > In any case, click "Change program...", then "Browse" to the current > proper locations, and click OK. This should (finally) fix your problem... > > Change Program? Do you mean on the installed program list? > I meant exactly what I typed. On the very screen we were just discussing - with the list of extensions (.py, .pyc, etc.) there is a button labeled "Change program..." Highlight the line for ".py". Click the button (yes, the one that says "Change program..."). You'll get another dialog box, and in that one there will be a button labeled "Browse". Click it. This will open up an "Open with..." dialog box, which will default to the Program Files folder. That's probably NOT where your Python install is located - by default, Python 2.5 would be installed in C:\Python25 - but it's up to you to figure out where you installed it. Once you've found it, highlight python.exe and click the "Open" button. Click "OK" to get back to the list of extensions. Repeat the process for ".pyc", ".pyo", and ".pyw". > > > The uninstall/install should have fixed this, but there are a lot of > things that could interfere - perhaps you didn't run it as Administrator, > perhaps it tripped over your previously-modified setting, perhaps the > installer is buggy, perhaps gremlins are trying to mess with your head...? > > Probably the latter. :-) Well, I may just punt and go to a 64-bit > install. Maybe up matters by going to 2.6. I think my 2.5.2 need may have > disappeared. > A 64-bit install will NOT make things any simpler; quite the reverse, in fact. . But upgrading to a newer version is definitely a good idea. Why not 2.7, which is current? -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Tue Nov 15 14:40:24 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Tue, 15 Nov 2011 05:40:24 -0800 (PST) Subject: [Tutor] list of objects? Message-ID: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> I am attempting to write a text based spider solitaire game.? I have? a pretty simple card class, and a deck class, which has a list of card objects, which are shuffled, then individual elements are put into self.dealt, which is a 'list of lists' when the cards are dealt. I am trying to control the visibility of the cards.? There is a small "for" loop in the "deal" method of the deck class, this is intended to toggle the visibility of four of the cards.? It does that just fine, but for some reason, it seems to be randomly toggling the visibility of other cards in the self.dealt list and I am thoroughly confused as to why that is.? Is it something to do with the way objects are referenced?? Is my list of card objects a bad way to approach this? -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: spider.py URL: From wprins at gmail.com Tue Nov 15 15:22:08 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 15 Nov 2011 14:22:08 +0000 Subject: [Tutor] list of objects? In-Reply-To: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> References: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> Message-ID: Hi Elwin, On 15 November 2011 13:40, Elwin Estle wrote: > I am attempting to write a text based spider solitaire game. I have a > pretty simple card class, and a deck class, which has a list of card > objects, which are shuffled, then individual elements are put into > self.dealt, which is a 'list of lists' when the cards are dealt. > > I am trying to control the visibility of the cards. There is a small > "for" loop in the "deal" method of the deck class, this is intended to > toggle the visibility of four of the cards. It does that just fine, but > for some reason, it seems to be randomly toggling the visibility of other > cards in the self.dealt list and I am thoroughly confused as to why that > is. Is it something to do with the way objects are referenced? Is my list > of card objects a bad way to approach this? > Off the top of my head, your problem is likely due to the line that reads: card_list = card_list * 8 What this will do is put the *same* set of card objects in the list to begin with, into a new card_list 8 times over. So the *same* Jack (for example) will appear 8 times in the resulting list. This list, card_list, is the list that implements then later on sliced in your deal method. So, when you then set the cards in the dealt hand to visible in your self.dealt[5] loop, because these same cards (card objects) also are part of the other piles/hands, they also appear visible elsewhere when the display method is called. To fix: Replace the line above (e.g. card_list = card_list * 8) with something that explicitly constructs new cards 8 times, thereby not holding mutliple refernces from seperate piles to the same card, then you should have no further issues. Maybe loop 8 times and make a function of te preceding code etc. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Tue Nov 15 15:28:30 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 15 Nov 2011 09:28:30 -0500 Subject: [Tutor] list of objects? In-Reply-To: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> References: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> Message-ID: On Tue, Nov 15, 2011 at 8:40 AM, Elwin Estle wrote: > I am attempting to write a text based spider solitaire game. I have a > pretty simple card class, and a deck class, which has a list of card > objects, which are shuffled, then individual elements are put into > self.dealt, which is a 'list of lists' when the cards are dealt. > > I am trying to control the visibility of the cards. There is a small > "for" loop in the "deal" method of the deck class, this is intended to > toggle the visibility of four of the cards. It does that just fine, but > for some reason, it seems to be randomly toggling the visibility of other > cards in the self.dealt list and I am thoroughly confused as to why that > is. Is it something to do with the way objects are referenced? Is my list > of card objects a bad way to approach this? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > A few thoughts first: class Card(object): def __init__(self): self.value = '' self.display = 'X' I would change the above to: class Card(object): def __init__(self, value): self.value = value self.display = 'X' (because you always have a card with a value) Which allows you to save a line here: for value in values: card = Card(value) card_list.append(card) like that Another idea would be to use "extend" here: values = [] for i in range(1, 11): values.append(str(i)) values.append('J') values.append('Q') values.append('K') So, you would do something like this instead: mylist = range(1, 11) mylist.extend(['J', 'Q', 'K']) for i in mylist: values.append(str(i)) What extend does is it extends one list with another list. Also, you can build the string conversion into the card class: Further saving you the above loop: class Card(object): def __init__(self, value): self.value = str(value) self.display = 'X' and then in the create_cards def: mylist = range(1, 11) mylist.extend(['J', 'Q', 'K']) # for i in mylist: # values.append(str(i)) for value in mylist: card = Card(value) card_list.append(card) (as an aside, I'm not sure why you do this: card_list = card_list * 8 if you need two decks, I think you should have a variable like 4*decks so you can shuffle the right amount of decks) I don't think you need to shuffle twice here (which in turn calls into question why you need a separate method, but maybe you were going to build on it - i do that all the time): def shuffle(self): random.shuffle(self.cards) #random.shuffle(self.cards) Now onto your question: You can see that there are four card values that are shown visible in any given run. There are always four values and they are always random from run to run. If you comment out this loop # for index, card in enumerate(self.dealt[5]): # print index, card # self.dealt[5][index].display = self.dealt[5][index].value You won't get that anymore. If you want to control whether to display any particular card or not, I would add a variable to the display_cards method: def display_cards(self, display = True): for row in self.dealt: for card in row: if display: print '%5s ' % card.display, else: print '%5s ' % card.value, print '' Or you can add another value to the card class, if you want to control the display of cards on a unique basis: class Card(object): def __init__(self, value): self.value = str(value) self.display = 'X' self.display_or_value = True then you can change your method above to be: def display_cards(self): for row in self.dealt: for card in row: if card.display_or_value: print '%5s ' % card.display, else: print '%5s ' % card.value, print '' Long story short, if I wanted to control the visibility of any card, I would do it within the Card class (since presumably that is an attribute of any given card - think about it in real life, a card can be up, or a card can be down, yet it still retains its other properties, like color, value, creases, etc) -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Tue Nov 15 15:34:35 2011 From: lina.lastname at gmail.com (lina) Date: Tue, 15 Nov 2011 22:34:35 +0800 Subject: [Tutor] optimize a plot In-Reply-To: References: Message-ID: Sorry for some not mature questions asked before, fixed now by: def PlotPathway(list1): for i in range(len(list1)): for j in range(len(list1[i])-1): if list1[i][j] != list1[i][j+1]: if ((int(list1[i][j])) < 43 and (int(list1[i][j-1])) < 43): g.add_edge(list1[i][j], list1[i][j+1]) for i in range(43,84): if g.has_node(i): g.delete_node(i) g.draw('graph4.png', prog="dot") just still don't get why the "if" does not work as expected. On Tue, Nov 15, 2011 at 10:19 PM, lina wrote: > > > I have a little issue regarding this one, the updated code: > > def PlotPathway(list1): > > ? ?for i in range(len(list1)): > ? ? ? ? ? ?for j in range(len(list1[i])-1): > ? ? ? ? ? ? ? ? ? ?if list1[i][j] != list1[i][j+1]: > ? ? ? ? ? ? ? ? ? ? ? ?if(int(list1[i][j])) < 43: > ? ? ? ? ? ? ? ? ? ? ? ? ? ?if(int(list1[i][j-1])) < 43: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?g.add_edge(list1[i][j], list1[i][j+1]) > ? ?g.draw('graph4.png', prog="dot") > > > I am confused, why this one still include the digital bigger than 43? > From mail at timgolden.me.uk Tue Nov 15 16:43:15 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 15 Nov 2011 15:43:15 +0000 Subject: [Tutor] Fwd: Re: [python-win32] Handling a Unicode Return using Pyodbc In-Reply-To: <4EC28744.70602@timgolden.me.uk> References: <4EC28744.70602@timgolden.me.uk> Message-ID: <4EC28893.5070308@timgolden.me.uk> [cc-ing back to the *correct* list in case other readers find it helpful...] On 15/11/2011 15:16, Tony Pelletier wrote: > Thanks, Tim! > > This is working brilliantly.... Slow, but working..:) I can go from > here and see if there's a way to speed it up. Well you've got a few options, although an amount depends on how much control you have over your data and how well you can predict. One option is to encode at SQL Server level: CAST your NVARCHAR to VARCHAR as part of the your query, eg: SELECT contacts.id, name = CAST ( contacts.name COLLATE SQL_Latin1_General_CP1_CS_AS AS VARCHAR (200) ) FROM contacts This will bring the text in as bytes encoded Latin1 which you can then write directly to the csv without the encoder. Without having tested this, I imagine it would be faster than encoding blindly at the Python end since it'll happen lower down the stack and you're pinpointing the data rather than running through all the columns on the offchance of finding one which is unicode. An alternative is to arrange something equivalent at the Python end -- ie have specific encoders for different rows which can target the specific columns which are known to be NVARCHAR. TJG _______________________________________________ python-win32 mailing list python-win32 at python.org http://mail.python.org/mailman/listinfo/python-win32 From sierra_mtnview at sbcglobal.net Tue Nov 15 16:47:37 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 15 Nov 2011 07:47:37 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> Message-ID: <4EC28999.1060108@sbcglobal.net> An HTML attachment was scrubbed... URL: From MPirritano at ochca.com Tue Nov 15 17:07:55 2011 From: MPirritano at ochca.com (Pirritano, Matthew) Date: Tue, 15 Nov 2011 08:07:55 -0800 Subject: [Tutor] run excel macro from python Message-ID: Pythonistas, I am running an excel macro from python with the following code: The problem I'm having is that when I try to run this function I get a dialog window that pops up titled: "Update Values: Personal.xls" When I try to cancel out of it I get directed to a type mismatch in the excel macro. The program is very long so I won't paste the whole thing here, just the call to the excel macro. What seems key is that the macro runs fine in excel. And I've run excel macros from python before. The only difference is that now the macro also calls some excel user defined functions. Since they live in Personal.xls I'm thinking that is the wrinkle here. All of my searching has led me nowhere. Has no one ever had this issue? You'll note the excessive closing language in the function. I thought that maybe what was happening is that more than one instance of excel was open and that was causing a problem with accessing personal.xls, as will happen if you try to manually open more than one instance of excel in windows. def runExcelMacro(): excel = win32.Dispatch("Excel.Application") excel.Visible = 0 fTest = excel.Workbooks.Add("D:\\Data\\Excel\\Blank_Summary_Report_Template_Macr o_20111114.xls") macName = "macroAllFiles" macName = fTest.Name + '!' + macName print macName excel.Run(macName) excel.DisplayAlerts = 0 fTest.Close(1) excel.Quit() del excel Any ideas!? Thanks Matt Matthew Pirritano, Ph.D. Research Analyst IV Medical Services Initiative (MSI) Orange County Health Care Agency (714) 568-5648 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 15 18:51:03 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Nov 2011 17:51:03 +0000 Subject: [Tutor] optimize a plot In-Reply-To: References: Message-ID: On 15/11/11 14:34, lina wrote: > Sorry for some not mature questions asked before, fixed now by: > > def PlotPathway(list1): > > for i in range(len(list1)): > for j in range(len(list1[i])-1): > if list1[i][j] != list1[i][j+1]: > if ((int(list1[i][j]))< 43 and (int(list1[i][j-1]))< 43): > g.add_edge(list1[i][j], list1[i][j+1]) > for i in range(43,84): > if g.has_node(i): > g.delete_node(i) > g.draw('graph4.png', prog="dot") > > > just still don't get why the "if" does not work as expected. Sorry, I haven't been following you earlier thread. Which 'if'? There are 3 to choose from. And how did you expect it to behave, and what is it doing that you didn't expect? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 15 18:54:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 15 Nov 2011 17:54:12 +0000 Subject: [Tutor] run excel macro from python In-Reply-To: References: Message-ID: On 15/11/11 16:07, Pirritano, Matthew wrote: > Pythonistas, > > I am running an excel macro from python with the following code: There are some Excel/Python users here so you might get a good reply, but you might also like to try a Python Windows mailing list/forum, where are more likely to be experts available. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Tue Nov 15 19:11:09 2011 From: d at davea.name (Dave Angel) Date: Tue, 15 Nov 2011 13:11:09 -0500 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC28999.1060108@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> Message-ID: <4EC2AB3D.8000309@davea.name> On 11/15/2011 10:47 AM, Wayne Watson wrote: > > > > Highlight the line for ".py". Click the button (yes, the one that says "Change > > program..."). You'll > Yes, did that. > > get another dialog box, and in that one there will be a button labeled > > "Browse". Click it. This will open up an "Open with..." dialog box, which will > > default to the Program Files folder. That's > Yes, did that. > > probably NOT where your Python install is located - by default, Python 2.5 > > would be installed in C:\Python25 - but it's up to you to figure out where you > > installed it. Once you've found it, > For py, I found \Python25\Lib\idlelib\idle.pyw. > Does no good to specify yet another .py file as the executable. You must specify a .EXE file (or .BAT, or .CMD, or very rarely, a .COM file). Find your python.exe and click on that, not on idle anything. After this works, you can worry about running IDLE.bat. But get something working first. -- DaveA From o0MB0o at hotmail.se Tue Nov 15 21:00:06 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 15 Nov 2011 21:00:06 +0100 Subject: [Tutor] Clock in tkinter? Message-ID: Hi! I am new to programming and I hop this question isn?t stupid. I am making a small GUI program. It is supposed to have a button and a clock in it that displays the same time as it is according to the computer. So as far as I am concerned both the clock and the are supposed to be widgets? So how do I add this clock as a widget placed next to the button? Here is the code I have written so far, that only displays a GUI window, and a button: from tkinter import * import time class Window(Frame): def __init__(self,master): super(Window,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): self.test_button=Button(self, text="Hi") self.test_button.grid(row=0,column=0) root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() Thank you for your help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Nov 15 21:11:21 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 15 Nov 2011 12:11:21 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> Message-ID: <4EC2C769.4080208@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Nov 15 21:19:34 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 15 Nov 2011 12:19:34 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC2AB3D.8000309@davea.name> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> <4EC2AB3D.8000309@davea.name> Message-ID: <4EC2C956.5000809@sbcglobal.net> >> For py, I found \Python25\Lib\idlelib\idle.pyw. >> > Does no good to specify yet another .py file as the executable. You > must specify a .EXE file (or .BAT, or .CMD, or very rarely, a .COM file). In py land I only have py, pyc, pyw, and pyo. I've now done py and pyc as default. Still have the same Win32 app problem. What am I supposed to do with python.exe? It will open a DOS window with a command >>> prompt. I can use the prompt to do arithmetic. Tried idle.bat moments ago. Still get Win32 app problem msg on py files. > > Find your python.exe and click on that, not on idle anything. After > this works, you can worry about running IDLE.bat. But get something > working first. > > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "My suspicion is that the universe is not only queerer than we suppose, but queerer than we can suppose." -- Physiologist and Geneticist J.B.S. Haldane 1860-1936 (Maybe not, Dr. Haldane. We have an amazing imagination) Web Page: From waynejwerner at gmail.com Tue Nov 15 22:14:11 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 15 Nov 2011 15:14:11 -0600 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: On Tue, Nov 15, 2011 at 2:00 PM, Mic wrote: > Hi! > I am new to programming and I hop this question isn?t stupid. > Welcome! > I am making a small GUI program. It is supposed to have a button and a > clock in it that displays the same time as it is according to the computer. > So as far as I am concerned both the clock and the are supposed to be > widgets? > Is this a homework assignment, or just something that you're doing for fun? It seems homework-ish. We don't mind pointing you in the right direction on homework assignments, but we definitely won't do it for you. > So how do I add this clock as a widget placed next to the button? > Tkinter doesn't have a native clock widget, so if you want to make a clock you need to roll your own. > Here is the code I have written so far, that only displays a GUI > window, and a button: > > from tkinter import * > import time > > class Window(Frame): > def __init__(self,master): > super(Window,self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > self.test_button=Button(self, text="Hi") > self.test_button.grid(row=0,column=0) > > root=Tk() > root.title("Test") > root.geometry("200x200") > app=Window(root) > root.mainloop() > Giving us code (especially such a small amount) is exactly the right thing to do when you ask a question - it shows that you've tried something, and if it's broken it usually shows why it's broken. You can add text to the Label widget - and you can change the text on that widget. You're already importing the time module - for more information about what it contains, you can run the interactive interpreter and do this: >>> import time >>> help(time) Or you can look online for the commands that might help you. If you get stuck, let us know what you're doing and where you're stuck at. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Nov 15 23:27:57 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 15 Nov 2011 14:27:57 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC2C956.5000809@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> <4EC2AB3D.8000309@davea.name> <4EC2C956.5000809@sbcglobal.net> Message-ID: On Tue, Nov 15, 2011 at 12:19 PM, Wayne Watson wrote: > > For py, I found \Python25\Lib\idlelib\idle.**pyw. >>> >>> Does no good to specify yet another .py file as the executable. You >> must specify a .EXE file (or .BAT, or .CMD, or very rarely, a .COM file). >> > In py land I only have py, pyc, pyw, and pyo. I've now done py and pyc as > default. Still have the same Win32 app problem. > What am I supposed to do with python.exe? It will open a DOS window with a > command >>> prompt. I can use the prompt to do arithmetic. > > Tried idle.bat moments ago. Still get Win32 app problem msg on py files. I'm going to try one last time before I give up: - Go to Control Panel\Programs\Default Programs\Set Associations. - Highlight the line for ".py" - Click "Change program..." - In the "Open with" dialog, click the "Browse..." button. - In the "Open with..." dialog, navigate to C:\Python25\Lib\idlelib - Highlight "idle.bat" - Click the "Open" button. - You'll be back in the "Open with" dialog. Click OK. If you - yet again - do something other than what I've just described, and then reply telling me that it didn't work, I will add you to my spam filter. You asked about the %1 %2 %3 etc. in idle.bat. Yes, those are arguments. >From now on, when you double-click on a .py file, - Windows will run idle.bat and pass it the name of your .py file as its first (and only) argument. - Idle.bat will then run pythonw.exe with "idle.pyw" as its first argument, and the name of your .py file as its second argument. - Python will then run IDLE with your .py file as its first argument. I'm going to underscore this one more time, because you need to understand it: Python is an interpreted/scripting language, and (except for specialty extensions like Pyrex) it does NOT compile into standalone executables.* Windows cannot run Python code directly - Windows doesn't know what Python is. When you double-click on a Python file and expect Windows to do something with it, you have to tell Windows to open it with a program that Windows actually CAN run directly - in this case, idle.bat. What you've been telling Windows to do, by associating .py files with idle.pyw, is to open one file it doesn't recognize by using another file it doesn't recognize. Don't do that. * Installation bundlers like Py2EXE or GUI2EXE simply create a minimal bundle of the Python interpreter and put it in (essentially) a self-extracting Zip file. Yes, the result is an executable - usually a gigantic one - but it's not "compiling" in the usually-understood meaning of the word. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Nov 16 00:55:29 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 15 Nov 2011 15:55:29 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> <4EC2AB3D.8000309@davea.name> <4EC2C956.5000809@sbcglobal.net> Message-ID: <4EC2FBF1.6080606@sbcglobal.net> ... With fingers crossed ... > > I'm going to try one last time before I give up: > > - Go to Control Panel\Programs\Default Programs\Set Associations. DONE > - Highlight the line for ".py" DONE > - Click "Change program..." DONE > - In the "Open with" dialog, click the "Browse..." button. DONE > - In the "Open with..." dialog, navigate to C:\Python25\Lib\idlelib DONE > - Highlight "idle.bat" DONE > - Click the "Open" button. DONE > - You'll be back in the "Open with" dialog. DONE. Click OK. DONE > > If you - yet again - do something other than what I've just described, > and then reply telling me that it didn't work, I will add you to my > spam filter. Sigh. The .py entry shows idle.bat OK, take a deep breath. With a right-click on a py file "Open with", idle.bat shows as the first entry, then idle.pyw, Notepad, and finally python.exe. If I select either idle.bat or idle.pyw, I get a cmd window that show in the title: c:\windows\system32\cmd.exe and another "normal" window that says, "Windows cannot find idle.pyw. Make sure you typed the name correctly, then try again." Selecting idle.pyw, gives me a window that tells me the app I've tried to open in IDLE is not a valid Win32 app. I have no idea if the Dave Angel intervention had anything to do with this. I think we've exhausted ourselves. Time to ditch 2.5.2 and find a better version of Python to work on. > > You asked about the %1 %2 %3 etc. in idle.bat. Yes, those are > arguments. From now on, when you double-click on a .py file, > - Windows will run idle.bat and pass it the name of your .py file as > its first (and only) argument. > - Idle.bat will then run pythonw.exe with "idle.pyw" as its first > argument, and the name of your .py file as its second argument. > - Python will then run IDLE with your .py file as its first argument. > > I'm going to underscore this one more time, because you need to > understand it: Python is an interpreted/scripting language, Clearly that is so. > and (except for specialty extensions like Pyrex) it does NOT compile > into standalone executables.* Again that is so. > Windows cannot run Python code directly - Windows doesn't know what > Python is. When you double-click on a Python file and expect Windows > to do something with it, you have to tell Windows to open it with a > program that Windows actually Of course. > CAN run directly - in this case, idle.bat. What you've been telling > Windows to do, by associating .py files with idle.pyw, is to open one > file it doesn't recognize by using another file it doesn't recognize. > Don't do that. I started this very simply. I just installed 2.5.2, as we know both know, and made no changes to any associations. The install made them, not me. They only came up in this thread earlier. I may have made a mistake in doing so, but I have no idea where. Users should not have to go through the association process unless asked to do so. There was never a message to ask that. I've seen it on programs like Winamp, WinMediaPlayer, RealPlayer, but not here. > > > * Installation bundlers like Py2EXE or GUI2EXE simply create a minimal > bundle of the Python interpreter and put it in (essentially) a > self-extracting Zip file. Yes, the result is an executable - usually > a gigantic one - but it's not "compiling" in the usually-understood > meaning of the word. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "My suspicion is that the universe is not only queerer than we suppose, but queerer than we can suppose." -- Physiologist and Geneticist J.B.S. Haldane 1860-1936 (Maybe not, Dr. Haldane. We have an amazing imagination) Web Page: From marc.tompkins at gmail.com Wed Nov 16 01:09:13 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 15 Nov 2011 16:09:13 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC2FBF1.6080606@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> <4EC2AB3D.8000309@davea.name> <4EC2C956.5000809@sbcglobal.net> <4EC2FBF1.6080606@sbcglobal.net> Message-ID: On Tue, Nov 15, 2011 at 3:55 PM, Wayne Watson wrote: > ... > > With fingers crossed ... > >> >> I'm going to try one last time before I give up: >> >> - Go to Control Panel\Programs\Default Programs\Set Associations. DONE >> - Highlight the line for ".py" DONE >> - Click "Change program..." DONE >> - In the "Open with" dialog, click the "Browse..." button. DONE >> - In the "Open with..." dialog, navigate to C:\Python25\Lib\idlelib DONE >> - Highlight "idle.bat" DONE >> - Click the "Open" button. DONE >> - You'll be back in the "Open with" dialog. DONE. Click OK. DONE >> >> >> If you - yet again - do something other than what I've just described, >> and then reply telling me that it didn't work, I will add you to my spam >> filter. >> > Sigh. > The .py entry shows idle.bat > OK, take a deep breath. With a right-click on a py file "Open with", > idle.bat shows as the first entry, then idle.pyw, Notepad, and finally > python.exe. If I select either idle.bat or idle.pyw, I get a cmd window > that show in the title: c:\windows\system32\cmd.exe and another "normal" > window that says, "Windows cannot find idle.pyw. Make sure you typed the > name correctly, then try again." Selecting idle.pyw, gives me a window that > tells me the app I've tried to open in IDLE is not a valid Win32 app. > > I have no idea if the Dave Angel intervention had anything to do with this. > > I think we've exhausted ourselves. Time to ditch 2.5.2 and find a better > version of Python to work on. > > > > >> You asked about the %1 %2 %3 etc. in idle.bat. Yes, those are arguments. >> From now on, when you double-click on a .py file, >> - Windows will run idle.bat and pass it the name of your .py file as its >> first (and only) argument. >> - Idle.bat will then run pythonw.exe with "idle.pyw" as its first >> argument, and the name of your .py file as its second argument. >> - Python will then run IDLE with your .py file as its first argument. >> >> I'm going to underscore this one more time, because you need to >> understand it: Python is an interpreted/scripting language, >> > Clearly that is so. > > and (except for specialty extensions like Pyrex) it does NOT compile into >> standalone executables.* >> > Again that is so. > > Windows cannot run Python code directly - Windows doesn't know what >> Python is. When you double-click on a Python file and expect Windows to do >> something with it, you have to tell Windows to open it with a program that >> Windows actually >> > Of course. > > CAN run directly - in this case, idle.bat. What you've been telling >> Windows to do, by associating .py files with idle.pyw, is to open one file >> it doesn't recognize by using another file it doesn't recognize. Don't do >> that. >> > I started this very simply. I just installed 2.5.2, as we know both know, > and made no changes to any associations. The install made them, not me. > They only came up in this thread earlier. I may have made a mistake in > doing so, but I have no idea where. Users should not have to go through the > association process unless asked to do so. There was never a message to > ask that. I've seen it on programs like Winamp, WinMediaPlayer, > RealPlayer, but not here. > > That's not entirely true, actually. See, the DEFAULT association for Python files, as set by the installation, is just to run the damn things using python.exe or pythonw.exe - NOT to edit them in IDLE. By default, if you want to edit the script you right-click and select "Open in IDLE" (or you use some other editor/IDE), but if you double-click it the script just runs. What's messed with all of that is your insistence that you want IDLE to be the default action. And there's nothing wrong with that either - but you need to recognize that it is NOT the default setting, and plan accordingly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Nov 16 01:33:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Nov 2011 00:33:40 +0000 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: <4EC2FBF1.6080606@sbcglobal.net> References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> <4EC2AB3D.8000309@davea.name> <4EC2C956.5000809@sbcglobal.net> <4EC2FBF1.6080606@sbcglobal.net> Message-ID: On 15/11/11 23:55, Wayne Watson wrote: > I think we've exhausted ourselves. Time to ditch 2.5.2 and find a better > version of Python to work on. There is nothiong wrong with Python 2.5.2, I used it for several years on Windows. But the default installation should not be setting up idle as the interpreter for .py files. However it would make more sense in 2011 to install a more recent version unless you specifically need 2.5 to work sith some old library. Otherwise 2.6 or 2.7 would be more senmsioble. Also if you are on Windows I strongly recommend the ActiveState version. Open Source purists may object but its integration with Windows is better and Pythonwin is a much better IDE than IDLE in almost every respect. > I started this very simply. I just installed 2.5.2, as we know both > know, and made no changes to any associations. The install made them, > not me. It sounds like the install maybe got messed up somehow, I've experienced that with python before. It's possible that simply uninstalling and reinstalling a fresh version will work. But as mentioned I'd recommend getting the ActiveState distribution. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Wed Nov 16 02:59:30 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 15 Nov 2011 17:59:30 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> <4EC2AB3D.8000309@davea.name> <4EC2C956.5000809@sbcglobal.net> <4EC2FBF1.6080606@sbcglobal.net> Message-ID: <4EC31902.4060707@sbcglobal.net> It was the default action before with the right-click. I don't care about double-click. I just looked on my XP, and that's the way it's done on 2.5.2 there. I have no idea how this got onto double-click. Let's not worry about it in any case. We can quibble some more, but I'm done with this effort. See my next post to Alan in a minute or two. Nevertheless, thanks for the help. > > That's not entirely true, actually. See, the DEFAULT association for > Python files, as set by the installation, is just to run the damn > things using python.exe or pythonw.exe - NOT to edit them in IDLE. By > default, if you want to edit the script you right-click and select > "Open in IDLE" (or you use some other editor/IDE), but if you > double-click it the script just runs. What's messed with all of that > is your insistence that you want IDLE to be the default action. And > there's nothing wrong with that either - but you need to recognize > that it is NOT the default setting, and plan accordingly. > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "My suspicion is that the universe is not only queerer than we suppose, but queerer than we can suppose." -- Physiologist and Geneticist J.B.S. Haldane 1860-1936 (Maybe not, Dr. Haldane. We have an amazing imagination) Web Page: From sierra_mtnview at sbcglobal.net Wed Nov 16 03:01:09 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 15 Nov 2011 18:01:09 -0800 Subject: [Tutor] Trouble installing Python on Win7 (not a valid Win 32 app) In-Reply-To: References: <4EC19146.7080900@sbcglobal.net> <4EC1AB8B.8080602@sbcglobal.net> <4EC1B87E.2020103@sbcglobal.net> <4EC1D7F6.5000004@sbcglobal.net> <4EC28999.1060108@sbcglobal.net> <4EC2AB3D.8000309@davea.name> <4EC2C956.5000809@sbcglobal.net> <4EC2FBF1.6080606@sbcglobal.net> Message-ID: <4EC31965.9020605@sbcglobal.net> Thanks. I took a look at active state once. Too much of a learning curve for me at the time. I'm not a frequent user of Python. I was on a small project that depended on 2.5.2. There were some issues with numpy, and other libs that needed to stay put. Project is pretty well gone. If not, I'm going to declare it dead. I think I'm done here with 2.5.2. I think it's time to move to 2.6 or 2.7. Now! On 11/15/2011 4:33 PM, Alan Gauld wrote: > On 15/11/11 23:55, Wayne Watson wrote: > >> I think we've exhausted ourselves. Time to ditch 2.5.2 and find a better >> version of Python to work on. > > There is nothiong wrong with Python 2.5.2, I used it for several years > on Windows. But the default installation should not be setting up idle > as the interpreter for .py files. > > However it would make more sense in 2011 to install a more recent > version unless you specifically need 2.5 to work sith some old > library. Otherwise 2.6 or 2.7 would be more senmsioble. > > Also if you are on Windows I strongly recommend the ActiveState version. > Open Source purists may object but its integration with Windows is > better and Pythonwin is a much better IDE than IDLE in almost every > respect. > >> I started this very simply. I just installed 2.5.2, as we know both >> know, and made no changes to any associations. The install made them, >> not me. > > It sounds like the install maybe got messed up somehow, I've > experienced that with python before. It's possible that simply > uninstalling and reinstalling a fresh version will work. > But as mentioned I'd recommend getting the ActiveState > distribution. > > HTH, -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "My suspicion is that the universe is not only queerer than we suppose, but queerer than we can suppose." -- Physiologist and Geneticist J.B.S. Haldane 1860-1936 (Maybe not, Dr. Haldane. We have an amazing imagination) Web Page: From bgailer at gmail.com Wed Nov 16 03:18:46 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 15 Nov 2011 21:18:46 -0500 Subject: [Tutor] list of objects? In-Reply-To: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> References: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> Message-ID: <4EC31D86.2050503@gmail.com> On 11/15/2011 8:40 AM, Elwin Estle wrote: > I am attempting to write a text based spider solitaire game. What are the rules of your version of Spider? The only spiders I know have 10 dealt piles and 1 draw pile. I think you have greatly complicated things by using classes. Consider: deck = random.shuffle(range(13)*8) # list of 108 card "indexes" in random order. values = "A23456789JQK" # display values corresponding to indexes piles = [deck[x:x+10] for x in range(0,108,10)] Anytime you want to display the value of a card use values[cardIndex] for example to display the last card in each pile: for pile in piles: print values[pile[-1]], What will your actual display look llike? Will you completely reprint it after each move, or alter it in place? How will you get the moves from the player? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Wed Nov 16 05:17:01 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Wed, 16 Nov 2011 09:47:01 +0530 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: > On Wed, Nov 16, 2011 at 1:30 AM, Mic wrote: > Hi! > I am new to programming WELCOME! >and I hop this question isn?t stupid. A teacher of mine said, "The only stupid question is the one you thought of asking but did not ask!" Happy learning Asokan Pichai -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Wed Nov 16 07:19:06 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 16 Nov 2011 14:19:06 +0800 Subject: [Tutor] optimize a plot In-Reply-To: References: Message-ID: >>> g.nodes() [u'1', u'2', u'34', u'59', u'57'] >>> for node in g.nodes(): print node Traceback (most recent call last): File "", line 2, in print node File "/usr/lib/python2.6/idlelib/rpc.py", line 597, in __call__ value = self.sockio.remotecall(self.oid, self.name, args, kwargs) File "/usr/lib/python2.6/idlelib/rpc.py", line 210, in remotecall seq = self.asynccall(oid, methodname, args, kwargs) File "/usr/lib/python2.6/idlelib/rpc.py", line 225, in asynccall self.putmessage((seq, request)) File "/usr/lib/python2.6/idlelib/rpc.py", line 324, in putmessage s = pickle.dumps(message) File "/usr/lib/python2.6/copy_reg.py", line 70, in _reduce_ex raise TypeError, "can't pickle %s objects" % base.__name__ TypeError: can't pickle PySwigObject objects >>> for node in g.nodes(): print type(node) and this problem is weird, when I run python script.py it did not show warning. well, on the same version idle, it showed above error message. Thanks From lina.lastname at gmail.com Wed Nov 16 08:52:30 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 16 Nov 2011 15:52:30 +0800 Subject: [Tutor] IndentationError: Message-ID: Why it keeps on complaining: $ python plot-pathway.py File "plot-pathway.py", line 35 if list1[i][j]<=42: ^ IndentationError: unindent does not match any outer indentation level def PlotPathway(list1): for i in range(len(list1)): for j in range(len(list1[i])-1): if list1[i][j] != list1[i][j+1]: g.add_edge(list1[i][j], list1[i][j+1]) if list1[i][j]<=42: g.node_attr.update(color='deepskyblue',style='filled') if list1[i][j] > 42: g.node_attr.update(color='green',style='filled') I checked the indentation very carefully, seems no problems. really no clue, Thanks with best regards, From lina.lastname at gmail.com Wed Nov 16 09:03:00 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 16 Nov 2011 16:03:00 +0800 Subject: [Tutor] optimize a plot In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 1:51 AM, Alan Gauld wrote: > On 15/11/11 14:34, lina wrote: >> >> Sorry for some not mature questions asked before, fixed now by: >> >> def PlotPathway(list1): >> >> ? ? for i in range(len(list1)): >> ? ? ? ? ? ?for j in range(len(list1[i])-1): >> ? ? ? ? ? ? ? ? ? ?if list1[i][j] != list1[i][j+1]: >> ? ? ? ? ? ? ? ? ? ? ? ?if ((int(list1[i][j]))< ?43 and >> (int(list1[i][j-1]))< ?43): >> ? ? ? ? ? ? ? ? ? ? ? ? ? ?g.add_edge(list1[i][j], list1[i][j+1]) >> ? ? for i in range(43,84): >> ? ? ? ? if g.has_node(i): >> ? ? ? ? ? ? ? ? ? ?g.delete_node(i) >> ? ? g.draw('graph4.png', prog="dot") >> >> >> just still don't get why the "if" does not work as expected. > > > Sorry, I haven't been following you earlier thread. My mistake, I attached a figure in earlier posting, but the message was held for approval due to it's too big. I just noticed those three notifications, so I canceled posting, not sure waiting for approval will get approved or not. > Which 'if'? There are 3 to choose from. > And how did you expect it to behave, and what is it doing that you didn't > expect? During those process, I met lots of problems, some are fixed, and some are forgot or switch to another problem. One thing is that I did not know how to get node value, and for the node value to change the attirbute of this certain node. This way is wrong: def PlotPathway(list1): for i in range(len(list1)): for j in range(len(list1[i])-1): if list1[i][j] != list1[i][j+1]: g.add_edge(list1[i][j], list1[i][j+1]) if list1[i][j]<=42: g.node_attr.update(color='deepskyblue',style='filled') if list1[i][j] > 42: g.node_attr.update(color='green',style='filled') it will keep on updating and mess things up, but this way can get the value. Below is a better way: def colorNodes(listofnodes): node_list=[] node_list_A=[] node_list_B=[] for node in g: node_list.append(node) if node.value < 42: ### I don't know how to get the value of the node. g.node_attr.update(color='deepskyblue',style='filled') else: g.node_attr.update(color='green',style='filled') > > -- > Alan G > 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 cl2dlope at gmail.com Wed Nov 16 09:06:36 2011 From: cl2dlope at gmail.com (=?ISO-8859-1?Q?Dario_Lopez=2DK=E4sten?=) Date: Wed, 16 Nov 2011 09:06:36 +0100 Subject: [Tutor] IndentationError: In-Reply-To: References: Message-ID: The indentation is indeed off: Original code: def PlotPathway(list1): for i in range(len(list1)): for j in range(len(list1[i])-1): if list1[i][j] != list1[i][j+1]: g.add_edge(list1[i][j], list1[i][j+1]) if list1[i][j]<=42: g.node_attr.update(color='deepskyblue',style='filled') if list1[i][j] > 42: g.node_attr.update(color='green',style='filled') What I think you meant: def PlotPathway(list1): for i in range(len(list1)): for j in range(len(list1[i])-1): if list1[i][j] != list1[i][j+1]: g.add_edge(list1[i][j], list1[i][j+1]) if list1[i][j]<=42: g.node_attr.update(color='deepskyblue',style='filled') if list1[i][j] > 42: g.node_attr.update(color='green',style='filled') Notice that I *consistently* use 4 spaces, and *only spaces, not tabs,* for each indentation level. In your code (assuming the copy paste I did was correct) I could see a mixture in the number of spaces for each indentation level. The error was the python interpreted the second and third if statements as being not properly indented, becuase of the lack of consitency: 1. they did not align with the first if statement in side the for loop 2. the did not align with the for-loop either, so there could not be intrepreted as being on the same level as the for loop. Hope this makes sense and helps! Best regards, /dario On Wed, Nov 16, 2011 at 8:52 AM, lina wrote: > Why it keeps on complaining: > > $ python plot-pathway.py > File "plot-pathway.py", line 35 > if list1[i][j]<=42: > ^ > IndentationError: unindent does not match any outer indentation level > > > def PlotPathway(list1): > for i in range(len(list1)): > for j in range(len(list1[i])-1): > if list1[i][j] != list1[i][j+1]: > g.add_edge(list1[i][j], list1[i][j+1]) > > if list1[i][j]<=42: > g.node_attr.update(color='deepskyblue',style='filled') > if list1[i][j] > 42: > g.node_attr.update(color='green',style='filled') > > I checked the indentation very carefully, seems no problems. > > really no clue, > > Thanks with best regards, > _______________________________________________ > 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 lina.lastname at gmail.com Wed Nov 16 09:21:05 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 16 Nov 2011 16:21:05 +0800 Subject: [Tutor] IndentationError: In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 4:06 PM, Dario Lopez-K?sten wrote: > The indentation is indeed off: > Original code: > def PlotPathway(list1): > ? ?for i in range(len(list1)): > ? ? ? ?for j in range(len(list1[i])-1): > ? ? ? ? ? ? ? ? ? ?if list1[i][j] != list1[i][j+1]: > ? ? ? ? ? ? ? ? ? ? ? ?g.add_edge(list1[i][j], list1[i][j+1]) > > ? ? ? ? ? ? ? ?if list1[i][j]<=42: > ? ? ? ? ? ? ? ? ? ?g.node_attr.update(color='deepskyblue',style='filled') > ? ? ? ? ? ? ? ?if list1[i][j] > 42: > ? ? ? ? ? ? ? ? ? ?g.node_attr.update(color='green',style='filled') > > What I think you meant: > def PlotPathway(list1): > ? ? for i in range(len(list1)): > ? ? ? ? for j in range(len(list1[i])-1): > ? ? ? ? ? ? if list1[i][j] != list1[i][j+1]: > ? ? ? ? ? ? ? ? g.add_edge(list1[i][j], list1[i][j+1]) > > ? ? ? ? ? ? if list1[i][j]<=42: > ? ? ? ? ? ? ? ? g.node_attr.update(color='deepskyblue',style='filled') > ? ? ? ? ? ? if list1[i][j] > 42: > ? ? ? ? ? ? ? ? g.node_attr.update(color='green',style='filled') > > > Notice that I consistently use 4 spaces, and only spaces, not tabs, for each > indentation level. In your code (assuming the copy paste I did was correct) > I could see a mixture in the number of spaces for each indentation level. > The error was the python interpreted the second and third if statements as > being not properly indented, becuase of the lack of consitency: > > they did not align with the first if statement in side the for loop > the did not align with the for-loop either, so there could not be > intrepreted as being on the same level as the for loop. Yes, it's lack of consistency, sorry, I thought I posted something like: if list1[i][j] != list1[i][j+1]: g.add_edge(list1[i][j], list1[i][j+1]) if list1[i][j]<=42: g.node_attr.update(color='deepskyblue',style='filled') if list1[i][j] > 42: g.node_attr.update(color='green',style='filled') The second and third if are inside the first if, it still complaining. I set the gedit, use space not tab, Now I even typed space by space, avoid using tab, it still has the same problem. How can I fixed it? I put the two files in below links: https://docs.google.com/open?id=0B93SVRfpVVg3NzlkMzVmOWYtNDk4MS00Yzk1LWEwMWQtYzIzMWU0Y2M2NmUz https://docs.google.com/open?id=0B93SVRfpVVg3ZDhiZjM1ZGItZDU0Ny00MDhhLThjZDQtYmRjMWJkMmVkNTk5 > > Hope this makes sense and helps! > Best regards, > /dario > On Wed, Nov 16, 2011 at 8:52 AM, lina wrote: >> >> Why it keeps on complaining: >> >> $ python plot-pathway.py >> ?File "plot-pathway.py", line 35 >> ? ?if list1[i][j]<=42: >> ? ? ? ? ? ? ? ? ? ? ?^ >> IndentationError: unindent does not match any outer indentation level >> >> >> def PlotPathway(list1): >> ? ?for i in range(len(list1)): >> ? ? ? ?for j in range(len(list1[i])-1): >> ? ? ? ? ? ? ? ? ? ?if list1[i][j] != list1[i][j+1]: >> ? ? ? ? ? ? ? ? ? ? ? ?g.add_edge(list1[i][j], list1[i][j+1]) >> >> ? ? ? ? ? ? ? ?if list1[i][j]<=42: >> ? ? ? ? ? ? ? ? ? ?g.node_attr.update(color='deepskyblue',style='filled') >> ? ? ? ? ? ? ? ?if list1[i][j] > 42: >> ? ? ? ? ? ? ? ? ? ?g.node_attr.update(color='green',style='filled') >> >> I checked the indentation very carefully, seems no problems. >> >> really no clue, >> >> Thanks with best regards, Thanks again, >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > > > From andreengels at gmail.com Wed Nov 16 09:31:26 2011 From: andreengels at gmail.com (Andre Engels) Date: Wed, 16 Nov 2011 09:31:26 +0100 Subject: [Tutor] IndentationError: In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 9:21 AM, lina wrote: > it still complaining. I set the gedit, use space not tab, > Now I even typed space by space, avoid using tab, it still has the same > problem. > > How can I fixed it? > The line if list1[i][j] != list1[i][j+1]: still contains a tab, thus it is now indented negative 3 spaces plus a tab plus 3 spaces compared to the encompassing loop, which is problematic both because there is a negative number in there and because it differs from the rest of the lines in the same loop (6 spaces) -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From Dhanashri.Shirkhedkar at Honeywell.com Mon Nov 14 06:34:18 2011 From: Dhanashri.Shirkhedkar at Honeywell.com (Shirkhedkar, Dhanashri) Date: Mon, 14 Nov 2011 11:04:18 +0530 Subject: [Tutor] binary file query Message-ID: If we are opening a binary file in python then do we have to use "Import struct" and do "struct.unpack" to work on the data from that binary file? Will we be able to process the file as text file without using struct? Thanks, Dhanashri -------------- next part -------------- An HTML attachment was scrubbed... URL: From gags786 at yahoo.com Thu Nov 10 18:10:23 2011 From: gags786 at yahoo.com (Amir) Date: Thu, 10 Nov 2011 17:10:23 +0000 Subject: [Tutor] Bulk Import Script Help Please References: <65EE14DAB3AECD4A826C6E29A843A1940B0E6DA2@EXCH-MB02.cc.rhul.local> Message-ID: <639DF706-C806-4C3B-96DE-A920B71EE5D3@yahoo.com> > Hi, > > > > I am new to python, and I need to bulk import a csv data dump into our content management system, Equella. > > > > I need to bulk import the CSV file dump into Equella to create a Taxonomy using a Python script. > > > > I would really appreciate any help someone can provide me, or get me started with the script. > > > > I have the csv file, the API details for bulk import and Admin access to the Equella Taxonomy console; > > > > If you require more specific or further info, please don't hesitate to contact me. > > > > Regards > > Amir > > > > Amir Rana > > Mob: 07843193398 > > E-mail: gags786 at yahoo.com > > Please Consider the Environment before Printing > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jexca_b1693 at yahoo.com Tue Nov 15 04:29:59 2011 From: jexca_b1693 at yahoo.com (MD.Mahbubur Rahman) Date: Mon, 14 Nov 2011 19:29:59 -0800 (PST) Subject: [Tutor] Running windows media player Message-ID: <32845242.post@talk.nabble.com> Hello friends, I need to run mp3/ogg files with Windows Media Player from a python script. I have the following code which only can start Windows Media Player. But I dont know how to run a mp3/ogg file with this instance of Windows Media Player: from pywinauto import application app = application.Application() try: wmp = app.start_( # connect_(path = ur"C:\Program Files\Windows Media Player\wmplayer.exe") except application.ProcessNotFoundError: print "Error Message " Can someone help me? Br Mahbub -- View this message in context: http://old.nabble.com/Running-windows-media-player-tp32845242p32845242.html Sent from the Python - tutor mailing list archive at Nabble.com. From lina.lastname at gmail.com Wed Nov 16 09:46:36 2011 From: lina.lastname at gmail.com (lina) Date: Wed, 16 Nov 2011 16:46:36 +0800 Subject: [Tutor] IndentationError: In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 4:31 PM, Andre Engels wrote: > On Wed, Nov 16, 2011 at 9:21 AM, lina wrote: >> >> it still complaining. I set the gedit, use space not tab, >> Now I even typed space by space, avoid using tab, it still has the same >> problem. >> >> How can I fixed it? > > The line > > ??? ??? ??? if list1[i][j] != list1[i][j+1]: > > still contains a tab, thus it is now indented negative 3 spaces plus a tab > plus 3 spaces compared to the encompassing loop, which is problematic both > because there is a negative number in there and because it differs from the > rest of the lines in the same loop (6 spaces) > Thanks, fixed, seems my gedit has problem? the preference setting using space, not Tab, really headache about it, sometimes. Thanks again, > -- > Andr? Engels, andreengels at gmail.com > > From timomlists at gmail.com Wed Nov 16 11:40:14 2011 From: timomlists at gmail.com (Timo) Date: Wed, 16 Nov 2011 11:40:14 +0100 Subject: [Tutor] Running windows media player In-Reply-To: <32845242.post@talk.nabble.com> References: <32845242.post@talk.nabble.com> Message-ID: <4EC3930E.5090606@gmail.com> Op 15-11-11 04:29, MD.Mahbubur Rahman schreef: > Hello friends, > I need to run mp3/ogg files with Windows Media Player from a python script. > I have the following code which only can start Windows Media Player. But I > dont know how to run a mp3/ogg file with this instance of Windows Media > Player: I don't have Windows, so can't test, but according to this Microsoft page [1], you can give some comandline parameters to WMP. Cheers, Timo [1] http://support.microsoft.com/kb/241422/en-us > > > from pywinauto import application > > app = application.Application() > try: > wmp = app.start_( # connect_(path = > ur"C:\Program Files\Windows Media Player\wmplayer.exe") > except application.ProcessNotFoundError: > print "Error Message " > > Can someone help me? > > Br > Mahbub From timomlists at gmail.com Wed Nov 16 11:46:57 2011 From: timomlists at gmail.com (Timo) Date: Wed, 16 Nov 2011 11:46:57 +0100 Subject: [Tutor] IndentationError: In-Reply-To: References: Message-ID: <4EC394A1.4020203@gmail.com> Op 16-11-11 09:46, lina schreef: > On Wed, Nov 16, 2011 at 4:31 PM, Andre Engels wrote: >> On Wed, Nov 16, 2011 at 9:21 AM, lina wrote: >>> it still complaining. I set the gedit, use space not tab, >>> Now I even typed space by space, avoid using tab, it still has the same >>> problem. >>> >>> How can I fixed it? >> The line >> >> if list1[i][j] != list1[i][j+1]: >> >> still contains a tab, thus it is now indented negative 3 spaces plus a tab >> plus 3 spaces compared to the encompassing loop, which is problematic both >> because there is a negative number in there and because it differs from the >> rest of the lines in the same loop (6 spaces) >> > Thanks, fixed, seems my gedit has problem? the preference setting > using space, not Tab, > really headache about it, sometimes. Gedit won't alter existing tabs when adjusting that setting. So that tab was probably already there, or you copy-pasted it from some other source. Cheers, Timo > > Thanks again, >> -- >> 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 From alan.gauld at btinternet.com Wed Nov 16 13:06:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Nov 2011 12:06:01 +0000 Subject: [Tutor] binary file query In-Reply-To: References: Message-ID: On 14/11/11 05:34, Shirkhedkar, Dhanashri wrote: > If we are opening a binary file in python then do we have to use ?Import > struct? and do ?struct.unpack? to work on the data from that binary file? That depends but in general the answer is no. But it all depends on what is in the file. If it is a known format (like Pickle say) there may well be a higher level module that will interopret the file for you. But fundamentally, opening a file in binary mode means you are reading the raw bytes from the file and the interpretation of those bytes is entirely your responsibility. > Will we be able to process the file as text file without using struct? Only if the bytes represent text. You can certainly treat the bytes as if they were text and interesting things may happen. Whether the text interpretation bears any resemblance to the original intent of the files author is another matter all together. The key thing in dealing with binary files is that you must know what the bytes you are reading represent (or be willing to reverse engineer it!). If an existing interpreter (eg pickle, PIL, gzip etc) exists that will make life easier. If not you can either read the bytes into a list and process them manually. Or, if you know what they represent, you can use struct to convert them into appropriate Python data objects. The choice is yours and depends on many factors. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 16 13:16:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Nov 2011 12:16:39 +0000 Subject: [Tutor] Bulk Import Script Help Please In-Reply-To: <639DF706-C806-4C3B-96DE-A920B71EE5D3@yahoo.com> References: <65EE14DAB3AECD4A826C6E29A843A1940B0E6DA2@EXCH-MB02.cc.rhul.local> <639DF706-C806-4C3B-96DE-A920B71EE5D3@yahoo.com> Message-ID: On 10/11/11 17:10, Amir wrote: >> I am new to python, and I need to bulk import a csv data dump into our >> content management system, Equella. OK, we can definitely help with the Python, the Equella bit will likely need a more specialised forum. What is your background? Can you already program in any other language? If so, which? What OS are you using? What Python version do you have? What tutorial are you following, if any? All of these answers can help us focus our responses. >> I need to bulk import the CSV file dump into Equella to create a >> Taxonomy using a Python script. OK, That needs more explanation too. What do you mean by a csv file dump? One large file or a folder full of files or a zip/tar file full of csvb files? And what kind of taxonomy do you mean? Is it one containing the data from the csv files or is it a taxonomy of csv files? And what is the taxonomy structure based on - is it part of Equilla? Or are you using a 3rd party tool, if so which? >> I have the csv file, the API details for bulk import and Admin access >> to the Equella Taxonomy console; OK, this suggests a single csv file, an API into Equilla and that the taxonomy is part of Equllla? Is that correct? If so the first thing to do is learn how to open and read the csv file. You should be able to do that easily using the csv module in the standard Python library. Is that enough of a starter? If not what extra information do you need? The more specific you make your questions, the more specific we can make our answers. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cranky.frankie at gmail.com Wed Nov 16 14:50:32 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 16 Nov 2011 08:50:32 -0500 Subject: [Tutor] Thank you! Message-ID: Thank you to all for your help on my SQL DDL parsing script, and thank you Alan for having this wonderful list. I got the program to work and verified the DDL is being parsed correctly. I've been working as a database administrator for many years, but before that I programmed on the mainframe. I'm used to COBOL, SQL, DB2, and latley XML. I've done some Unix scripting and VB script, taught myself some basic C and C++, with some odd Visual Basic along the way, but Python is enitirely new to me. That's why I got thrown off with the output not lining up in Notepad - I've never written anything before that could be displayed in a mode that used proportional fonts. The things I like about Python: - the forced indentation makes for really readable code - it's free! - it can be used on any platform - it can be used for scripting or for builing a stand alone program - it can work in any programming style (O-O, sturctured, etc.) I'm going to be doing a presentation on Python programming for database administrators. This script will help a lot to explain some of the basic concepts. Thanks again very much for your help. Python rocks! -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From bgailer at gmail.com Wed Nov 16 15:26:21 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 16 Nov 2011 09:26:21 -0500 Subject: [Tutor] list of objects? In-Reply-To: <1321445939.36982.YahooMailNeo@web130212.mail.mud.yahoo.com> References: <1321364424.47660.YahooMailNeo@web130222.mail.mud.yahoo.com> <4EC31D86.2050503@gmail.com> <1321445939.36982.YahooMailNeo@web130212.mail.mud.yahoo.com> Message-ID: <4EC3C80D.5020909@gmail.com> Please always reply-all so a copy goes to the list. Am forwarding this on your behalf. I will reply this afternoon. On 11/16/2011 7:18 AM, Elwin Estle wrote: > Part of the reason I am writing this program is to learn OOP, hence > the use of classes. Most of what little programming background I have > comes from working with various flavors of BASIC on old Atari 8-bit > computers back in the day, and more recently a little Tcl/Tk, so my > first instinct is to do everything from a procedural standpoint. I'm > trying to get out of my comfort zone. > > As for the game, I am doing the 'easy' version of spider that uses 8 > suits of spades. I was planing to just re-draw the display after each > move. Input-wise, I was just going to use raw_input. My idea was to > have a move consist of a three character coordinate, The 10 dealt > piles would be named by letter, A-J, and the cards in each pile would > be by number, i.e. 1-nn. A move would consist of the starting pile, > the number of the card in that pile, and the letter of the destination > pile, so 'B5H' would move everything from the 5th card down in pile B > and put it on pile H. > > ------------------------------------------------------------------------ > *From:* bob gailer > *To:* Elwin Estle > *Cc:* "tutor at python.org" > *Sent:* Tuesday, November 15, 2011 9:18 PM > *Subject:* Re: [Tutor] list of objects? > > On 11/15/2011 8:40 AM, Elwin Estle wrote: >> I am attempting to write a text based spider solitaire game. > > What are the rules of your version of Spider? The only spiders I know > have 10 dealt piles and 1 draw pile. > > I think you have greatly complicated things by using classes. Consider: > > deck = random.shuffle(range(13)*8) # list of 108 card "indexes" in > random order. > values = "A23456789JQK" # display values corresponding to indexes > piles = [deck[x:x+10] for x in range(0,108,10)] > > Anytime you want to display the value of a card use values[cardIndex] > for example to display the last card in each pile: > > for pile in piles: > print values[pile[-1]], > > What will your actual display look llike? > > Will you completely reprint it after each move, or alter it in place? > > How will you get the moves from the player? > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Wed Nov 16 16:28:57 2011 From: o0MB0o at hotmail.se (Mic) Date: Wed, 16 Nov 2011 16:28:57 +0100 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: Hi! It is no homework, in fact am I working ahead of class. I have now, after five minutes thinking, solved my problem, but a new problem has risen. But to begin with, here is how I solved the problem: from tkinter import* import time the_time='' class Window(Frame): def __init__(self,master): super(Window,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): #Create a hello button: hej=self.hellobttn=Button(self,text="Hey") self.hellobttn.grid(row=0, column=0) #Create a label that displays time: self.display_time=Label(self, text=the_time) self.display_time.grid(row=0, column=1) def change_value_the_time(): global the_time newtime = time.strftime('%H:%M:%S') if newtime != the_time: the_time= newtime self.display_time.config(text=the_time, font="40") self.display_time.after(20, change_value_the_time) change_value_the_time() root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() I found some help on the internet about making a clock, although I had to modify a lot of the code to fit my own code and window. Now to my next question. Say that I want a text ?Hi, how are you?? to be printed when the time passes 15:00:00 each day. How do I do that? At first I thought that I could just write an if statement. Like: if the_time>15:00:00: print (?Hi, how are you??) But it is obviously not working. Thank you for your help! Another question, am I supposed to add tutor at python.orgtutor@python.org; as copy? You did that, right? Regards Mic From: Wayne Werner Sent: Tuesday, November 15, 2011 10:14 PM To: Mic Cc: tutor at python.org Subject: Re: [Tutor] Clock in tkinter? On Tue, Nov 15, 2011 at 2:00 PM, Mic wrote: Hi! I am new to programming and I hop this question isn?t stupid. Welcome! I am making a small GUI program. It is supposed to have a button and a clock in it that displays the same time as it is according to the computer. So as far as I am concerned both the clock and the are supposed to be widgets? Is this a homework assignment, or just something that you're doing for fun? It seems homework-ish. We don't mind pointing you in the right direction on homework assignments, but we definitely won't do it for you. So how do I add this clock as a widget placed next to the button? Tkinter doesn't have a native clock widget, so if you want to make a clock you need to roll your own. Here is the code I have written so far, that only displays a GUI window, and a button: from tkinter import * import time class Window(Frame): def __init__(self,master): super(Window,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): self.test_button=Button(self, text="Hi") self.test_button.grid(row=0,column=0) root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() Giving us code (especially such a small amount) is exactly the right thing to do when you ask a question - it shows that you've tried something, and if it's broken it usually shows why it's broken. You can add text to the Label widget - and you can change the text on that widget. You're already importing the time module - for more information about what it contains, you can run the interactive interpreter and do this: >>> import time >>> help(time) Or you can look online for the commands that might help you. If you get stuck, let us know what you're doing and where you're stuck at. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Wed Nov 16 16:32:31 2011 From: o0MB0o at hotmail.se (Mic) Date: Wed, 16 Nov 2011 16:32:31 +0100 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: Thank you Yes, wise statement. Mic From: Asokan Pichai Sent: Wednesday, November 16, 2011 5:17 AM To: Mic Cc: tutor at python.org Subject: Re: [Tutor] Clock in tkinter? > On Wed, Nov 16, 2011 at 1:30 AM, Mic wrote: > Hi! > I am new to programming WELCOME! >and I hop this question isn?t stupid. A teacher of mine said, "The only stupid question is the one you thought of asking but did not ask!" Happy learning Asokan Pichai -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: wlEmoticon-smile[1].png Type: image/png Size: 1041 bytes Desc: not available URL: From kellyadrian at hotmail.com Wed Nov 16 16:46:54 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Wed, 16 Nov 2011 15:46:54 +0000 Subject: [Tutor] modulus Message-ID: Please can anyone tell me how i can print this without all the brackets and commas, i know i need the modulus symbol but i dont know how it works. any advice would be appreciated regards adrian def arguments(): name=raw_input ("Please enter your firstname: ") surname=raw_input ("Enter your surname: ") address1=raw_input ("Enter Address line 1: ") address2=raw_input ("Enter Address line 2: ") address3=raw_input ("Enter Address line 3: ") return name,surname,address1,address2,address3 address=arguments() print "%s %s" % address -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Nov 16 16:59:50 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Nov 2011 09:59:50 -0600 Subject: [Tutor] modulus In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 9:46 AM, ADRIAN KELLY wrote: > Please can anyone tell me how i can print this without all the brackets > and commas, i know i need the modulus symbol but i dont know how it works. > any advice would be appreciated > > regards > adrian > > def arguments(): > name=raw_input ("Please enter your firstname: ") > surname=raw_input ("Enter your surname: ") > address1=raw_input ("Enter Address line 1: ") > address2=raw_input ("Enter Address line 2: ") > address3=raw_input ("Enter Address line 3: ") > return name,surname,address1,address2,address3 > address=arguments() > print "%s %s" % address > In this case it's not actually modulus, it's just the syntax for string formatting. I'm not sure *what* the reasoning behind the % was, but that's the way it is. There are two ways to do string formatting, the new (.format) and old (%). In new style formatting you use the .format method of the string: "{0} {1} {2}".format("One", 2, "Five") You don't usually have to worry about the type, though you can specify it along with some other useful modifiers for precision, spacing, and alignment. In old style formatting, you use a string with format specifiers (%s, %d, etc.) followed by a tuple of arguments. Here, the lengths have to match exactly - if you have one specifier then you must have a 1-element tuple. In your case, you're returning a 5 element tuple, so you want 5 format specifiers: print "%s %s %s %s %s" % address However, if you just want to print the data out like that you can do it a little easier like this: print ' '.join(address) Or if you are in 3.x or use `from __future__ import print_function` then you can do this: print(*address) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Nov 16 17:01:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Nov 2011 03:01:58 +1100 Subject: [Tutor] modulus In-Reply-To: References: Message-ID: <4EC3DE76.1050902@pearwood.info> ADRIAN KELLY wrote: > Please can anyone tell me how i can print this without all the brackets and commas, i know i need the modulus symbol but i dont know how it works. > any advice would be appreciated > > regards > adrian > > def arguments(): > name=raw_input ("Please enter your firstname: ") > surname=raw_input ("Enter your surname: ") > address1=raw_input ("Enter Address line 1: ") > address2=raw_input ("Enter Address line 2: ") > address3=raw_input ("Enter Address line 3: ") > return name,surname,address1,address2,address3 > address=arguments() This line is misleading. arguments() does not return an address. It returns a name, a surname, and three address lines. > print "%s %s" % address Try one of these instead: # Version 1 name,surname,address1,address2,address3 = arguments() print name print surname print address1 print address2 print address3 # Version 2 items = arguments() for item in items: print item # Version 3 items = arguments() print "%s %s %s %s %s" % items -- Steven From steve at pearwood.info Wed Nov 16 17:09:09 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Nov 2011 03:09:09 +1100 Subject: [Tutor] modulus In-Reply-To: References: Message-ID: <4EC3E025.6030203@pearwood.info> Wayne Werner wrote: > In this case it's not actually modulus, it's just the syntax for string > formatting. I'm not sure *what* the reasoning behind the % was, but that's > the way it is. I believe the designers of the C programming language are to blame. [...] > In old style formatting, you use a string with format specifiers (%s, %d, > etc.) followed by a tuple of arguments. Here, the lengths have to match > exactly - if you have one specifier then you must have a 1-element tuple. That's actually wrong. If you have one specifier, you must have one object of any sort *except* a tuple. >>> "%s" % 42 # One object not a tuple. '42' But if you have a tuple, the % formatting will try to use each element in the tuple separately: >>> "%s" % (23, 42) # One object which is a tuple Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting So if you actually want to use a tuple as the object, you need to wrap it in a single item tuple: >>> "%s" % ((23, 42),) # Tuple inside a tuple. '(23, 42)' -- Steven From kellyadrian at hotmail.com Wed Nov 16 17:09:04 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Wed, 16 Nov 2011 16:09:04 +0000 Subject: [Tutor] modulus In-Reply-To: References: , Message-ID: really appreciate that answer thanks very much.......... Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwerner at gmail.com Date: Wed, 16 Nov 2011 09:59:50 -0600 Subject: Re: [Tutor] modulus To: kellyadrian at hotmail.com CC: tutor at python.org On Wed, Nov 16, 2011 at 9:46 AM, ADRIAN KELLY wrote: Please can anyone tell me how i can print this without all the brackets and commas, i know i need the modulus symbol but i dont know how it works. any advice would be appreciated regards adrian def arguments(): name=raw_input ("Please enter your firstname: ") surname=raw_input ("Enter your surname: ") address1=raw_input ("Enter Address line 1: ") address2=raw_input ("Enter Address line 2: ") address3=raw_input ("Enter Address line 3: ") return name,surname,address1,address2,address3 address=arguments() print "%s %s" % address In this case it's not actually modulus, it's just the syntax for string formatting. I'm not sure *what* the reasoning behind the % was, but that's the way it is. There are two ways to do string formatting, the new (.format) and old (%). In new style formatting you use the .format method of the string: "{0} {1} {2}".format("One", 2, "Five") You don't usually have to worry about the type, though you can specify it along with some other useful modifiers for precision, spacing, and alignment. In old style formatting, you use a string with format specifiers (%s, %d, etc.) followed by a tuple of arguments. Here, the lengths have to match exactly - if you have one specifier then you must have a 1-element tuple. In your case, you're returning a 5 element tuple, so you want 5 format specifiers: print "%s %s %s %s %s" % address However, if you just want to print the data out like that you can do it a little easier like this: print ' '.join(address) Or if you are in 3.x or use `from __future__ import print_function` then you can do this: print(*address) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Nov 16 17:17:46 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Nov 2011 10:17:46 -0600 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 9:28 AM, Mic wrote: > Hi! > It is no homework, in fact am I working ahead of class. I have now, after > five minutes thinking, solved my problem, but a new problem has risen. > But to begin with, here is how I solved the problem: > > > > from tkinter import* > import time > > the_time='' > > > > class Window(Frame): > def __init__(self,master): > super(Window,self).__init__(master) > self.grid() > self.create_widgets() > > > def create_widgets(self): > > #Create a hello button: > hej=self.hellobttn=Button(self,text="Hey") > self.hellobttn.grid(row=0, column=0) > > #Create a label that displays time: > self.display_time=Label(self, text=the_time) > self.display_time.grid(row=0, column=1) > > def change_value_the_time(): > global the_time > newtime = time.strftime('%H:%M:%S') > if newtime != the_time: > the_time= newtime > self.display_time.config(text=the_time, font="40") > self.display_time.after(20, change_value_the_time) > If you're going to put a function inside your class (since you're using self in there, I'm sure that's what you meant to do), you should change it to: def change_value_the_time(self): and call it with self.display_time.after(20, self.change_value_the_time) But your program also has unnecessary code. First, since you have a class then instead of using a global, you should simply declare `self.the_time = ''` in your __init__ for your class. Personally, I would have written the function more like this: def update_time(self): self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') self.after(20, self.update_time) Then at the end of my __init__ function I would call self.update_time() I'm not sure how that will work with your current setup, though. I found some help on the internet about making a clock, although I had to > modify a lot of the code to fit my own code and window. > Now to my next question. Say that I want a text ?Hi, how are you?? to be > printed when the time passes 15:00:00 each day. How do I do that? > > At first I thought that I could just write an if statement. Like: > > if the_time>15:00:00: > print (?Hi, how are you??) > > But it is obviously not working. > You can write one very similar to that. Take a look at the time.localtime method. > > Thank you for your help! Another question, am I supposed to add > tutor at python.org; as copy? You did that, right? > Yes - if you click "reply to all" in your email client, that will automatically send it to tutor at python.org HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Nov 16 17:28:40 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Nov 2011 10:28:40 -0600 Subject: [Tutor] modulus In-Reply-To: <4EC3E025.6030203@pearwood.info> References: <4EC3E025.6030203@pearwood.info> Message-ID: On Wed, Nov 16, 2011 at 10:09 AM, Steven D'Aprano wrote: > Wayne Werner wrote: > > >> In old style formatting, you use a string with format specifiers (%s, %d, >> etc.) followed by a tuple of arguments. Here, the lengths have to match >> exactly - if you have one specifier then you must have a 1-element tuple. >> > > That's actually wrong. If you have one specifier, you must have one object > of any sort *except* a tuple. I think you misunderstood - I said a 1-element tuple - e.g. (3,) > >>> "%s" % 42 # One object not a tuple. > '42' > > But if you have a tuple, the % formatting will try to use each element in > the tuple separately: > > >>> "%s" % (23, 42) # One object which is a tuple > As above, that's a two-element tuple. It was explained to me once that in this case: "%s" % 42 That since python expects to see a single-element tuple it treats it as or converts 42 to a single element tuple. I suppose I could have called it a tuple of length 1 instead. Sorry for the mistunderstanding, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Wed Nov 16 17:59:12 2011 From: o0MB0o at hotmail.se (Mic) Date: Wed, 16 Nov 2011 17:59:12 +0100 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: Thanks for your quick answer. Hmm, I never thought that didn?t have to use a global variable. When you mentioned time.localtime() method, did you mean that I should convert the time to numbers and then write an if statement? Like, say that I make 1 hour equivalent to the integear clock= 1. Then I write an if statement that says that the computer should print ?Hi? if clock>1: print (?hi?) Did I understand that correctly? Thanks for your answers! Mic From: Wayne Werner Sent: Wednesday, November 16, 2011 5:17 PM To: Mic Cc: tutor at python.org Subject: Re: [Tutor] Clock in tkinter? On Wed, Nov 16, 2011 at 9:28 AM, Mic wrote: Hi! It is no homework, in fact am I working ahead of class. I have now, after five minutes thinking, solved my problem, but a new problem has risen. But to begin with, here is how I solved the problem: from tkinter import* import time the_time='' class Window(Frame): def __init__(self,master): super(Window,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): #Create a hello button: hej=self.hellobttn=Button(self,text="Hey") self.hellobttn.grid(row=0, column=0) #Create a label that displays time: self.display_time=Label(self, text=the_time) self.display_time.grid(row=0, column=1) def change_value_the_time(): global the_time newtime = time.strftime('%H:%M:%S') if newtime != the_time: the_time= newtime self.display_time.config(text=the_time, font="40") self.display_time.after(20, change_value_the_time) If you're going to put a function inside your class (since you're using self in there, I'm sure that's what you meant to do), you should change it to: def change_value_the_time(self): and call it with self.display_time.after(20, self.change_value_the_time) But your program also has unnecessary code. First, since you have a class then instead of using a global, you should simply declare `self.the_time = ''` in your __init__ for your class. Personally, I would have written the function more like this: def update_time(self): self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') self.after(20, self.update_time) Then at the end of my __init__ function I would call self.update_time() I'm not sure how that will work with your current setup, though. I found some help on the internet about making a clock, although I had to modify a lot of the code to fit my own code and window. Now to my next question. Say that I want a text ?Hi, how are you?? to be printed when the time passes 15:00:00 each day. How do I do that? At first I thought that I could just write an if statement. Like: if the_time>15:00:00: print (?Hi, how are you??) But it is obviously not working. You can write one very similar to that. Take a look at the time.localtime method. Thank you for your help! Another question, am I supposed to add tutor at python.org; as copy? You did that, right? Yes - if you click "reply to all" in your email client, that will automatically send it to tutor at python.org HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Nov 16 17:44:37 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 16 Nov 2011 16:44:37 +0000 Subject: [Tutor] binary file query In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47401EC9C@SCACMX007.exchad.jpmchase.net> >If we are opening a binary file in python then do we have to use "Import struct" and do "struct.unpack" to work on the data from that binary file? >Will we be able to process the file as text file without using struct? You should open the file with the 'rb' parameter and then read from it as you need to. with open( 'filename.ext', 'rb' ) as f: # python 2.6+ syntax f.read( [size] ) # OR f.readline( [size] ) http://docs.python.org/tutorial/inputoutput.html Start from section 7.2 Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From waynejwerner at gmail.com Wed Nov 16 18:27:04 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Nov 2011 11:27:04 -0600 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 10:59 AM, Mic wrote: > Thanks for your quick answer. Hmm, I never thought that didn?t have to > use a global variable. > That's often the point of using classes - you want to collect related data and functions in one place. In this case, you're creating a clock widget, so you want all of your clock data and methods inside your class. > When you mentioned time.localtime() method, did you mean that I should > convert the time to numbers and then write an if statement? > Like, say that I make 1 hour equivalent to the integear clock= 1. Then I > write an if statement that says that the computer should print ?Hi? > if clock>1: > print (?hi?) > Take a look at what's available from the localtime: >>> help(time.localtime) and >>> help(time.localtime()) You should be able to figure out a way to make it work pretty much like what your initial thought was. As an aside, you've been top-posting, which can cause a lot of problems for people who want to follow the thread of the conversation - all they see is what you've written with no context. The appropriate thing to do is reply inline, removing any irrelevant material and (usually) indicating that you've done so with a or [...] or something similiar. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Wed Nov 16 18:44:30 2011 From: o0MB0o at hotmail.se (Mic) Date: Wed, 16 Nov 2011 18:44:30 +0100 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: Okay, that is good to know. Yes, I here is how I solved my problem: def print_hi_15_00(): time1=int(time.strftime('%H')) if time1>15: print("hi") That worked fine. However, if the time is say 15, I want it print 16 instead. And if the time is 16, I want it to print 17 instead. Here is how I thought to solve it. time2=time1 + 1 print(time2) ...And apparently it worked now, when I tested it. It didn?t earlier... I wonder if you have any suggestions regarding how to place widgets in my window. Even though I try to arrange them as orderly as possible they get placed at all different kind of places in the window. I use the grid method and place them in the window by using row=something and column=something. It just doesn?t look good. It looks okay I suppose, but not as good as I want it to look. I must admit though that I did not understand what you wrote earlier, refering to the fact that I don?t need global variables. I tried your suggestion of the function but didn?t get it to work. So if I got it right. Inside the constructor (__init__) I should declare: self.the_time=?? Then, if I understood it right, I should also place the function call there? self.update_time() as you refered to? Oh, by top-posting you mean that I include everything I have written before in my post, and that it is no good to do? So I just post what I wrote, and nothing from earlier on in this conversation? Mic -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Nov 16 19:13:35 2011 From: d at davea.name (Dave Angel) Date: Wed, 16 Nov 2011 13:13:35 -0500 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: <4EC3FD4F.8070207@davea.name> Top-posting is what I'm doing here. Putting my remarks BEFORE the part I'm quoting. On 11/16/2011 12:44 PM, Mic wrote: > > > > Oh, by top-posting you mean that I include everything I have written before in my post, and that it is no good to do? > So I just post what I wrote, and nothing from earlier on in this conversation? > This is where the new remarks should go. Just after the part you're responding to. And since I'm not commenting on anything else, I snipped it out. -- DaveA From d at davea.name Wed Nov 16 19:22:14 2011 From: d at davea.name (Dave Angel) Date: Wed, 16 Nov 2011 13:22:14 -0500 Subject: [Tutor] Multiple threads In-Reply-To: References: <31766634.4.1321451296410.JavaMail.geo-discussion-forums@yqcm23> <4EC3F298.1030604@davea.name> Message-ID: <4EC3FF56.7030101@davea.name> (You're top-posting. Put your remarks AFTER what you're quoting) On 11/16/2011 12:52 PM, Jack Keegan wrote: > Ok, I thought that processes would do the same job as threads. So would the > general rule be some thing like so: > > If I want another piece of work to run (theoretically) along side my main > script, and I want to share data between them, I should use a thread and > share data with the thread-safe queue. > If the work I want done can function and complete on its own, go for a > process. > > Would that be about right? > Yes, with all the caveats I mentioned before. With some language implementations, and with some operating systems, and on some CPU-systems, the guidelines could be different. They all trade off in ways too complex to describe here. For example, if a thread is mostly doing I/O, it may be just as efficient as a separate process, even if sharing data isn't an issue. And in some languages, sharing data between processes isn't all that tough, either. -- DaveA From alan.gauld at btinternet.com Wed Nov 16 20:15:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 16 Nov 2011 19:15:40 +0000 Subject: [Tutor] Thank you! In-Reply-To: References: Message-ID: On 16/11/11 13:50, Cranky Frankie wrote: > Thank you to all for your help on my SQL DDL parsing script, and thank > you Alan for having this wonderful list. Not much to do with me I'm just one the moderators who happens to flush the admin queue occasionally! :-) > before that I programmed on the mainframe. I'm used to COBOL, SQL, > DB2, and latley XML. I've done some Unix scripting and VB script, > taught myself some basic C and C++, with some odd Visual Basic along > the way, but Python is enitirely new to me. That's why I got thrown > off with the output not lining up in Notepad - I've never written > anything before that could be displayed in a mode that used > proportional fonts. I don't believe you! :-) What you probably mean is that you haven't had a display tool that could use proportional fonts (or at least never used them!) You will hit the same problem using some Winsdows VT200 emulators, or even 3270 emulators for the mainframe if they support proportional fonts. (But never, ever try working a 3270 with proportional fonts!) You could take some plain text produced by one of your programs 20 years ago and Notepad, with the wrong font, would still cause misalignment. It's nothing to do with the output but all to do with the display tool. And its by no means a new problem, its been around since the first graphical, bitmapped, displays appeared in the 1980's... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Wed Nov 16 20:38:30 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Nov 2011 13:38:30 -0600 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 11:44 AM, Mic wrote: > I wonder if you have any suggestions regarding how to place widgets in > my window. > Even though I try to arrange them as orderly as possible they get placed > at all different kind of places in the window. > I use the grid method and place them in the window by using row=something > and column=something. > > It just doesn?t look good. It looks okay I suppose, but not as good as I > want it to look. > http://twitpic.com/2t4n9q/full http://twitpic.com/2t4n9p/full Those images might help you understand a little bit more about the grid layout. > So if I got it right. Inside the constructor (__init__) I should declare: > self.the_time=?? > Then, if I understood it right, I should also place the function call > there? > self.update_time() as you refered to? > Your constructor should look something like this: def __init__(self): #Your call to super self.the_time = '' # your other code self.update_time() I don't know for sure that it will work, but I expect that it will. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From nidianjs at hotmail.com Wed Nov 16 20:41:48 2011 From: nidianjs at hotmail.com (Nidian Job-Smith) Date: Wed, 16 Nov 2011 19:41:48 +0000 Subject: [Tutor] Tutor Ilde running problems In-Reply-To: References: , Message-ID: Hi all, Just installed python 2.7.2 on my windows 7 32-bit laptop. However when I attempt to run idle it wont open (nothing happens) Wondered if any of you have had this problem and have any tips? Cheers> _______________________________________________ > 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 Wed Nov 16 21:11:23 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Nov 2011 14:11:23 -0600 Subject: [Tutor] Tutor Ilde running problems In-Reply-To: References: Message-ID: On Wed, Nov 16, 2011 at 1:41 PM, Nidian Job-Smith wrote: > Hi all, > > Just installed python 2.7.2 on my windows 7 32-bit laptop. However > when I attempt to run idle it wont open (nothing happens) > > Wondered if any of you have had this problem and have any tips? > This is more of a Windows issue, but I'll give it a go: I would try opening the command prompt (type cmd in the start menu) and typing the following at the prompt: c:\Python27\python.exe c:\Python27\lib\idlelib\idle.pyw If you installed Python somewhere else, replace Python27 with the directory you installed it to. Copy and paste the output of that command - you might need to click on the icon in the top left of the window and there's an edit option that should help you out. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Wed Nov 16 21:55:47 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Wed, 16 Nov 2011 20:55:47 +0000 Subject: [Tutor] format integer to currency Message-ID: print ("i own {0:.2f} {1}".format(1.1,"million")) can anyone help me with code to change the format of this to currency ?1.10 million thanks for your help -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Nov 16 22:46:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Nov 2011 08:46:00 +1100 Subject: [Tutor] format integer to currency In-Reply-To: References: Message-ID: <4EC42F18.5020309@pearwood.info> ADRIAN KELLY wrote: > > print ("i own {0:.2f} {1}".format(1.1,"million")) > > can anyone help me with code to change the format of this to currency ?1.10 million > thanks for your help # Python 2.6 or 2.7 print (u"I own ?{0:.2f} {1}".format(1.1, "million")) # Python 3 print ("I own ?{0:.2f} {1}".format(1.1, "million")) -- Steven From steve at pearwood.info Wed Nov 16 23:04:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Nov 2011 09:04:54 +1100 Subject: [Tutor] modulus In-Reply-To: References: <4EC3E025.6030203@pearwood.info> Message-ID: <4EC43386.9030306@pearwood.info> Wayne Werner wrote: > On Wed, Nov 16, 2011 at 10:09 AM, Steven D'Aprano wrote: > >> Wayne Werner wrote: >> >> >>> In old style formatting, you use a string with format specifiers (%s, %d, >>> etc.) followed by a tuple of arguments. Here, the lengths have to match >>> exactly - if you have one specifier then you must have a 1-element tuple. >>> >> That's actually wrong. If you have one specifier, you must have one object >> of any sort *except* a tuple. > > > I think you misunderstood - I said a 1-element tuple - e.g. (3,) Actually, I didn't misunderstand... I just worded my reply badly. Sorry for the confusion. What I should have said was, you *can* use a 1-element tuple, but you don't *need* to use a 1-element tuple UNLESS that element is itself a tuple. For any other object, just use the object itself. There's no need to wrap it in a tuple first. > As above, that's a two-element tuple. It was explained to me once that in > this case: > > "%s" % 42 > > That since python expects to see a single-element tuple it treats it as or > converts 42 to a single element tuple. "Treats as" may be true; "converts to" not so much. What it actually does is this: py> import dis py> dis.dis(compile('"%s" % x', '', 'single')) 1 0 LOAD_CONST 0 ('%s') 3 LOAD_NAME 0 (x) 6 BINARY_MODULO 7 PRINT_EXPR 8 LOAD_CONST 1 (None) 11 RETURN_VALUE Notice that the call to BINARY_MODULO (the % operator) takes two arguments, the string "%s" and the object x, whatever it happens to be. Python can't convert x to a tuple at this point, because it doesn't know what x is, and it may not know how many format specifiers are in the string either. Once the string and the object hit BINARY_MODULO, all bets are off. It will do whatever it likes, because that's purely internal implementation. -- Steven From waynejwerner at gmail.com Wed Nov 16 23:29:26 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 16 Nov 2011 16:29:26 -0600 Subject: [Tutor] modulus In-Reply-To: <4EC43386.9030306@pearwood.info> References: <4EC3E025.6030203@pearwood.info> <4EC43386.9030306@pearwood.info> Message-ID: On Wed, Nov 16, 2011 at 4:04 PM, Steven D'Aprano wrote: > Wayne Werner wrote: > >> It was explained to me once that in > > this case: >> >> "%s" % 42 >> >> That since python expects to see a single-element tuple it treats it as or >> converts 42 to a single element tuple. >> > > "Treats as" may be true; "converts to" not so much. What it actually does > is this: > > py> import dis > py> dis.dis(compile('"%s" % x', '', 'single')) > 1 0 LOAD_CONST 0 ('%s') > 3 LOAD_NAME 0 (x) > 6 BINARY_MODULO > 7 PRINT_EXPR > 8 LOAD_CONST 1 (None) > 11 RETURN_VALUE > > > Notice that the call to BINARY_MODULO (the % operator) takes two > arguments, the string "%s" and the object x, whatever it happens to be. > Python can't convert x to a tuple at this point, because it doesn't know > what x is, and it may not know how many format specifiers are in the string > either. > > Once the string and the object hit BINARY_MODULO, all bets are off. It > will do whatever it likes, because that's purely internal implementation. Ah, very cool. Just because I was interested, I did the same thing, only using (x,) and there was only one difference (line? 6): >>> dis.dis(compile('"%s" % (x, )', '', 'single')) 1 0 LOAD_CONST 0 ('%s') 3 LOAD_NAME 0 (x) 6 BUILD_TUPLE 1 9 BINARY_MODULO 10 PRINT_EXPR 11 LOAD_CONST 1 (None) 14 RETURN_VALUE The more you know! Thanks, -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From questions.anon at gmail.com Thu Nov 17 06:02:06 2011 From: questions.anon at gmail.com (questions anon) Date: Thu, 17 Nov 2011 16:02:06 +1100 Subject: [Tutor] change values in an array Message-ID: I am trying to do something really simple. I have a numpy array and if any values in the array are 255 I want to change them to 1. but I can't seem to get anything to work! If I use: for i, value in enumerate(mask_arr): if value==255: mask_arr[i]=1 I get this error: Traceback (most recent call last): File "d:/timeseries_mask.py", line 51, in if value==255: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() and if I try to add a.any() to my code: for i, value in enumerate(mask_arr): if value.any()==255: mask_arr[i]=1 my array does not change at all. Any feedback will be greatly appreciated -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Nov 17 09:21:29 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Nov 2011 09:21:29 +0100 Subject: [Tutor] change values in an array References: Message-ID: questions anon wrote: > I am trying to do something really simple. > I have a numpy array and if any values in the array are 255 I want to > change them to 1. > but I can't seem to get anything to work! Note that numpy is a specialist topic, and for everything but the basics the numpy mailing list is the best place to ask questions about it. > > If I use: > > for i, value in enumerate(mask_arr): > if value==255: > mask_arr[i]=1 > > I get this error: > > Traceback (most recent call last): > File "d:/timeseries_mask.py", line 51, in > if value==255: > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > > and if I try to add a.any() to my code: > > for i, value in enumerate(mask_arr): > if value.any()==255: > mask_arr[i]=1 > > my array does not change at all. > Any feedback will be greatly appreciated You seem to have a multidimensional array, i. e. value is still an array >>> import numpy >>> a = numpy.array([[1, 2], [3, 4]]) >>> for value in a: print value ... [1 2] [3 4] >>> if a[0]: pass ... Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() If you want to access the values of an n-dimensional array using a standard Python approach you have to use n nested for-loops: >>> for i, row in enumerate(a): ... for k, value in enumerate(row): ... if value == 1: ... a[i, k] = 42 ... >>> a array([[42, 2], [ 3, 4]]) As that is not very efficient numpy offers an alternative: >>> a[a == 42] = 123 >>> a array([[123, 2], [ 3, 4]]) or using the names from your example: mask_arr[mask_arr == 255] = 1 From lina.lastname at gmail.com Thu Nov 17 10:59:14 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 17 Nov 2011 17:59:14 +0800 Subject: [Tutor] how to understand unhashable type: 'list' Message-ID: list1 [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] >>> weight={} >>> weight{list1[0]}=1 SyntaxError: invalid syntax >>> weight[list1[0]]=1 Traceback (most recent call last): File "", line 1, in weight[list1[0]]=1 TypeError: unhashable type: 'list' >>> I wonder how to count the occurence of the list of lists. Thanks, ^_^ From cwitts at compuscan.co.za Thu Nov 17 11:09:12 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 17 Nov 2011 12:09:12 +0200 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: Message-ID: <4EC4DD48.5090801@compuscan.co.za> On 2011/11/17 11:59 AM, lina wrote: > list1 > [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', > '70', '61', '34'], ['34', '58', '34', '58']] >>>> weight={} >>>> weight{list1[0]}=1 > SyntaxError: invalid syntax >>>> weight[list1[0]]=1 > Traceback (most recent call last): > File "", line 1, in > weight[list1[0]]=1 > TypeError: unhashable type: 'list' > I wonder how to count the occurence of the list of lists. > > Thanks, ^_^ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > sum(1 if type(elem) == list else 0 for elem in list1) not work for you if all you want to do is count how many lists you have in your main list ? -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 17 11:26:29 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 17 Nov 2011 18:26:29 +0800 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: <4EC4DD48.5090801@compuscan.co.za> References: <4EC4DD48.5090801@compuscan.co.za> Message-ID: On Thu, Nov 17, 2011 at 6:09 PM, Christian Witts wrote: > On 2011/11/17 11:59 AM, lina wrote: > > list1 > [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', > '70', '61', '34'], ['34', '58', '34', '58']] > > weight={} > weight{list1[0]}=1 > > SyntaxError: invalid syntax > > weight[list1[0]]=1 > > Traceback (most recent call last): > File "", line 1, in > weight[list1[0]]=1 > TypeError: unhashable type: 'list' > > I wonder how to count the occurence of the list of lists. > > Thanks, ^_^ > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > sum(1 if type(elem) == list else 0 for elem in list1) not work for you if > all you want to do is count how many lists you have in your main list ? not count how many sublists in the main list. wanna count the occurence of the sublists, I mean, something like >>> dictionary[list1[1]]=occurence Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' >>> > -- >>>> dictionary[list1[1]]=1 Traceback (most recent call last): File "", line 1, in dictionary[list1[1]]=1 TypeError: unhashable type: 'list' >>> > Christian Witts > Python Developer > From cwitts at compuscan.co.za Thu Nov 17 11:39:04 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 17 Nov 2011 12:39:04 +0200 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4DD48.5090801@compuscan.co.za> Message-ID: <4EC4E448.1020506@compuscan.co.za> On 2011/11/17 12:26 PM, lina wrote: > On Thu, Nov 17, 2011 at 6:09 PM, Christian Witts wrote: >> On 2011/11/17 11:59 AM, lina wrote: >> >> list1 >> [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', >> '70', '61', '34'], ['34', '58', '34', '58']] >> >> weight={} >> weight{list1[0]}=1 >> >> SyntaxError: invalid syntax >> >> weight[list1[0]]=1 >> >> Traceback (most recent call last): >> File "", line 1, in >> weight[list1[0]]=1 >> TypeError: unhashable type: 'list' >> >> I wonder how to count the occurence of the list of lists. >> >> Thanks, ^_^ >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> sum(1 if type(elem) == list else 0 for elem in list1) not work for you if >> all you want to do is count how many lists you have in your main list ? > not count how many sublists in the main list. > > wanna count the occurence of the sublists, > > I mean, something like > >>>> dictionary[list1[1]]=occurence > Traceback (most recent call last): > File "", line 1, in > dictionary[list1[1]]=1 > TypeError: unhashable type: 'list' >>>>> dictionary[list1[1]]=1 > Traceback (most recent call last): > File "", line 1, in > dictionary[list1[1]]=1 > TypeError: unhashable type: 'list' > For that you'll need to convert your list to a hash-able type if you want to use dictionaries for your store, easiest would probably to use the string representation for it so you could do >>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] >>> weight = {} >>> for elem in list1: ... if elem.__repr__() in weight: ... weight[elem.__repr__()] += 1 ... else: ... weight[elem.__repr__()] = 1 ... >>> weight {"['34', '58', '34', '58']": 1, "['61', '70', '61', '34']": 1, "['61', '34', '61 ', '34']": 1, "['61', '35', '61', '70', '61']": 1} or >>> from collections import defaultdict >>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '7 0', '61', '34'], ['34', '58', '34', '58']] >>> weight = defaultdict(int) >>> for elem in list1: ... weight[elem.__repr__()] += 1 ... >>> weight defaultdict(, {"['34', '58', '34', '58']": 1, "['61', '70', '61', '34']": 1, "['61', '34', '61', '34']": 1, "['61', '35', '61', '70', '61']": 1}) Hope that helps. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikunj.Badjatya at emc.com Thu Nov 17 11:51:06 2011 From: Nikunj.Badjatya at emc.com (Nikunj.Badjatya at emc.com) Date: Thu, 17 Nov 2011 05:51:06 -0500 Subject: [Tutor] ProgressBar - Python and Powershell Message-ID: <599CEBACD49B4144A61212D837EE3C0F144604D187@MX34A.corp.emc.com> Hi All, I am using Python 2.7, windows Env. I have an Installer written in Python(45%) and Powershell(55%) which is used to install Virtual Machines at specific locations. It is single threaded. I am trying to implement a ProgressBar for this installer. So that the user will come to know the progress of the installation. I am using pypi progressbar module. The top script is in python which inturns calls powershell scripts using subprocess.call() and proceeds with the installation. I am taking a shared file between python and powershell, so that diff functions can update their %age completion level in to the file. Ex. Func1() updates it to 5%, func2() will add its own 5% to it.. and so on. At the start of the (main.py) script I am creating a thread whose sole purpose would be to keep "READ" a temp file for a new entry in it. Based on this entry I can have my thread update the progressbar on the console. My questions are: 1. Can I have a better shared mechanism between python and powershell.? As I am using a file here. Reading + writing in python and writing only in powershell. ! 2. Does this thread mechanism work.? I am yet to implement and test it.! :P What can be the possible shortfalls.? Thanks Nikunj Bangalore - India -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Nov 17 13:17:10 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 17 Nov 2011 23:17:10 +1100 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: Message-ID: <4EC4FB46.2010303@pearwood.info> lina wrote: > list1 > [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', > '70', '61', '34'], ['34', '58', '34', '58']] You have a list of lists. >>>> weight={} >>>> weight{list1[0]}=1 > SyntaxError: invalid syntax In Python, {} are used for dicts, and in Python 3, sets. They aren't used for anything else. obj{...} is illegal syntax. >>>> weight[list1[0]]=1 > > Traceback (most recent call last): > File "", line 1, in > weight[list1[0]]=1 > TypeError: unhashable type: 'list' You are trying to store a list as a key inside a dict. This cannot be done because lists (like all mutable types) can't be hashed. If your list of lists is small, say, less than a few thousand items, it would be fast enough to do this: counts = [] seen = [] for sublist in list1: if sublist in seen: # No need to do it again. continue seen.append(sublist) counts.append( (sublist, list1.count(sublist)) ) If I run this code on your list1, I get these counts: [(['61', '34', '61', '34'], 1), (['61', '35', '61', '70', '61'], 1), (['61', '70', '61', '34'], 1), (['34', '58', '34', '58'], 1)] That is, each list is unique. However, if you have many thousands of items, the above may be too slow. It is slow because of all the linear searches: "sublist in seen" searches seen for the sublist, one item at a time, and "list1.count(sublist)" searches list1 for sublist, also one item at a time. If there are many items, this will be slow. To speed it up, you can do this: (1) Keep the seen list sorted, and use binary search instead of linear search. See the bisect module for help. (2) Sort list1, and write your own smarter count() function that doesn't have to travel along the entire list. All that involves writing a lot of code though. Probably much faster would be to make a temporary copy of list1, with the inner lists converted to tuples: list2 = [tuple(l) for l in list1] counts = {} for t in list2: counts[t] = 1 + counts.get(t, 0) for t, n in counts.items(): print list(t), n -- Steven From nidianjs at hotmail.com Thu Nov 17 14:14:42 2011 From: nidianjs at hotmail.com (Nidian Job-Smith) Date: Thu, 17 Nov 2011 13:14:42 +0000 Subject: [Tutor] (no subject) Message-ID: Hi all, I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to programme rot13. I've written some code but it doesn't seem to work.... Here it is: def rot13(s): char_low = () result = "" if not s.isalpha(): return char char_low = char_low.lower() if char_low <= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) def rot13_char(ch): return ''.join( rot13(s) for char in ch ) Any idea where i'm wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Nov 17 14:39:19 2011 From: andreengels at gmail.com (Andre Engels) Date: Thu, 17 Nov 2011 14:39:19 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Thu, Nov 17, 2011 at 2:14 PM, Nidian Job-Smith wrote: > Hi all, > > I'm new to programming (thus Python), so after reading the > basics, I wanted to practise what I've learnt . I've come across a > beginners exercise which is to programme rot13. > > I've written some code but it doesn't seem to work.... > > Here it is: > > > def rot13(s): > char_low = () > result = "" > if not s.isalpha(): > return char > char_low = char_low.lower() > if char_low <= 'm': > dist = 13 > else: > dist = -13 > char = chr(ord(char) + dist) > > def rot13_char(ch): > return ''.join( rot13(s) for char in ch ) > > > Any idea where i'm wrong? > Please, when posting a program that has problems to this list, do not just say that "it doesn't work". Tell us what is wrong: * If you get a syntax error, tell us that, and tell us where it is claimed the syntax error is * if you get an error message, give the error message as well as the stack trace provided with it, or at least the last part of that stack trace * If the program does not crash, but behaves different from what you expected, tell us what you expected to get, and what you actually got (for example, "After giving the input 5 and 3 I had expected the program to output 8 and ask for a new pair of numbers, but instead it showed 8 lines of 8 stars, printed 'Thank you for using my program' and ended. Having said that, using your program gave me various problems. The first was in return ''.join( rot13(s) for char in ch ) - I got an error message that the name 's' was not defined. Reason: the variable before the for should be the same as after, so you should either say 'rot13(s) for s in ch' or 'rot13(char) for char in ch' Most of your other problems had the same cause: If you want to use something (a thing, a number, a letter, whatever), use the same name as you used when you defined that thing. -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 17 14:56:37 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 17 Nov 2011 21:56:37 +0800 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: <4EC4E448.1020506@compuscan.co.za> References: <4EC4DD48.5090801@compuscan.co.za> <4EC4E448.1020506@compuscan.co.za> Message-ID: > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > sum(1 if type(elem) == list else 0 for elem in list1) not work for you if > all you want to do is count how many lists you have in your main list ? > > not count how many sublists in the main list. > > wanna count the occurence of the sublists, > > I mean, something like > > dictionary[list1[1]]=occurence > > Traceback (most recent call last): > File "", line 1, in > dictionary[list1[1]]=1 > TypeError: unhashable type: 'list' > > dictionary[list1[1]]=1 > > Traceback (most recent call last): > File "", line 1, in > dictionary[list1[1]]=1 > TypeError: unhashable type: 'list' > > > For that you'll need to convert your list to a hash-able type if you want to > use dictionaries for your store, easiest would probably to use the string > representation for it so you could do > >>>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], >>>> ['61', '70', '61', '34'], ['34', '58', '34', '58']] >>>> weight = {} >>>> for elem in list1: > ...?? if elem.__repr__() in weight: This is cool. May I ask which role the __repr__ plays here? > ...??? ?? weight[elem.__repr__()] += 1 > ...?? else: > ...??? ?? weight[elem.__repr__()] = 1 > ... >>>> weight > {"['34', '58', '34', '58']": 1, "['61', '70', '61', '34']": 1, "['61', '34', > '61 > ', '34']": 1, "['61', '35', '61', '70', '61']": 1} > > or > >>>> from collections import defaultdict >>>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], >>>> ['61', '7 > 0', '61', '34'], ['34', '58', '34', '58']] >>>> weight = defaultdict(int) >>>> for elem in list1: > ...???? weight[elem.__repr__()] += 1 > ... >>>> weight > defaultdict(, {"['34', '58', '34', '58']": 1, "['61', '70', > '61', '34']": 1, "['61', '34', '61', '34']": 1, "['61', '35', '61', '70', > '61']": 1}) > > Hope that helps. > > -- > > Christian Witts > Python Developer > From lina.lastname at gmail.com Thu Nov 17 15:04:16 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 17 Nov 2011 22:04:16 +0800 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: <4EC4FB46.2010303@pearwood.info> References: <4EC4FB46.2010303@pearwood.info> Message-ID: On Thu, Nov 17, 2011 at 8:17 PM, Steven D'Aprano wrote: > lina wrote: >> >> list1 >> [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', >> '70', '61', '34'], ['34', '58', '34', '58']] > > You have a list of lists. > > >>>>> weight={} >>>>> weight{list1[0]}=1 >> >> SyntaxError: invalid syntax > > In Python, {} are used for dicts, and in Python 3, sets. They aren't used > for anything else. obj{...} is illegal syntax. > > >>>>> weight[list1[0]]=1 >> >> Traceback (most recent call last): >> ?File "", line 1, in >> ? ?weight[list1[0]]=1 >> TypeError: unhashable type: 'list' > > You are trying to store a list as a key inside a dict. This cannot be done > because lists (like all mutable types) can't be hashed. I checked online dictionary, still confused about hashed. is it equal to mix together or mess together? > > If your list of lists is small, say, less than a few thousand items, it > would be fast enough to do this: > > counts = [] > seen = [] > for sublist in list1: > ? ?if sublist in seen: > ? ? ? ?# No need to do it again. > ? ? ? ?continue > ? ?seen.append(sublist) > ? ?counts.append( (sublist, list1.count(sublist)) ) Thanks, can I print the counts based on its value? > > > If I run this code on your list1, I get these counts: > > [(['61', '34', '61', '34'], 1), (['61', '35', '61', '70', '61'], 1), (['61', > '70', '61', '34'], 1), (['34', '58', '34', '58'], 1)] > > > That is, each list is unique. > > However, if you have many thousands of items, the above may be too slow. It > is slow because of all the linear searches: "sublist in seen" searches seen > for the sublist, one item at a time, and "list1.count(sublist)" searches > list1 for sublist, also one item at a time. If there are many items, this > will be slow. > > To speed it up, you can do this: > > (1) Keep the seen list sorted, and use binary search instead of linear > search. See the bisect module for help. > > (2) Sort list1, and write your own smarter count() function that doesn't > have to travel along the entire list. > > > All that involves writing a lot of code though. Probably much faster would > be to make a temporary copy of list1, with the inner lists converted to > tuples: > > > list2 = [tuple(l) for l in list1] > counts = {} > for t in list2: > ? ?counts[t] = 1 + counts.get(t, 0) > > for t, n in counts.items(): > ? ?print list(t), n > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at pearwood.info Thu Nov 17 15:09:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Nov 2011 01:09:58 +1100 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4DD48.5090801@compuscan.co.za> <4EC4E448.1020506@compuscan.co.za> Message-ID: <4EC515B6.2030103@pearwood.info> lina wrote: > May I ask which role the __repr__ plays here? > ... weight[elem.__repr__()] += 1 >> ... else: >> ... weight[elem.__repr__()] = 1 >> ... You should never call elem.__repr__(), any more than you would call elem.__len__() or elem.__str__(). (Well, technically there *are* rare uses for calling such double underscore special methods directly, but this is not one of them!) Instead, you should call repr(elem), len(elem), str(elem). The purpose here is to convert the sublist, elem, which is unhashable, into something which is hashable. Strings are hashable, and so if you use repr() to convert it into a string, you can use it in a dictionary. I don't see any advantage to using repr() instead of str(). Given the data you are working with, there is no difference: py> str([['1', '2'], ['33', '44']]) "[['1', '2'], ['33', '44']]" py> repr([['1', '2'], ['33', '44']]) "[['1', '2'], ['33', '44']]" In my opinion, turning objects into strings unnecessarily is not good practice. Better to use a tuple than a string. -- Steven From steve at pearwood.info Thu Nov 17 15:11:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Nov 2011 01:11:00 +1100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4EC515F4.8070406@pearwood.info> Nidian Job-Smith wrote: > Hi all, > I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to programme rot13. > I've written some code but it doesn't seem to work.... > Here it is: > > def rot13(s): char_low = () result = "" if not s.isalpha(): return char char_low = char_low.lower() if char_low <= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) def rot13_char(ch): return ''.join( rot13(s) for char in ch ) > Any idea where i'm wrong? Hi Nidian, If possible, please send code as plain text emails, not so-called "rich-text" (actually HTML), as it tends to mangle the formatting and make it almost impossible to decipher for some people. Also, please choose a meaningful subject line, to make it easier for people to follow the conversation. Some comments on your code, if I have re-created the formatting correctly. (1) You seem to have mixed up strings and characters. You have a function called "rot13" with an argument called "s" (for "string"), but it is intended to operate on a single character. On the other hand, you have a function called "rot13_char" with an argument "ch" (for "character"), but it operates on an entire string! You should reverse them: rot13(s) => apply rot13 to an entire string, s rot13_char(c) => apply rot13 to a single character, c (2) You have a lot of inconsistent variable names. For example, in your version of "rot13_char" (which actually operates on an entire string, not a character), you have: def rot13_char(ch): return ''.join( rot13(s) for char in ch ) Inside the join(), you have a loop "for char in ch" (for character in character???) but then you refer to "s". This should be written as: def rot13(string): return ''.join(rot13_char(char) for char in string) Likewise in the "rot13" function (better named rot13_char), you inconsistently refer to variables by different names. You must be consistent. Does that give you enough hints to continue? If not, ask any more questions you like! -- Steven From cwitts at compuscan.co.za Thu Nov 17 15:12:45 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 17 Nov 2011 16:12:45 +0200 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4DD48.5090801@compuscan.co.za> <4EC4E448.1020506@compuscan.co.za> Message-ID: <4EC5165D.9040501@compuscan.co.za> On 2011/11/17 03:56 PM, lina wrote: > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> sum(1 if type(elem) == list else 0 for elem in list1) not work for you if >> all you want to do is count how many lists you have in your main list ? >> >> not count how many sublists in the main list. >> >> wanna count the occurence of the sublists, >> >> I mean, something like >> >> dictionary[list1[1]]=occurence >> >> Traceback (most recent call last): >> File "", line 1, in >> dictionary[list1[1]]=1 >> TypeError: unhashable type: 'list' >> >> dictionary[list1[1]]=1 >> >> Traceback (most recent call last): >> File "", line 1, in >> dictionary[list1[1]]=1 >> TypeError: unhashable type: 'list' >> >> >> For that you'll need to convert your list to a hash-able type if you want to >> use dictionaries for your store, easiest would probably to use the string >> representation for it so you could do >> >>>>> list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], >>>>> ['61', '70', '61', '34'], ['34', '58', '34', '58']] >>>>> weight = {} >>>>> for elem in list1: >> ... if elem.__repr__() in weight: > This is cool. > > May I ask which role the __repr__ plays here? > > __repr__ is the string representation of a Python object [1] so I'm using it to create something that is hash-able to be used as the dictionary key value. [1] http://docs.python.org/library/functions.html#repr -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Nov 17 15:16:03 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 17 Nov 2011 14:16:03 +0000 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> Message-ID: Hi Lina On 17 November 2011 14:04, lina wrote: > >> Traceback (most recent call last): > >> File "", line 1, in > >> weight[list1[0]]=1 > >> TypeError: unhashable type: 'list' > > > > You are trying to store a list as a key inside a dict. This cannot be > done > > because lists (like all mutable types) can't be hashed. > > I checked online dictionary, still confused about hashed. is it equal > to mix together or mess together? > No.... you need to think programming/computer science where hash/hashing has a different meaning. See wikipedia: http://en.wikipedia.org/wiki/Hash_function http://en.wikipedia.org/wiki/Hash_table Also see the description for "hashable" in the Python glossary: http://docs.python.org/glossary.html#hashable Basically hashing is a way to convert something (often a string) into an identifying number (not neccesarily but usually unique) in order to use this number as a token for the original thing. Aside, you can infer that that because the "dict" code complains about hashing implies that dicts themselves are essentially implemented as hash tables... ;) HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 17 15:32:56 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 17 Nov 2011 22:32:56 +0800 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> Message-ID: Thanks for all. Everything new to me is so amazing. Well, still a remaining question, how to sort based on the value of the key. Actually I googled hours ago, wanna see more ways of doing it. Best regards, > > On 17 November 2011 14:04, lina wrote: >> >> >> Traceback (most recent call last): >> >> ?File "", line 1, in >> >> ? ?weight[list1[0]]=1 >> >> TypeError: unhashable type: 'list' >> > >> > You are trying to store a list as a key inside a dict. This cannot be >> > done >> > because lists (like all mutable types) can't be hashed. >> >> I checked online dictionary, still confused about hashed. is it equal >> to mix together or mess together? > > No.... you need to think programming/computer science where hash/hashing has > a different meaning.? See wikipedia: > http://en.wikipedia.org/wiki/Hash_function > http://en.wikipedia.org/wiki/Hash_table > > Also see the description for "hashable" in the Python glossary: > http://docs.python.org/glossary.html#hashable > > Basically hashing is a way to convert something (often a string) into an > identifying number (not neccesarily but usually unique) in order to use this > number as a token for the original thing.? Aside, you can infer that that > because the "dict" code complains about hashing implies that dicts > themselves are essentially implemented as hash tables... ;) > > HTH, > > Walter > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From steve at pearwood.info Thu Nov 17 15:44:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Nov 2011 01:44:48 +1100 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> Message-ID: <4EC51DE0.2070407@pearwood.info> lina wrote: >> You are trying to store a list as a key inside a dict. This cannot be done >> because lists (like all mutable types) can't be hashed. > > I checked online dictionary, still confused about hashed. is it equal > to mix together or mess together? Almost. In ordinary English, a hash is a mixed up mess. For example, "hash browns" are fried mashed potato. In computing, a hash got its name by analogy with "mixed up". A hash is short for "hash table". An ordinary table might look something like this: Position Value 1 "Fred" 2 "Barney" 3 "George" 4 "Betty" 5 "Mary" 6 *unused* 7 *unused* 8 *unused* 9 *unused* To find whether "Mary" is in the table, you have to start at position 1, and inspect each value to see whether it equals "Mary": for position 1 to 9: if value at position == "Mary": print FOUND If there are many items, this will be slow. But here's a faster way, using a "hash table": Position Value 1 *unused* 2 "Barney" 3 *unused* 4 "Betty" 5 *unused* 6 *unused* 7 "Fred" 8 "Mary" 9 "George" Take the string "Mary", and mix it up into a "hash value" between 1 and 9. In this case, you will get 8. Look in position 8, and you will find "Mary". Take the string "Susan" and mix it up into a hash value. In this case, you might get 3. Since position 3 is actually unused, you know that "Susan" is not in the hash table. All the hard work is done in the "mixing" of the string. This is called a hash function, and Python already has one: py> hash("Mary") -1963774307 py> hash("Susan") 92926151 If you change just one letter of the string, the hash can change a lot: py> hash("abcdef") -33722981 py> hash("bbcdef") -508939398 But lists are not hashable, because they are mutable (can be changed): py> hash([1, 2, 3]) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' Python dictionaries are hash tables. You could have a million items in a dict, and to check whether "Mary" is one of them with a list would require you to check all one million items. But with a dict, Python hashes the string to get a number, then reduces that number to fit within the range of positions in the dict, then looks immediately in the right spot to find "Mary". -- Steven From o0MB0o at hotmail.se Thu Nov 17 15:57:17 2011 From: o0MB0o at hotmail.se (Mic) Date: Thu, 17 Nov 2011 15:57:17 +0100 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: From: Wayne Werner Sent: Wednesday, November 16, 2011 8:38 PM To: Mic Cc: tutor at python.org Subject: Re: [Tutor] Clock in tkinter? On Wed, Nov 16, 2011 at 11:44 AM, Mic wrote: I wonder if you have any suggestions regarding how to place widgets in my window. Even though I try to arrange them as orderly as possible they get placed at all different kind of places in the window. I use the grid method and place them in the window by using row=something and column=something. It just doesn?t look good. It looks okay I suppose, but not as good as I want it to look. http://twitpic.com/2t4n9q/full http://twitpic.com/2t4n9p/full Those images might help you understand a little bit more about the grid layout. So if I got it right. Inside the constructor (__init__) I should declare: self.the_time=?? Then, if I understood it right, I should also place the function call there? self.update_time() as you refered to? Your constructor should look something like this: def __init__(self): #Your call to super self.the_time = '' # your other code self.update_time() I don't know for sure that it will work, but I expect that it will. HTH, Wayne Okay, to begin with, I hope I am replying correctly now. I will work to get my code into the constructor instead of having them in the global scope. Thanks for the pictures, I have now manged to organize the widgets in a much better way. I wonder, how do I add a background picture to my GUI window? So far, I thought I could make a label that is as large as the entire window, and then add a picture to it. The other widgets are supposed to be placed on top of the picture. But I am lost on how to accomplish this. Can you point me in the right direction to solve this? Mic -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Nov 17 15:55:27 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 17 Nov 2011 14:55:27 +0000 Subject: [Tutor] binary file query In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47401EC9C@SCACMX007.exchad.jpmchase.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF4740236D1@SCACMX007.exchad.jpmchase.net> -----Original Message----- From: Shirkhedkar, Dhanashri [mailto:Dhanashri.Shirkhedkar at Honeywell.com] Sent: Wednesday, November 16, 2011 10:58 PM To: Prasad, Ramit Subject: RE: binary file query Thanks for replying. It means that no need to use the 'Struct' module for binary file read, right? =================================================================== Please reply to the list (or use reply-all). It really depends on your file. The struct module says, "This module performs conversions between Python values and C structs represented as Python strings." If your file is not a C-struct data then no need to use the struct module. For every other kind of binary data, use a library suited to that file if it exists. Otherwise you can read the raw data by just opening the file in binary mode as I shows in my previous email. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From waynejwerner at gmail.com Thu Nov 17 16:15:20 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 17 Nov 2011 09:15:20 -0600 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: On Thu, Nov 17, 2011 at 8:57 AM, Mic wrote: > > > Okay, to begin with, I hope I am replying correctly now. > Better, though there was quite a lot of my email that you could have removed. > > I wonder, how do I add a background picture to my GUI window? > > So far, I thought I could make a label that is as large as the > entire window, and then add a picture to it. The other widgets > are supposed to be placed on top of the picture. > > But I am lost on how to accomplish this. Can you point me in the > right direction to solve this? > If you want to do this, I would recommend using the place (as opposed to pack or grid) manager inside of a frame widget. Use that to place your image, and another frame that contains your other widgets - I would use the pack or grid layout inside this other frame, though. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Nov 17 16:30:31 2011 From: lina.lastname at gmail.com (lina) Date: Thu, 17 Nov 2011 23:30:31 +0800 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: <4EC51DE0.2070407@pearwood.info> References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info> Message-ID: On Thu, Nov 17, 2011 at 10:44 PM, Steven D'Aprano wrote: > lina wrote: > >>> You are trying to store a list as a key inside a dict. This cannot be >>> done >>> because lists (like all mutable types) can't be hashed. >> >> I checked online dictionary, still confused about hashed. is it equal >> to mix together or mess together? > > Almost. > > In ordinary English, a hash is a mixed up mess. For example, "hash browns" > are fried mashed potato. > > In computing, a hash got its name by analogy with "mixed up". A hash is > short for "hash table". > > An ordinary table might look something like this: > > > Position ?Value > 1 ? ? ? ? "Fred" > 2 ? ? ? ? "Barney" > 3 ? ? ? ? "George" > 4 ? ? ? ? "Betty" > 5 ? ? ? ? "Mary" > 6 ? ? ? ? *unused* > 7 ? ? ? ? *unused* > 8 ? ? ? ? *unused* > 9 ? ? ? ? *unused* > > > To find whether "Mary" is in the table, you have to start at position 1, and > inspect each value to see whether it equals "Mary": > > for position 1 to 9: > ? ?if value at position == "Mary": print FOUND > > > If there are many items, this will be slow. But here's a faster way, using a > "hash table": > > Position ?Value > 1 ? ? ? ? *unused* > 2 ? ? ? ? "Barney" > 3 ? ? ? ? *unused* > 4 ? ? ? ? "Betty" > 5 ? ? ? ? *unused* > 6 ? ? ? ? *unused* > 7 ? ? ? ? "Fred" > 8 ? ? ? ? "Mary" > 9 ? ? ? ? "George" > > Take the string "Mary", and mix it up into a "hash value" between 1 and 9. > In this case, you will get 8. Look in position 8, and you will find "Mary". > > Take the string "Susan" and mix it up into a hash value. In this case, you > might get 3. Since position 3 is actually unused, you know that "Susan" is > not in the hash table. > > > All the hard work is done in the "mixing" of the string. This is called a > hash function, and Python already has one: > > py> hash("Mary") > -1963774307 > py> hash("Susan") > 92926151 > > > If you change just one letter of the string, the hash can change a lot: > > > py> hash("abcdef") > -33722981 > py> hash("bbcdef") > -508939398 > > > But lists are not hashable, because they are mutable (can be changed): > > py> hash([1, 2, 3]) > Traceback (most recent call last): > ?File "", line 1, in > TypeError: unhashable type: 'list' > > > Python dictionaries are hash tables. You could have a million items in a > dict, and to check whether "Mary" is one of them with a list would require > you to check all one million items. But with a dict, Python hashes the > string to get a number, then reduces that number to fit within the range of > positions in the dict, then looks immediately in the right spot to find > "Mary". > Really appreciated for your detailed explaination. Right now I wanna check which are not hash-able, for strings, set, and tuple (which I don't understand). Seems string is hash-able. Just another quick Q: >>> basket ['apple', 'pineapple', 'apple', 'pear'] >>> hash(basket[1]) -8771120720059735049 >>> hash(basket[2]) 6709291584508918021 >>> print(id(basket)) 29215848 >>> print(id(basket[1])) 27389096 What are those numbers means? Sorry, > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at pearwood.info Thu Nov 17 18:35:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Nov 2011 04:35:18 +1100 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info> Message-ID: <4EC545D6.3010308@pearwood.info> lina wrote: > Right now I wanna check which are not hash-able, for strings, set, and > tuple (which I don't understand). Mutable objects are those that can be changed in place: lists, sets, dicts are all mutable, because you can change them: >>> mylist = [1, 2, 3] >>> mylist[1] = 200 >>> print mylist [1, 200, 3 Mutable objects are not hashable. Immutable objects are those that cannot be changed in place: you have to create a new object. Tuples, frozensets, strings, ints, floats are all immutable. They are hashable. > Seems string is hash-able. > > Just another quick Q: > >>>> basket > ['apple', 'pineapple', 'apple', 'pear'] > >>>> hash(basket[1]) > -8771120720059735049 >>>> hash(basket[2]) > 6709291584508918021 The number doesn't mean anything. It's just a number. It gets used by dictionaries for fast searching, but that's all. This might help you understand. Here is a very simple hash function that takes a string and mixes it up to make a number. It isn't very good, it is a terrible hash function, but it is simple! The Python one is better, but this will give you an idea of how they work: def my_hash(string): num = 102345 # some random number I just made up for c in string: num = (num*17 + ord(c)*9) % 3200 return num Designing a good hash function is very hard. >>>> print(id(basket)) > 29215848 >>>> print(id(basket[1])) > 27389096 The id() of an object is just an identity number. Do you have a passport or driver's licence? Or a social security number? That is like your ID. It identifies you. Nobody else can have the same ID at the same time. In CPython, IDs are large numbers, and they are re-usable. If you delete an object, another object can get the same ID later on. In Jython and IronPython, IDs start counting at 1 and increase with every object created. Used IDs are never reused. IDs aren't important. In 15 years of using Python, I don't think I have needed to care about the ID of an object once. -- Steven From nidianjs at hotmail.com Thu Nov 17 18:45:11 2011 From: nidianjs at hotmail.com (Nidian Job-Smith) Date: Thu, 17 Nov 2011 17:45:11 +0000 Subject: [Tutor] Rot13 In-Reply-To: <4EC515F4.8070406@pearwood.info> References: , <4EC515F4.8070406@pearwood.info> Message-ID: Hi all, I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . I've come across a beginners exercise which is to write the code for rot13. ?I've written some code but it doesn't seem to work.... When?I?run it?I?get this error: NameError: global name 'rot13_char' is not defined Here it is:? def rot13(s):? ? char_low = ()? ? result = ""? ? if not s.isalpha():? ? ? ? return char? ? char_low = char_low.lower()? ? if char_low <= 'm':? ? ? ? ? ? ? ? dist = 13? ? else:? ? ? ? ? ? ? ? dist = -13? ? char = chr(ord(char) + dist)? ? ? ? ? ? ?def rot13(string):? return ''.join( rot13_char(char)for char in string ) Any ideas where i'm wrong?? Huge thanks, Nidian From nidianjs at hotmail.com Thu Nov 17 18:54:54 2011 From: nidianjs at hotmail.com (Nidian Job-Smith) Date: Thu, 17 Nov 2011 17:54:54 +0000 Subject: [Tutor] Rot13 In-Reply-To: References: , , <4EC515F4.8070406@pearwood.info>, Message-ID: Sorry about the code format in last E-mail. I'll attach the code in notepad, as my e-mail doesnt seem to like sending plain text.. ---------------------------------------- > From: nidianjs at hotmail.com > To: steve at pearwood.info; tutor at python.org > Date: Thu, 17 Nov 2011 17:45:11 +0000 > Subject: [Tutor] Rot13 > > > Hi all, > > I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . > I've come across a beginners exercise which is to write the code for rot13. I've written some code but it doesn't seem to work.... > When I run it I get this error: > > > NameError: global name 'rot13_char' is not defined > > > Here it is: > > > > def rot13(s): char_low = () result = "" if not s.isalpha(): return char char_low = char_low.lower() if char_low <= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) def rot13(string): return ''.join( rot13_char(char)for char in string ) > > > > > Any ideas where i'm wrong? > > Huge thanks, > Nidian > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: rot13_code.txt URL: From steve at pearwood.info Thu Nov 17 19:23:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Nov 2011 05:23:23 +1100 Subject: [Tutor] Rot13 In-Reply-To: References: , , <4EC515F4.8070406@pearwood.info>, Message-ID: <4EC5511B.1070208@pearwood.info> Nidian Job-Smith wrote: >> When I run it I get this error: >> >> >> NameError: global name 'rot13_char' is not defined [...] >> Any ideas where i'm wrong? You have a function called "rot13", and *another* function called "rot13", which will over-write the first one. But you have no function called "rot13_char". -- Steven From evosweet at hotmail.com Thu Nov 17 19:32:34 2011 From: evosweet at hotmail.com (Rayon) Date: Thu, 17 Nov 2011 14:32:34 -0400 Subject: [Tutor] python telnet Message-ID: From: Rayon [mailto:rayon at gtt.co.gy] Sent: 17 November 2011 14:04 To: 'tutor at python.org' Subject: python telnet I am trying to use winpexpect to connect a telnet session. I keep getting this error. raise ExceptionPexpect, 'Command not found: %s' % self.command ExceptionPexpect: Command not found: telnet ###########code############### from winpexpect import winspawn child = winspawn('telnet 192.168.0.55:210') help me plz Regards Rayon -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Nov 17 19:34:05 2011 From: d at davea.name (Dave Angel) Date: Thu, 17 Nov 2011 13:34:05 -0500 Subject: [Tutor] Rot13 In-Reply-To: References: , , <4EC515F4.8070406@pearwood.info>, Message-ID: <4EC5539D.7060300@davea.name> On 11/17/2011 12:54 PM, Nidian Job-Smith wrote: > Sorry about the code format in last E-mail. I'll attach the code in notepad, as my e-mail doesnt seem to like sending plain text.. > But attachments aren't visible to everyone on the list, and even when they are, some people are (rightfully) paranoid about arbitrarily opening attachments. You don't name your email program, but if it cannot handle text messages, perhaps you should look for another. There are many free email programs. For example, I use Thunderbird. I know it works under Windows, since I used to use it that way. But I'm currently using it under Linux. > ---------------------------------------- >> From: nidianjs at hotmail.com >> To: steve at pearwood.info; tutor at python.org >> Date: Thu, 17 Nov 2011 17:45:11 +0000 >> Subject: [Tutor] Rot13 >> >> >> Hi all, >> >> I'm new to programming (thus Python), so after reading the basics, I wanted to practise what I've learnt . >> I've come across a beginners exercise which is to write the code for rot13. I've written some code but it doesn't seem to work.... >> When I run it I get this error: >> >> >> NameError: global name 'rot13_char' is not defined >> That's not the whole error message/ How can you get this error when the file you attached never used that name ? Be sure and use cut 'n paste when telling about an error message. If you don't know how, ask, but be sure and give your environment specifics. Further, the file you attached wouldn't even try to run anything, so it couldn't get any such error, even if we concede a typo in the name. When I run it (after renaming it from a .txt extension to a .py one), I get the following: davea at think:~/temppython$ mv rot13_code-1.txt rot13_code-1.py davea at think:~/temppython$ python rot13_code-1.py davea at think:~/temppython$ Now, if I add a couple of lines to it to test it out: print rot13("abc") print rot13("XyzzY") Then I indeed get an error: davea at think:~/temppython$ python rot13_code-1.py Traceback (most recent call last): File "rot13_code-1.py", line 32, in print rot13("abc") File "rot13_code-1.py", line 30, in rot13 return ''.join( rot13_low(char)for char in string ) File "rot13_code-1.py", line 30, in return ''.join( rot13_low(char)for char in string ) NameError: global name 'rot13_low' is not defined Guess what, you had two functions with the same name. So the first one disappears. Apparently you wanted to name it rot13_low(): def rot13_low(s): Now, when I run it, I get: davea at think:~/temppython$ python rot13_code-1.py Traceback (most recent call last): File "rot13_code-1.py", line 32, in print rot13("abc") File "rot13_code-1.py", line 30, in rot13 return ''.join( rot13_low(char)for char in string ) File "rot13_code-1.py", line 30, in return ''.join( rot13_low(char)for char in string ) File "rot13_code-1.py", line 22, in rot13_low char_low = char_low.lower() AttributeError: 'tuple' object has no attribute 'lower' No idea why you created a tuple called char_low. My guess is that you meant the formal parameter of the first function to be char_low, since calling it s would be misleading. It's intended to be a single character, not a string. Anyway, you can presumably see the process. Look at the whole error traceback, and if you can't see what it means, ask for help. BTW, the docstring you have for the first function belongs in the second one. That first function doesn't deal with strings. -- DaveA From kellyadrian at hotmail.com Thu Nov 17 19:47:07 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 17 Nov 2011 18:47:07 +0000 Subject: [Tutor] local variable referenced before assignment Message-ID: hi all,keep getting the above error, can't understand or fix it, can anyone help. def exchange(): euro=1 dollar=1.35 base=50 amount = input ('how much do you want to change') if amount>base: totalreturn=amount*dollar else: print 'not enough' return totalreturn print exchange() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Nov 17 19:53:00 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 17 Nov 2011 18:53:00 +0000 Subject: [Tutor] local variable referenced before assignment In-Reply-To: References: Message-ID: <424265233-1321555980-cardhu_decombobulator_blackberry.rim.net-1110719749-@b18.c12.bise7.blackberry> Post the error stack. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: ADRIAN KELLY Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 17 Nov 2011 18:47:07 To: Subject: [Tutor] local variable referenced before assignment _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From joel.goldstick at gmail.com Thu Nov 17 20:01:41 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 17 Nov 2011 14:01:41 -0500 Subject: [Tutor] local variable referenced before assignment In-Reply-To: <424265233-1321555980-cardhu_decombobulator_blackberry.rim.net-1110719749-@b18.c12.bise7.blackberry> References: <424265233-1321555980-cardhu_decombobulator_blackberry.rim.net-1110719749-@b18.c12.bise7.blackberry> Message-ID: On Thu, Nov 17, 2011 at 1:53 PM, wrote: > Post the error stack. > Sent from my BlackBerry wireless device from MTN > > -----Original Message----- > From: ADRIAN KELLY > Sender: tutor-bounces+delegbede=dudupay.com at python.org > Date: Thu, 17 Nov 2011 18:47:07 > To: > Subject: [Tutor] local variable referenced before assignment > > _______________________________________________ > 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 > if amount>base: totalreturn=amount*dollar else: print 'not enough' return totalreturn Notice if amount isn't more than base totalreturn is not created, so the else clause executes and totalreturn doesn't exist -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Nov 17 20:01:19 2011 From: d at davea.name (Dave Angel) Date: Thu, 17 Nov 2011 14:01:19 -0500 Subject: [Tutor] local variable referenced before assignment In-Reply-To: References: Message-ID: <4EC559FF.2030808@davea.name> On 11/17/2011 01:47 PM, ADRIAN KELLY wrote: > hi all,keep getting the above error, can't understand or fix it, can anyone help. > def exchange(): euro=1 dollar=1.35 base=50 amount = input ('how much do you want to change') if amount>base: totalreturn=amount*dollar else: print 'not enough' return totalreturn > print exchange() > > You've been doing better, but this one has lost its formatting entirely. Are you posting in text mode? That's not the entire error message. If you examined the entire traceback, it'd identify the line with the problem, and the particular variable that's being used before it's been defined. But since the function is small, i can guess my way through. The variable is apparently "totalreturn". And when you go through the else clause you completely miss the assignment to it. When you have a mechanism like: if x > y: newval = 49 else: print "error message" #newval = -5 return newval Without that second assignment, you'll get "the above error" whenever the else condition prevails. newval has no value, and in fact doesn't exist if you go through the else clause. -- DaveA From __peter__ at web.de Thu Nov 17 20:03:03 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 17 Nov 2011 20:03:03 +0100 Subject: [Tutor] how to understand unhashable type: 'list' References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info> <4EC545D6.3010308@pearwood.info> Message-ID: Steven D'Aprano wrote: > Immutable objects are those that cannot be changed in place: you have to > create a new object. Tuples, frozensets, strings, ints, floats are all > immutable. They are hashable. Tuples are special: there are hashable and unhashable tuples. To be hashable all items in a tuple have to be hashable: >>> a = 1, 2 >>> hash(a) 3713081631934410656 >>> b = 1, [] >>> hash(b) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'list' Instances of custom classes are special, too; by default they are hashable and mutable. That is possible without messing things up too much because instead of the instance's data they use its id() to calculate the hash value (and object equality). This is obvious in older Python versions like Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class A: pass ... >>> a = A() >>> id(a) 140312106243352 >>> hash(a) 140312106243352 >>> id(a) == hash(a) True but the principle also applies in 2.7 and 3.1 and above. From o0MB0o at hotmail.se Thu Nov 17 20:17:53 2011 From: o0MB0o at hotmail.se (Mic) Date: Thu, 17 Nov 2011 20:17:53 +0100 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: If you're going to put a function inside your class (since you're using self in there, I'm sure that's what you meant to do), you should change it to: def change_value_the_time(self): and call it with self.display_time.after(20, self.change_value_the_time) But your program also has unnecessary code. First, since you have a class then instead of using a global, you should simply declare `self.the_time = ''` in your __init__ for your class. Personally, I would have written the function more like this: def update_time(self): self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') self.after(20, self.update_time) Then at the end of my __init__ function I would call self.update_time() I'm not sure how that will work with your current setup, though. ------------------------------------------------------------------------------------------------------------------------------------- I have now worked to stop using the global scope and instead put my prior global variable into the constructor in the class. I believe that I have managed to do that now. Do you believe that this is correctly done? #Trying putting the_time'' in constructor instead of #putting it in the global scope to shorten code. from tkinter import* import time import os class Window(Frame): def __init__(self,master): super (Window,self).__init__(master) self.grid() self.the_time='' self.create_widgets() self.update_time() def create_widgets(self): #Create a hello Button: self.hellobttn=Button(self, text="Hey") self.hellobttn.grid(row=0, column=1) #Create a label that displays time. self.display_time=Label(self, text=self.the_time) self.display_time.grid(row=1, column=1) def update_time(self): self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') self.after(20, self.update_time) root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() I get no error while doing this, and the program works fine. I have another question. Say that I have a class and I want to make 100 objects. Then it could look like this: #How to shorten this? #Create the class. class Chairs(object): def __init__(self, age, weight): self.age=age self.weight=weight def __str__(self): rep=self.age+self.weight return rep #Create the objects chair1=Chairs("10","20") chair2=Chairs("10","20") chair3=Chairs("10","20") chair4=Chairs("10","20") chair5=Chairs("10","20") chair6=Chairs("10","20") chair7=Chairs("10","20") chair8=Chairs("10","20") chair9=Chairs("10","20") #And so on How do I shorten this? I have thought of using a for sling. I have looked in my programming book and on the internet, but I don?t know how to make this shorter. The arguements (?10?, ?20?) should be the same for every object, which should make it easier than if they were different each time? Right now, it feels like a lot of my code in my other programs could be made dramatically shorter. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Thu Nov 17 20:19:06 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 17 Nov 2011 19:19:06 +0000 Subject: [Tutor] local variable referenced before assignment In-Reply-To: <4EC559FF.2030808@davea.name> References: , <4EC559FF.2030808@davea.name> Message-ID: you are spot on......... thanks very much i understand the problem now and its been solved. very clear help thanks, adrian > Date: Thu, 17 Nov 2011 14:01:19 -0500 > From: d at davea.name > To: kellyadrian at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] local variable referenced before assignment > > On 11/17/2011 01:47 PM, ADRIAN KELLY wrote: > > hi all,keep getting the above error, can't understand or fix it, can anyone help. > > def exchange(): euro=1 dollar=1.35 base=50 amount = input ('how much do you want to change') if amount>base: totalreturn=amount*dollar else: print 'not enough' return totalreturn > > print exchange() > > > > > You've been doing better, but this one has lost its formatting > entirely. Are you posting in text mode? > > That's not the entire error message. If you examined the entire > traceback, it'd identify the line with the problem, and the particular > variable that's being used before it's been defined. > > > But since the function is small, i can guess my way through. The > variable is apparently "totalreturn". And when you go through the else > clause you completely miss the assignment to it. When you have a > mechanism like: > > if x > y: > newval = 49 > else: > print "error message" > #newval = -5 > return newval > > Without that second assignment, you'll get "the above error" whenever > the else condition prevails. newval has no value, and in fact doesn't > exist if you go through the else clause. > > > -- > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Nov 17 20:30:52 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 17 Nov 2011 13:30:52 -0600 Subject: [Tutor] Clock in tkinter? In-Reply-To: References: Message-ID: On Thu, Nov 17, 2011 at 1:17 PM, Mic wrote: > I have now worked to stop using the global scope and instead put my > prior global variable into > the constructor in the class. I believe that I have managed to do that now. > > Do you believe that this is correctly done? > > > #Trying putting the_time'' in constructor instead of > #putting it in the global scope to shorten code. > > > def update_time(self): > self.display_time.config(text=time.strftime('%H:%M:%S'), font='40') > self.after(20, self.update_time) > Since you're using the shorter version of the function you no longer need self.the_time, so you can go ahead and remove that variable. > > I have another question. > It would have been fine (and even preferred) to create a new email here with a title something like "How do I shorten this code?" > > Say that I have a class and I want to make 100 objects. > Then it could look like this: > > class Chairs(object): > > > #Create the objects > chair1=Chairs("10","20") > chair2=Chairs("10","20") > chair3=Chairs("10","20") > > How do I shorten this? I have thought of using a for sling. I have looked > in my programming > book and on the internet, but I don?t know how to make this shorter. The > arguements (?10?, ?20?) > should be the same for every object, which should make it easier than if > they were different each time? > If you ever write a line of code more than once, it's a good sign that you have what's called a code smell. This example is very smelly code ;) What you should do instead is have a collection of chairs: chairs = [] for _ in range(100): # the underscore `_` indicates that you don't care about the value chairs.append(Chairs("10","20)) You can do that even shorter with a list comprehension, but I'll leave that exercise up to you :) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Thu Nov 17 22:19:45 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 17 Nov 2011 21:19:45 +0000 Subject: [Tutor] please help - stuck for hours Message-ID: i have tried everything, i am trying to build in a loop to my 2 functions which worked fine up until my latest sorti. please have a look if you can.............. def exchange(cash_in): euro=1 dollar=1.35 base=50 if cash_in>base: totalreturn=cash_in*dollar else: totalreturn=0 return totalreturn def main(): amount="" while amount<50: print 'Sorry, cannot convert an amount under ?50 ' amount = input('how much do you want to change:') else: total=exchange(amount) print 'Your exchange comes to: ',total main() Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, in main total=exchange(amount) File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in exchange totalreturn=cash_in*dollarTypeError: can't multiply sequence by non-int of type 'float'>>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Thu Nov 17 22:29:37 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 17 Nov 2011 21:29:37 +0000 Subject: [Tutor] infinite loop Message-ID: #i am nearly there guys..........please loop at the infinite loop i am getting here..................PLEASE!!#ADRIAN def exchange(cash_in): euro=1 dollar=float(1.35) base=50 if cash_in>base: totalreturn=cash_in*dollar else: totalreturn=0 return totalreturn amount=float()def main(): amount = float(raw_input('how much do you want to change:')) while amount<50: print 'Sorry, cannot convert an amount under ?50 ' else: total=exchange(amount) print 'Your exchange comes to: ',total main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Nov 17 22:35:29 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 17 Nov 2011 15:35:29 -0600 Subject: [Tutor] please help - stuck for hours In-Reply-To: References: Message-ID: On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY wrote: > i have tried everything, i am trying to build in a loop to my 2 functions > which worked fine up until my latest sorti. > > please have a look if you can.............. > > def exchange(cash_in): > euro=1 > dollar=1.35 > base=50 > if cash_in>base: > totalreturn=cash_in*dollar > else: > totalreturn=0 > return totalreturn > > > def main(): > amount="" > while amount<50: > print 'Sorry, cannot convert an amount under ?50 ' > amount = input('how much do you want to change:') > else: > total=exchange(amount) > print 'Your exchange comes to: ',total > > > main() > > > > Traceback (most recent call last): > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, > in > main() > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, > in main > total=exchange(amount) > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in > exchange > totalreturn=cash_in*dollar > TypeError: can't multiply sequence by non-int of type 'float' > Thank you for posting the full traceback - this last line tells you the exact problem - you're trying to multiply a sequence by a float (in this case your sequence is a string). The line right above that tells you the what you tried to do: multiply `cash_in` by `dollar`. Take a look at your code and what do you see? Well, you set `dollar = 1.35`, and you don't change the value elsewhere so that's certainly a float. What about cash_in? Well if you work your way backwards through the traceback you see that it was called with the parameter "amount". Where is amount set? Ah, on that line: amount = input() This line is extremely problematic. First, I see by your print statement that you're using Python 2.x, so input is actually executing arbitrary code. What you *want* is raw_input which returns a string and is much MUCH safer. I don't know what your input value was, but I suspect that you did something like '30' (with the quotes), because otherwise it would evaluate to an integer. It's also possible that you used `amount`, which would evaluate to "" since you already declared it. None of these things are good. Change your initial assignment to : amount = 0 and the input line to: amount = float(raw_input("How much would you like to exchange? ")) This will first get a string from the user and then convert it to a float - which I suspect you'll want, since you're dealing with monetary values. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Nov 17 22:36:35 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 17 Nov 2011 15:36:35 -0600 Subject: [Tutor] infinite loop In-Reply-To: References: Message-ID: On Thu, Nov 17, 2011 at 3:29 PM, ADRIAN KELLY wrote: > def main(): > amount = float(raw_input('how much do you want to change:')) > while amount<50: > print 'Sorry, cannot convert an amount under ?50 ' > > When do you reassign amount? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Thu Nov 17 22:49:58 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Thu, 17 Nov 2011 21:49:58 +0000 Subject: [Tutor] please help - stuck for hours In-Reply-To: References: Message-ID: <1020847580-1321566597-cardhu_decombobulator_blackberry.rim.net-1315833316-@b18.c12.bise7.blackberry> Where do you intend the variable cash_in to come from? The system doesn't know what cash_in is beyond that you mentioned it and that makes it impossible to multiply it with dollar which is a float type. If cash_in is supposed to be an input from the user, you probably should make it an int type right away before doing the multiplication. Hope this helps. Cheers. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: ADRIAN KELLY Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Thu, 17 Nov 2011 21:19:45 To: Subject: [Tutor] please help - stuck for hours _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From kellyadrian at hotmail.com Thu Nov 17 23:32:53 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 17 Nov 2011 22:32:53 +0000 Subject: [Tutor] please help - stuck for hours In-Reply-To: References: , Message-ID: thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? # -*- coding: cp1252 -*-def exchange(cash_in): euro=1 dollar=1.35 base=50 if cash_in>base: totalreturn=cash_in*dollar else: totalreturn=0 return totalreturn def main(): amount=0 while amount<50: amount = input('how much do you want to change:') print 'enter an amount over ?50: ' else: total=exchange(amount) print 'Your exchange comes to: ',total main() Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwerner at gmail.com Date: Thu, 17 Nov 2011 15:35:29 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadrian at hotmail.com CC: tutor at python.org On Thu, Nov 17, 2011 at 3:19 PM, ADRIAN KELLY wrote: i have tried everything, i am trying to build in a loop to my 2 functions which worked fine up until my latest sorti. please have a look if you can.............. def exchange(cash_in): euro=1 dollar=1.35 base=50 if cash_in>base: totalreturn=cash_in*dollar else: totalreturn=0 return totalreturn def main(): amount="" while amount<50: print 'Sorry, cannot convert an amount under ?50 ' amount = input('how much do you want to change:') else: total=exchange(amount) print 'Your exchange comes to: ',total main() Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 27, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 19, in main total=exchange(amount) File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex3.py", line 7, in exchange totalreturn=cash_in*dollar TypeError: can't multiply sequence by non-int of type 'float' Thank you for posting the full traceback - this last line tells you the exact problem - you're trying to multiply a sequence by a float (in this case your sequence is a string). The line right above that tells you the what you tried to do: multiply `cash_in` by `dollar`. Take a look at your code and what do you see? Well, you set `dollar = 1.35`, and you don't change the value elsewhere so that's certainly a float. What about cash_in? Well if you work your way backwards through the traceback you see that it was called with the parameter "amount". Where is amount set? Ah, on that line: amount = input() This line is extremely problematic. First, I see by your print statement that you're using Python 2.x, so input is actually executing arbitrary code. What you *want* is raw_input which returns a string and is much MUCH safer. I don't know what your input value was, but I suspect that you did something like '30' (with the quotes), because otherwise it would evaluate to an integer. It's also possible that you used `amount`, which would evaluate to "" since you already declared it. None of these things are good. Change your initial assignment to : amount = 0 and the input line to: amount = float(raw_input("How much would you like to exchange? ")) This will first get a string from the user and then convert it to a float - which I suspect you'll want, since you're dealing with monetary values.HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Nov 17 23:53:59 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 17 Nov 2011 16:53:59 -0600 Subject: [Tutor] please help - stuck for hours In-Reply-To: References: Message-ID: On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: > > thanks very much, great response really really appreciated it and now i > understand. i hate to ask again but can you see why it won't print the > 'enter and amount over 50' in the right place?? > Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. > > def main(): > amount=0 > while amount<50: > amount = input('how much do you want to change:') > print 'enter an amount over ?50: ' > else: > total=exchange(amount) > print 'Your exchange comes to: ',total > Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Fri Nov 18 00:12:30 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 17 Nov 2011 23:12:30 +0000 Subject: [Tutor] please help - stuck for hours In-Reply-To: References: , , Message-ID: i know i should use input but when i changed to raw_input it wouldn't recognise the word print on the next line. honestly i have tried everything to get this working..i am 6 hrs at one program Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwerner at gmail.com Date: Thu, 17 Nov 2011 16:53:59 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadrian at hotmail.com CC: tutor at python.org On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. def main(): amount=0 while amount<50: amount = input('how much do you want to change:') print 'enter an amount over ?50: ' else: total=exchange(amount) print 'Your exchange comes to: ',total Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Fri Nov 18 00:26:52 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Thu, 17 Nov 2011 23:26:52 +0000 Subject: [Tutor] urgent help!!!!!!!!!!! In-Reply-To: References: , , Message-ID: i know i'm stupid but i have tried everything to get one line of text working, i have written out pseudo and read every website.....now i am getting this error............ Traceback (most recent call last): File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 24, in main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 14, in main while amount<50:UnboundLocalError: local variable 'amount' referenced before assignment>>> def exchange(cash_in): euro=1 dollar=1.35 base=50 if cash_in>base: totalreturn=cash_in*dollar else: totalreturn=0 return totalreturn amount=0def main(): while amount<50: amount = raw_input(float('how much do you want to change:')) if amount<50: total=0 print 'enter an amount over 50: ' else: total=exchange(amount) print 'Your exchange comes to: ',total Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwerner at gmail.com Date: Thu, 17 Nov 2011 16:53:59 -0600 Subject: Re: [Tutor] please help - stuck for hours To: kellyadrian at hotmail.com CC: tutor at python.org On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY wrote: thanks very much, great response really really appreciated it and now i understand. i hate to ask again but can you see why it won't print the 'enter and amount over 50' in the right place?? Computers are unfailingly stupid machines. They will do whatever wrong thing you tell them to do every single time. def main(): amount=0 while amount<50: amount = input('how much do you want to change:') print 'enter an amount over ?50: ' else: total=exchange(amount) print 'Your exchange comes to: ',total Sometimes it helps writing out the logic in steps before you translate it to code. In this case my guess is that these are the steps you want: 1. Get a value from the user (you're still using input - stop that, it's dangerous! input is only a good function in 3.x where it replaces raw_input) 2. If the value is less than 50, tell the user to enter an amount > 50 and repeat step 1 3. Otherwise, exchange the amount and display that. Right now, these are the steps that you're doing: 1. Get a value from the user 2. Display the error message 3. If the value is < 50, go to 1 4. exchange the amount 5. display the amount. HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 18 00:39:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Nov 2011 23:39:11 +0000 Subject: [Tutor] binary file query In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4740236D1@SCACMX007.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47401EC9C@SCACMX007.exchad.jpmchase.net> <5B80DD153D7D744689F57F4FB69AF4740236D1@SCACMX007.exchad.jpmchase.net> Message-ID: On 17/11/11 14:55, Prasad, Ramit wrote: > It means that no need to use the 'Struct' module for binary file read, > right? Its not necessary but if the data does not already have a file handling module then the struct module is a very convenient way of accessing the data. > It really depends on your file. The struct module says, "This module > performs conversions between Python values and C structs represented > as Python strings." If your file is not a C-struct data then no need > to use the struct module. No *need* but, often convenient, regardless of whether the data was written by a C struct or not.(*) It is a way to interpret binary data in terms of fundamental data types such as ints, floats, strings etc. Trying to convert raw bytes representing floats into a floating point number without using struct would be an interesting exercise. Using struct it's trivial. Struct works with any kind of basic binary data provided you know what the byte sequence represents. Where it breaks down is when it represents more complex concepts like references to objects and even graphical bitmaps etc. That's where dedicated file handling modules come into play. (*)The struct docs acknowledge this with the following comment: "To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details." -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mehgcap at gmail.com Fri Nov 18 00:39:41 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 17 Nov 2011 18:39:41 -0500 Subject: [Tutor] urgent help!!!!!!!!!!! In-Reply-To: References: Message-ID: My mail client stripped new lines, at least on this machine, so I will just top-post this. Sorry! Your problem is that you say: amount=0 def main()... You then try to use amount in main, but main has no amount in it. Either move "amount=0" inside main, or put a global reference: amount=0 def main(): global amount ... On 11/17/11, ADRIAN KELLY wrote: > > i know i'm stupid but i have tried everything to get one line of text > working, i have written out pseudo and read every website.....now i am > getting this error............ > Traceback (most recent call last): File "F:\VTOS > ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", line 24, in > main() File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - > Copy.py", line 14, in main while amount<50:UnboundLocalError: local > variable 'amount' referenced before assignment>>> > > > def exchange(cash_in): euro=1 dollar=1.35 base=50 if > cash_in>base: totalreturn=cash_in*dollar else: > totalreturn=0 return totalreturn > amount=0def main(): while amount<50: amount = raw_input(float('how > much do you want to change:')) if amount<50: total=0 print > 'enter an amount over 50: ' else: total=exchange(amount) > print 'Your exchange comes to: ',total > > > > > Adrian Kelly > 1 Bramble Close > > Baylough > > Athlone > > County Westmeath > > 0879495663 > > > From: waynejwerner at gmail.com > Date: Thu, 17 Nov 2011 16:53:59 -0600 > Subject: Re: [Tutor] please help - stuck for hours > To: kellyadrian at hotmail.com > CC: tutor at python.org > > On Thu, Nov 17, 2011 at 4:32 PM, ADRIAN KELLY > wrote: > > > > > > > > > thanks very much, great response really really appreciated it and now i > understand. i hate to ask again but can you see why it won't print the > 'enter and amount over 50' in the right place?? > > > Computers are unfailingly stupid machines. They will do whatever wrong thing > you tell them to do every single time. > > def main(): amount=0 while amount<50: amount = > input('how much do you want to change:') > > print 'enter an amount over ?50: ' else: > total=exchange(amount) print 'Your exchange comes to: ',total > > > Sometimes it helps writing out the logic in steps before you translate it to > code. In this case my guess is that these are the steps you want: > 1. Get a value from the user (you're still using input - stop that, it's > dangerous! input is only a good function in 3.x where it replaces > raw_input) > > 2. If the value is less than 50, tell the user to enter an amount > 50 > and repeat step 1 > 3. Otherwise, exchange the amount and display that. > Right now, these are the steps that you're doing: > > > 1. Get a value from the user > 2. Display the error message > 3. If the value is < 50, go to 1 > 4. exchange the amount > > > 5. display the amount. > HTH,Wayne -- 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 Nov 18 00:51:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 18 Nov 2011 10:51:33 +1100 Subject: [Tutor] python telnet In-Reply-To: References: Message-ID: <4EC59E05.7050106@pearwood.info> Rayon wrote: > I am trying to use winpexpect to connect a telnet session. > I keep getting this error. > > > > raise ExceptionPexpect, 'Command not found: %s' % self.command > ExceptionPexpect: Command not found: telnet Please copy and paste the entire traceback, not just the last couple of lines. But judging by just the small bit you show, it looks like "telnet" is not a command that winpexpect understands, so it raises an error "command not found". Perhaps it is a bug in winpexpect. Are you using the latest version? Do you actually have telnet available on your system? If not, then you can't expect winpexpect to use something which isn't there. -- Steven From alan.gauld at btinternet.com Fri Nov 18 00:56:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 17 Nov 2011 23:56:28 +0000 Subject: [Tutor] please help - stuck for hours In-Reply-To: References: , , Message-ID: On 17/11/11 23:12, ADRIAN KELLY wrote: > i know i should use input but when i changed to raw_input In Python v3 use input() In python v2 input() is dangerous, use raw_input() instead. > ... it wouldn't recognise the word print on the next line. Show us the exact code and error. You may be missing a parenthesis, or maybe you are just expecting the wrong behaviour... It won't execute the print until after it has read your input. > everything to get this working.. > i am 6 hrs at one program Heh, I've got one I've been working on for over 10 years, 6 hours is nothing! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Nov 18 01:06:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Nov 2011 00:06:44 +0000 Subject: [Tutor] infinite loop In-Reply-To: References: Message-ID: On 17/11/11 21:29, ADRIAN KELLY wrote: > amount=float() You don;t need this line because you assign a value to amount immediately you run main() > def main(): > amount = float(raw_input('how much do you want to change:')) > while amount<50: > print 'Sorry, cannot convert an amount under ?50 ' To get a while loop to terminate you must change something about the test condition. In this case the test value 50 is a constant so it needs to be amount that changes. But you only print a message... You need to read a new amount. > else: > total=exchange(amount) > print 'Your exchange comes to: ',total You don't really want/need the else: line. It's not wrong but its more normal to see it done like this: while loop body here next statement with no explicit else. In fact, thinking about it, I've never found a use for the while/else construct, has anyone else? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Fri Nov 18 00:43:10 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 17 Nov 2011 23:43:10 +0000 Subject: [Tutor] urgent help!!!!!!!!!!! In-Reply-To: References: , , Message-ID: <5B80DD153D7D744689F57F4FB69AF474024E03@SCACMX007.exchad.jpmchase.net> def exchange(cash_in): ? ? euro=1 ? ? dollar=1.35 ? ? base=50 ? ? if cash_in>base: ? ? ? ? totalreturn=cash_in*dollar ? ? else: ? ? ? ? totalreturn=0 ? ? return totalreturn amount=0 # this would be better placed inside the main function. def main(): ? ? while amount<50: ? ? ? ? amount = raw_input(float('how much do you want to change:')) # This should be # amount = float( raw_input('how much do you want to change:' ) ) ? ? if amount<50: ? ? ? ? total=0 ? ? ? ? print 'enter an amount over 50: ' ? ? else: ? ? ? ? total=exchange(amount) ? ? ? ? print 'Your exchange comes to: ',total Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Fri Nov 18 01:19:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Nov 2011 00:19:30 +0000 Subject: [Tutor] how to understand unhashable type: 'list' In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info> Message-ID: On 17/11/11 15:30, lina wrote: > tuple (which I don't understand). You mean you don't understand the term 'tuple'? Basically its just a collection of data. You can get a triple - 3 items, a quadruple - 4 items, quintiple - 5 items etc The generic term for a collection of N items is a tuple. triple, quadruple, etc are all specific types of tuple. It's a math thing... In python a tuple is just lie a list except you can't change it - ie. it is immutable. This makes it perfect for using as a key in a dictionary when you'd like to use a list... As an aside some folks like to distinguish between tuples and lists by suggesting that tuples can hold collections of different types of data: t = (1,'two', 3.0) whereas lists should only hold items of the same type. L = [1,2,3] But that's a semantic nicety, Python doesn't make any such distinction. And for dictionary keys (1,2,3) is the only way to do it... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From nidianjs at hotmail.com Fri Nov 18 02:45:00 2011 From: nidianjs at hotmail.com (Nidian Job-Smith) Date: Fri, 18 Nov 2011 01:45:00 +0000 Subject: [Tutor] Encoding In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info>, , Message-ID: Hi all, In my programme I am encoding what the user has in-putted. What the user inputs will in a string, which might a mixture of letters and numbers. However I only want the letters to be encoded. Does any-one how I can only allow the characters to be encoded ?? Big thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlybrand at gmail.com Fri Nov 18 03:26:08 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Thu, 17 Nov 2011 18:26:08 -0800 Subject: [Tutor] The Perennial 3.2 vs 2.7 Message-ID: Okay, so I am about to take up the banner of learning Python again. I had started with 3.2 and I have a book that I like. But all of the things that I want to use Python for appear to be 2.x specific. Will I be setting myself up for failure if I continue learning 3 and then try to write programs in 2.x? Note that I am an experienced programmer, albeit in curly-brace languages (Perl, Java, C#, HTML/CSS/JavaScript), so that will probably count in my favor. But y'all would know better than I if there are significant issues that I will need to overcome conceptually. -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri Nov 18 03:41:56 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 17 Nov 2011 20:41:56 -0600 Subject: [Tutor] The Perennial 3.2 vs 2.7 In-Reply-To: References: Message-ID: On Nov 17, 2011 8:28 PM, "Mark Lybrand" wrote: > > Okay, so I am about to take up the banner of learning Python again. I had started with 3.2 and I have a book that I like. But all of the things that I want to use Python for appear to be 2.x specific. Will I be setting myself up for failure if I continue learning 3 and then try to write programs in 2.x? Note that I am an experienced programmer, albeit in curly-brace languages (Perl, Java, C#, HTML/CSS/JavaScript), so that will probably count in my favor. But y'all would know better than I if there are significant issues that I will need to overcome conceptually. The main differences are syntactic. If you add these lines to the top of your 2.7 files then you won't have much else to worry about. from __future__ import print_function, unicode_literals, division, absolute_import range, input = xrange, raw_input There may be some other differences but those should take care of the larger ones. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Nov 18 04:24:49 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 17 Nov 2011 22:24:49 -0500 Subject: [Tutor] Encoding In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info>, , Message-ID: <4EC5D001.7070105@gmail.com> On 11/17/2011 8:45 PM, Nidian Job-Smith wrote: > > Hi all, > > In my programme I am encoding what the user has in-putted. > > What the user inputs will in a string, which might a mixture of > letters and numbers. > > However I only want the letters to be encoded. > > > Does any-one how I can only allow the characters to be encoded ?? Your question makes no sense to me. Please explain what you mean by encoding letters? An example of input and output might also help. Be sure to reply-all. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From nidianjs at hotmail.com Fri Nov 18 16:29:34 2011 From: nidianjs at hotmail.com (John) Date: Fri, 18 Nov 2011 03:29:34 -1200 Subject: [Tutor] Doctest error! In-Reply-To: <4EC6785E.7060304@hotmail.com> References: <4EC6785E.7060304@hotmail.com> Message-ID: Hi all, When i run a doctest on this piece of code (shown at bottom) i get this error message [from the doctest]: Trying: rot13('5 The Parade') Expecting: '5 Gur Cnenqr' ********************************************************************** File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 Failed example: rot13('5 The Parade') Expected: '5 Gur Cnenqr' Got: 'B-aur-]n\x7fnqr' Trying: rot13('5 Gur Cnenqr') Expecting: '5 The Parade' ********************************************************************** File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 Failed example: rot13('5 Gur Cnenqr') Expected: '5 The Parade' Got: 'B-T\x82\x7f-P{r{~\x7f' An one have any idea why? (I'm guessing its to do with the numbers) code: def rot13(s): """ >>> type(rot13("bob")) >>> len(rot13("foobar")) 6 >>> rot13("abc") 'nop' >>> rot13("XYZ") 'KLM' >>> rot13('5 The Parade') '5 Gur Cnenqr' >>> rot13('5 Gur Cnenqr') '5 The Parade' """ result = '' # initialize output to empty for char in s: # iterate over string if int: char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 char = chr(ord(char) + dist) result+=char return result From d at davea.name Fri Nov 18 04:49:33 2011 From: d at davea.name (Dave Angel) Date: Thu, 17 Nov 2011 22:49:33 -0500 Subject: [Tutor] Doctest error! In-Reply-To: References: <4EC6785E.7060304@hotmail.com> Message-ID: <4EC5D5CD.7010505@davea.name> On 11/18/2011 10:29 AM, John wrote: > > Hi all, > When i run a doctest on this piece of code (shown at bottom) i get > this error message [from the doctest]: > > > > Trying: > rot13('5 The Parade') > Expecting: > '5 Gur Cnenqr' > ********************************************************************** > File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 > Failed example: > rot13('5 The Parade') > Expected: > '5 Gur Cnenqr' > Got: > 'B-aur-]n\x7fnqr' > Trying: > rot13('5 Gur Cnenqr') > Expecting: > '5 The Parade' > ********************************************************************** > File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 > Failed example: > rot13('5 Gur Cnenqr') > Expected: > '5 The Parade' > Got: > 'B-T\x82\x7f-P{r{~\x7f' > > > > An one have any idea why? (I'm guessing its to do with the numbers) > > > code: > > def rot13(s): > > """ > >>> type(rot13("bob")) > > >>> len(rot13("foobar")) > 6 > >>> rot13("abc") > 'nop' > >>> rot13("XYZ") > 'KLM' > >>> rot13('5 The Parade') > '5 Gur Cnenqr' > >>> rot13('5 Gur Cnenqr') > '5 The Parade' > """ > result = '' # initialize output to empty > for char in s: # iterate over string > if int: > char_low = s.lower() > if char_low<= 'm': > dist = 13 > else: > dist = -13 > char = chr(ord(char) + dist) > result+=char > return result The line "if int:" is clearly wrong. Did you write this code yourself, or was it typed in from a listing somewhere? I'd assume that you wanted to do some check on the char value. But if int will always be true. -- DaveA From d at davea.name Fri Nov 18 04:54:33 2011 From: d at davea.name (Dave Angel) Date: Thu, 17 Nov 2011 22:54:33 -0500 Subject: [Tutor] infinite loop In-Reply-To: References: Message-ID: <4EC5D6F9.6010808@davea.name> On 11/17/2011 04:29 PM, ADRIAN KELLY wrote: > #i am nearly there guys..........please loop at the infinite loop i am getting here..................PLEASE!!#ADRIAN > > def exchange(cash_in): euro=1 dollar=float(1.35) base=50 if cash_in>base: totalreturn=cash_in*dollar else: totalreturn=0 return totalreturn > amount=float()def main(): amount = float(raw_input('how much do you want to change:')) while amount<50: print 'Sorry, cannot convert an amount under ?50 ' else: total=exchange(amount) print 'Your exchange comes to: ',total main() > > Till you learn how to post in text mode, I and many others will be unable to read your messages. See how the lines above are all running together? But congratulations on picking a good subject for this one. Others like "please help" are useless subject lines. While I've got your attention, please put your response after the material you're quoting. Not before. And use standard quoting techniques so people can tell your portions apart from the rest. (That last point will probably address itself when you switch to non-html messages) -- DaveA From nidianjs at hotmail.com Fri Nov 18 04:56:29 2011 From: nidianjs at hotmail.com (Nidian Job-Smith) Date: Fri, 18 Nov 2011 03:56:29 +0000 Subject: [Tutor] Doctest error! In-Reply-To: <4EC5D5CD.7010505@davea.name> References: <4EC6785E.7060304@hotmail.com> , <4EC5D5CD.7010505@davea.name> Message-ID: ---------------------------------------- > Date: Thu, 17 Nov 2011 22:49:33 -0500 > From: d at davea.name > To: nidianjs at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] Doctest error! > > On 11/18/2011 10:29 AM, John wrote: > > > > Hi all, > > When i run a doctest on this piece of code (shown at bottom) i get > > this error message [from the doctest]: > > > > > > > > Trying: > > rot13('5 The Parade') > > Expecting: > > '5 Gur Cnenqr' > > ********************************************************************** > > File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 > > Failed example: > > rot13('5 The Parade') > > Expected: > > '5 Gur Cnenqr' > > Got: > > 'B-aur-]n\x7fnqr' > > Trying: > > rot13('5 Gur Cnenqr') > > Expecting: > > '5 The Parade' > > ********************************************************************** > > File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 > > Failed example: > > rot13('5 Gur Cnenqr') > > Expected: > > '5 The Parade' > > Got: > > 'B-T\x82\x7f-P{r{~\x7f' > > > > > > > > An one have any idea why? (I'm guessing its to do with the numbers) > > > > > > code: > > > > def rot13(s): > > > > """ > > >>> type(rot13("bob")) > > > > >>> len(rot13("foobar")) > > 6 > > >>> rot13("abc") > > 'nop' > > >>> rot13("XYZ") > > 'KLM' > > >>> rot13('5 The Parade') > > '5 Gur Cnenqr' > > >>> rot13('5 Gur Cnenqr') > > '5 The Parade' > > """ > > result = '' # initialize output to empty > > for char in s: # iterate over string > > if int: > > char_low = s.lower() > > if char_low<= 'm': > > dist = 13 > > else: > > dist = -13 > > char = chr(ord(char) + dist) > > result+=char > > return result > > The line "if int:" is clearly wrong. Did you write this code > yourself, or was it typed in from a listing somewhere? I'd assume that > you wanted to do some check on the char value. But if int will always > be true. > > > > > -- > > DaveA I want it to look in s, and only perform this code on the letters in s(not numbers): ?char_low = s.lower()? ? ? ? ? ? if char_low <= 'm':? ? ? ? ? ? ? ? ? ? dist = 13? ? ? ? ? ? else:? ? ? ? ? ? ? ? dist = -13 From d at davea.name Fri Nov 18 05:24:16 2011 From: d at davea.name (Dave Angel) Date: Thu, 17 Nov 2011 23:24:16 -0500 Subject: [Tutor] Doctest error! In-Reply-To: References: <4EC6785E.7060304@hotmail.com> , <4EC5D5CD.7010505@davea.name> Message-ID: <4EC5DDF0.3030006@davea.name> On 11/17/2011 10:56 PM, Nidian Job-Smith wrote: > > > ---------------------------------------- >> Date: Thu, 17 Nov 2011 22:49:33 -0500 >> From: d at davea.name >> To: nidianjs at hotmail.com >> CC: tutor at python.org >> Subject: Re: [Tutor] Doctest error! >> >> On 11/18/2011 10:29 AM, John wrote: >>> Hi all, >>> When i run a doctest on this piece of code (shown at bottom) i get >>> this error message [from the doctest]: >>> >>> >>> >>> Trying: >>> rot13('5 The Parade') >>> Expecting: >>> '5 Gur Cnenqr' >>> ********************************************************************** >>> File "F:\Uni\Rot13_1.py", line 12, in Rot13_1.rot13 >>> Failed example: >>> rot13('5 The Parade') >>> Expected: >>> '5 Gur Cnenqr' >>> Got: >>> 'B-aur-]n\x7fnqr' >>> Trying: >>> rot13('5 Gur Cnenqr') >>> Expecting: >>> '5 The Parade' >>> ********************************************************************** >>> File "F:\Uni\Rot13_1.py", line 14, in Rot13_1.rot13 >>> Failed example: >>> rot13('5 Gur Cnenqr') >>> Expected: >>> '5 The Parade' >>> Got: >>> 'B-T\x82\x7f-P{r{~\x7f' >>> >>> >>> >>> An one have any idea why? (I'm guessing its to do with the numbers) >>> >>> >>> code: >>> >>> def rot13(s): >>> >>> """ >>>>>> type(rot13("bob")) >>> >>>>>> len(rot13("foobar")) >>> 6 >>>>>> rot13("abc") >>> 'nop' >>>>>> rot13("XYZ") >>> 'KLM' >>>>>> rot13('5 The Parade') >>> '5 Gur Cnenqr' >>>>>> rot13('5 Gur Cnenqr') >>> '5 The Parade' >>> """ >>> result = '' # initialize output to empty >>> for char in s: # iterate over string >>> if int: >>> char_low = s.lower() >>> if char_low<= 'm': >>> dist = 13 >>> else: >>> dist = -13 >>> char = chr(ord(char) + dist) >>> result+=char >>> return result >> The line "if int:" is clearly wrong. Did you write this code >> yourself, or was it typed in from a listing somewhere? I'd assume that >> you wanted to do some check on the char value. But if int will always >> be true. >> >> >> >> >> -- >> >> DaveA > > I want it to look in s, and only perform this code on the letters in s(not numbers): > char_low = s.lower() if char_low<= 'm': dist = 13 else: dist = -13 > Your formatting is messed up, and I can now see there at least one other bug in it anyway. The method to check if a particular character is alphabetic is str.isalpha(). See if you can see what variable to call that on. Hint: it's not s, since you want to check one character at a time in your loop. -- DaveA From waynejwerner at gmail.com Fri Nov 18 06:58:33 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 17 Nov 2011 23:58:33 -0600 Subject: [Tutor] The Perennial 3.2 vs 2.7 In-Reply-To: References: Message-ID: Forwarding on to the list... (hit reply to all next time) On Thu, Nov 17, 2011 at 8:45 PM, Mark Lybrand wrote: > so, use my 2.7 and not my 3.2 for my study? Or use my 3.2 for study and > then do what I have to in 2.7 after including those lines? > > Thanks for the quick reply by the way. I am still struggling with the loss > od curly braces :) > Honestly it probably doesn't matter. Many 3rd party libraries have now been ported to Python 3.x, so unless you have a particular library you're interested in, I would start with 3.2 until you find something you can't do. As far as the curly braces go... just think about everything that isn't really programming, but telling the compiler something. Get rid of it, and you probably have Python... and you can always try: from __future__ import braces ;) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Fri Nov 18 09:16:46 2011 From: o0MB0o at hotmail.se (Mic) Date: Fri, 18 Nov 2011 09:16:46 +0100 Subject: [Tutor] Shorten Code. In-Reply-To: References: Message-ID: From: Wayne Werner Sent: Thursday, November 17, 2011 8:30 PM To: Mic Cc: tutor at python.org Subject: Re: [Tutor] Clock in tkinter? Say that I have a class and I want to make 100 objects. Then it could look like this: class Chairs(object): #Create the objects chair1=Chairs("10","20") chair2=Chairs("10","20") chair3=Chairs("10","20") How do I shorten this? I have thought of using a for sling. I have looked in my programming book and on the internet, but I don?t know how to make this shorter. The arguements (?10?, ?20?) should be the same for every object, which should make it easier than if they were different each time? If you ever write a line of code more than once, it's a good sign that you have what's called a code smell. This example is very smelly code ;) What you should do instead is have a collection of chairs: chairs = [] for _ in range(100): # the underscore `_` indicates that you don't care about the value chairs.append(Chairs("10","20)) ---------------------------------------------------------------------------------- Yes, I got that right now. But now that you talked about shortening code, I have a general question. What if I don?t write the same line of code more than once, but I write similiar lines more than once. Is that okay? For example: value="green? value_1=?green? click=-1 click1=-1 click2=-1 I know that I can make this shorter, with a for sling for example, but the problem is that I need to use these variables later in my program, and I don?t know how do to then, to be able to use them later on, in a function for example. Do you have any general tips on how to make your code shorter? I also hope I have learnt to post better now. Thanks! Mic -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: wlEmoticon-smile[1].png Type: image/png Size: 1041 bytes Desc: not available URL: From alan.gauld at btinternet.com Fri Nov 18 10:01:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 18 Nov 2011 09:01:41 +0000 Subject: [Tutor] Shorten Code. In-Reply-To: References: Message-ID: On 18/11/11 08:16, Mic wrote: > What if I don?t write the same line of code more than once, but I write > similiar lines more than once. Is that okay? Ler > For example: > value="green? > value_1=?green? If you had a lot of these you could shorten it with a loop (BTW the English term in programming terminology is "loop" not "sling" ;-) for var in [value,value_1]: var = "green" But you need to have already created the variables somewhere and unless there is a big list its not usually worth while. One other trick you can use for this specific type of assignment is value = value_1 = "green" But it gets a bit unreadable for long lists of names. > click=-1 > click1=-1 > click2=-1 Same here, but imagine it had been: click=-1 click1= 2 click2=-1 And here you are changing both name and value. The best abbreviation here is probably tuple expansion: click, click1, click2 = -1,2,-1 > Do you have any general tips on how to make > your code shorter? Shorter is not necessarily better. Clarity is far more important and you should always consider whether tricks like those above are helping or hindering clarity. Only use them if they make your code easier to read. (Also they all make debugging slightly harder so you should think about that too) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kinuthia.muchane at gmail.com Fri Nov 18 14:16:47 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Fri, 18 Nov 2011 16:16:47 +0300 Subject: [Tutor] A recursion question Message-ID: <4EC65ABF.7080703@gmail.com> Hi, I am trying to do something which is really stupid :-) I would like to count the number of occurrences of a certain character in a list. This is more of an exercise in recursion rather than the underlying problem. I could have used a *for* loop or simply the list *count* method. Here is the code: class Find_Ex(): count = 0 def slais(self, lst, x): if len(lst) == 0: #if list is empty just give a -1 return -1 elif lst[0] == x: Find_Ex.count += 1 # we have found 'x', increment class attribute 'count' by 1 Find_Ex.slais(self,lst[1:], x)# slice the list and go to the next element else: Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to the next element return Find_Ex.count s = Find_Ex() lst = [4,4,4,5,6,7,4,7,7,4] x = 4 print "There are %d occurrences of %d"%(s.slais(lst, x),x) It works as advertised but I am convincing myself that it should not! :-) If the list is empty, which is the base case, s.slais([], 4) returns -1. Now using some bush logic, in a non-empty list, in order for the recursion to terminate it has to 'hit' the base case and return -1. Where does this -1 go ? Further, why do not I get a *TypeError* when I use a simple *return* statement in the *if* clause? The reason I am asking that is that I think(wrongly, of course :-)) it should be part of the answer and therefore I should be getting an answer that is off by one or a *TypeError*!! And by the way, the reason I used a *class* was that I could not get a suitable place in the program to initialise my *count* variable otherwise. Thanks... -- K?n?thia S 1? 8' 24? E 36? 57' 36? 1522m From cwitts at compuscan.co.za Fri Nov 18 14:36:54 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 18 Nov 2011 15:36:54 +0200 Subject: [Tutor] A recursion question In-Reply-To: <4EC65ABF.7080703@gmail.com> References: <4EC65ABF.7080703@gmail.com> Message-ID: <4EC65F76.4040403@compuscan.co.za> On 2011/11/18 03:16 PM, K?n?thia M?chane wrote: > Hi, > > I am trying to do something which is really stupid :-) > I would like to count the number of occurrences of a certain character > in a list. > This is more of an exercise in recursion rather than the underlying > problem. > I could have used a *for* loop or simply the list *count* method. > Here is the code: > > class Find_Ex(): > > count = 0 > def slais(self, lst, x): > if len(lst) == 0: #if list is empty just give a -1 > return -1 > elif lst[0] == x: > Find_Ex.count += 1 # we have found 'x', increment class > attribute 'count' by 1 > Find_Ex.slais(self,lst[1:], x)# slice the list and go to > the next element > else: > Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to > the next element > return Find_Ex.count > > s = Find_Ex() > lst = [4,4,4,5,6,7,4,7,7,4] > x = 4 > print "There are %d occurrences of %d"%(s.slais(lst, x),x) > > It works as advertised but I am convincing myself that it should not! :-) > > If the list is empty, which is the base case, s.slais([], 4) returns > -1. Now using some bush logic, in a non-empty list, in order for the > recursion to terminate it has to 'hit' the base case and return -1. > Where does this -1 go ? Further, why do not I get a *TypeError* when > I use a simple *return* statement in the *if* clause? > > The reason I am asking that is that I think(wrongly, of course :-)) > it should be part of the answer and therefore I should be getting an > answer that is off by one or a *TypeError*!! > > And by the way, the reason I used a *class* was that I could not get a > suitable place in the program to initialise my *count* variable > otherwise. > > Thanks... > If you pop in some print statements you can see what's happening a bit easier. You are creating a stack of functions which each return their values but in a LIFO fashion (Last In, First Out) so you can see the first return is -1 as you expected to happen when the list is exhausted, and then each subsequent return is the count which is why you get the correct return value in the end. Also, why do you think you should get a TypeError when you `return -1` ? class Find_Ex(): count = 0 def slais(self, lst, x): print lst if len(lst) == 0: #if list is empty just give a -1 print 'Returning -1' return -1 elif lst[0] == x: print 'Incrementing Count' Find_Ex.count += 1 # we have found 'x', increment class attribute 'count' by 1 Find_Ex.slais(self,lst[1:], x)# slice the list and go to the next element else: print 'Nothing Found' Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to the next element print 'Returning the count' return Find_Ex.count s = Find_Ex() lst = [4,4,4,5,6,7,4,7,7,4] x = 4 print "There are %d occurrences of %d"%(s.slais(lst, x),x) [4, 4, 4, 5, 6, 7, 4, 7, 7, 4] Incrementing Count [4, 4, 5, 6, 7, 4, 7, 7, 4] Incrementing Count [4, 5, 6, 7, 4, 7, 7, 4] Incrementing Count [5, 6, 7, 4, 7, 7, 4] Nothing Found [6, 7, 4, 7, 7, 4] Nothing Found [7, 4, 7, 7, 4] Nothing Found [4, 7, 7, 4] Incrementing Count [7, 7, 4] Nothing Found [7, 4] Nothing Found [4] Incrementing Count [] Returning -1 Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count There are 5 occurrences of 4 -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Fri Nov 18 15:05:44 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Fri, 18 Nov 2011 09:05:44 -0500 Subject: [Tutor] Encoding In-Reply-To: References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info> Message-ID: Well, I am assuming that by this you mean converting user input into a string, and then extracting the numerals (0-9) from it. Next time, please tell us your version of Python. I'll do my best to help with this. You might try the following: the_input = input("Insert string here: ") # change to raw_input in python 2 after = "" for char in the_input: try: char = int(char) except: after += char If other symbols might be in the string ($, @, etc.), then you might use the_input = input('Insert string here: ') # change to raw_input in python 2 after = '' not_allowed = '1234567890-=!@#$%^&**()_+,./<>?`~[]{}\\|' for char in the_input: if char in not_allowed: pass else: after += char This method requires more typing, but it works with a wider variety of characters. Hopefully this helped. On Thu, Nov 17, 2011 at 8:45 PM, Nidian Job-Smith wrote: > > Hi all, > > In my programme I am encoding what the user has in-putted. > > What the user inputs will in a string, which might a mixture of letters > and numbers. > > However I only want the letters to be encoded. > > > Does any-one how I can only allow the characters to be encoded ?? > > Big thanks, > > > > _______________________________________________ > 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 d at davea.name Fri Nov 18 15:39:05 2011 From: d at davea.name (Dave Angel) Date: Fri, 18 Nov 2011 09:39:05 -0500 Subject: [Tutor] Shorten Code. In-Reply-To: References: Message-ID: <4EC66E09.8060702@davea.name> On 11/18/2011 04:01 AM, Alan Gauld wrote: > On 18/11/11 08:16, Mic wrote: > >> What if I don?t write the same line of code more than once, but I write >> similiar lines more than once. Is that okay? Ler >> For example: >> value="green? >> value_1=?green? > > If you had a lot of these you could shorten it with a loop (BTW the > English term in programming terminology is "loop" not "sling" ;-) > > for var in [value,value_1]: > var = "green" Um, that won't work. You typed that example too quickly. .... Mic, the problem is not "shortening code," but making it more readable, and easier to maintain. If you have a series of variables that hold similar or identical values, or which are treated in consistent ways, then you should probably make a list out of them. And that will naturally shorten code like this. student0 = 4 student1 = 3 student2 = 12 student3 = 11 Replace with students = list((4,3,12,11)) Then if you want to deal with a particular student, you might do student[2] = 5 But if you want to deal with the ith student, you could do student[i] = and if you want to do something with all of them: for index, student in enumerate(students): students[indes] += 65 There are plenty of more advanced methods that would make even that simpler, but I'm trying to keep it simple. -- DaveA From d at davea.name Fri Nov 18 16:04:22 2011 From: d at davea.name (Dave Angel) Date: Fri, 18 Nov 2011 10:04:22 -0500 Subject: [Tutor] A recursion question In-Reply-To: <4EC65ABF.7080703@gmail.com> References: <4EC65ABF.7080703@gmail.com> Message-ID: <4EC673F6.6050300@davea.name> On 11/18/2011 08:16 AM, K?n?thia M?chane wrote: > Hi, > > I am trying to do something which is really stupid :-) > I would like to count the number of occurrences of a certain character > in a list. > This is more of an exercise in recursion rather than the underlying > problem. > I could have used a *for* loop or simply the list *count* method. > Here is the code: > > class Find_Ex(): > > count = 0 > def slais(self, lst, x): > if len(lst) == 0: #if list is empty just give a -1 > return -1 > elif lst[0] == x: > Find_Ex.count += 1 # we have found 'x', increment class > attribute 'count' by 1 > Find_Ex.slais(self,lst[1:], x)# slice the list and go to > the next element > else: > Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to > the next element > return Find_Ex.count > > s = Find_Ex() > lst = [4,4,4,5,6,7,4,7,7,4] > x = 4 > print "There are %d occurrences of %d"%(s.slais(lst, x),x) > > It works as advertised but I am convincing myself that it should not! :-) > Well, it doesn't count the number of occurrences correctly if the list is empty. It should get zero, and it gets -1. But for any non-empty list, nothing ever looks at the -1 value, so it doesn't matter what you put there. This example diverges from traditional recursion in many ways, but the chief reason it's not traditional recursion is that it never uses the return value. within the function. > If the list is empty, which is the base case, s.slais([], 4) returns > -1. Now using some bush logic, in a non-empty list, in order for the > recursion to terminate it has to 'hit' the base case and return -1. > Where does this -1 go ? Nowhere. You don't use it, so it gets discarded. if you were going to use it, your internal calls to the method would look something like: b = self.slais(lst[1:], x) and then you'd do something with b. > Further, why do not I get a *TypeError* when I use a simple *return* > statement in the *if* clause? > You would if you actually used the value for arithmetic. But the return itself would be perfectly legal. it's just a shortcut for 'return None' > The reason I am asking that is that I think(wrongly, of course :-)) > it should be part of the answer and therefore I should be getting an > answer that is off by one or a *TypeError*!! > > And by the way, the reason I used a *class* was that I could not get a > suitable place in the program to initialise my *count* variable > otherwise. > Using a class is fine. But you're abusing it. What happens if you try to sum a second list? (Hint, it gives you a higher number) > Thanks... > If you really want to recursively count, you need a structure which uses no objects of global lifetime. The intermediate values should be stored in local variables to that method. def counter(mylist, val): if len(mylist == 0): return 0 prev = counter(mylist[1:], val) #this is actually using the recursive return value if mylist[0] == val: return prev + 1 else: return prev Totally untested. And there are certainly many other variants possible. But the key is you have to do something with the value returned to you by the lower level function. -- DaveA From ramit.prasad at jpmorgan.com Fri Nov 18 16:26:32 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 18 Nov 2011 15:26:32 +0000 Subject: [Tutor] FW: urgent help!! THANKS EVERYONE! Message-ID: <5B80DD153D7D744689F57F4FB69AF47402547F@SCACMX007.exchad.jpmchase.net> Forwarding to the list since I wasn't the only person who helped ;) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- From: ADRIAN KELLY [mailto:kellyadrian at hotmail.com] Sent: Thursday, November 17, 2011 6:08 PM To: Prasad, Ramit Subject: RE: [Tutor] urgent help!! THANKS EVERYONE! Thanks for your help i just got it going my way below - but your way looks easier and better! ? thanks for all your help everyone. ?feel free to comment on my method - its?awkward but it works..........? adrian def exchange(cash_in): ? ? euro=1 ? ? dollar=1.35 ? ? base=50 ? ? if cash_in>base: ? ? ? ? totalreturn=cash_in*dollar ? ? else: ? ? ? ? totalreturn=0 ? ? return totalreturn def main(): ? ? amount=0 ? ? amount = float(raw_input('how much do you want to change:')) ? ? while amount<50: ? ? ? ? print 'enter an amount over 50' ? ? ? ? amount = float(raw_input('how much do you want to change:')) ? ? else: ? ? ? ? total=exchange(amount) ? ? ? ? print 'Your exchange comes to: ',total ?? ? ?? main() ? ? > From: ramit.prasad at jpmorgan.com > To: kellyadrian at hotmail.com; waynejwerner at gmail.com > CC: tutor at python.org > Subject: RE: [Tutor] urgent help!!!!!!!!!!! > Date: Thu, 17 Nov 2011 23:43:10 +0000 > > def exchange(cash_in): > ? ? euro=1 > ? ? dollar=1.35 > ? ? base=50 > ? ? if cash_in>base: > ? ? ? ? totalreturn=cash_in*dollar > ? ? else: > ? ? ? ? totalreturn=0 > ? ? return totalreturn > > amount=0 > # this would be better placed inside the main function. > def main(): > ? ? while amount<50: > ? ? ? ? amount = raw_input(float('how much do you want to change:')) > # This should be > # amount = float( raw_input('how much do you want to change:' ) ) > ? ? if amount<50: > ? ? ? ? total=0 > ? ? ? ? print 'enter an amount over 50: ' > ? ? else: > ? ? ? ? total=exchange(amount) > ? ? ? ? print 'Your exchange comes to: ',total > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From waynejwerner at gmail.com Fri Nov 18 17:00:11 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 18 Nov 2011 10:00:11 -0600 Subject: [Tutor] FW: urgent help!! THANKS EVERYONE! In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47402547F@SCACMX007.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47402547F@SCACMX007.exchad.jpmchase.net> Message-ID: On Fri, Nov 18, 2011 at 9:26 AM, Prasad, Ramit wrote: > Forwarding to the list since I wasn't the only person who helped ;) > > From: ADRIAN KELLY [mailto:kellyadrian at hotmail.com] > Sent: Thursday, November 17, 2011 6:08 PM > To: Prasad, Ramit > Subject: RE: [Tutor] urgent help!! THANKS EVERYONE! > > Thanks for your help i just got it going my way below - but your way looks > easier and better! > thanks for all your help everyone. feel free to comment on my method - > its awkward but it works.......... > def main(): > amount=0 > amount = float(raw_input('how much do you want to change:')) > while amount<50: > print 'enter an amount over 50' > amount = float(raw_input('how much do you want to change:')) > else: > total=exchange(amount) > print 'Your exchange comes to: ',total > In these sorts of cases I actually prefer the recursive solution. And from a usability standpoint it's much nicer to warn the user ahead of time: def amount_over_50(): amount = float(raw_input("How much do you want to change (minimum $50)? Amount: $")) if amount < 50.0: print 'Please enter an amount greater than $50' return amount_over_50() return amount Then you can just do this: def main(): print 'Your total comes to', exchange(amount_over_50()) The chances of hitting the maximum recursion depth is pretty slim, unless your user manages to type in a wrong number about 1000 times ;) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From joebatt at hotmail.co.uk Fri Nov 18 17:12:23 2011 From: joebatt at hotmail.co.uk (Joe Batt) Date: Fri, 18 Nov 2011 16:12:23 +0000 Subject: [Tutor] =?windows-1252?q?In_a_pickle_over_pickles=85=2EPython_3?= Message-ID: Hi All,Sorry to trouble you all again with more nooby problems! Only been programming a week so still all a haze especially since self taught?.. I am opening a url and saving it to a file on my computer, then I am trying to pickle it. I have written the url file to a file on my computer then opened it and assigned the contents to a var 'filecontents' and tried to pickle it it is giving the error: Traceback (most recent call last): File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in geturlfile(urlfile) File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 28, in geturlfile pickle.dump(filecontents,pickledfile)TypeError: must be str, not bytes Yet I tested the variable filecontents using print (type(file contents)) and it is saying that it is a str yet the error seems to indicate it is a byte, can anyone point me in the right direction please? (I know my coding is very untidy and verbose, sorry I am very new and at the moment I have to think in baby steps with little knowledge!) Joe #################################################################### Pickle an object- ################################################################### import pickleimport urllib def geturlfile(urlfile):#gets the user URL from main opens it and saves it to var fileurl from urllib.request import urlopen fileurl=urlopen(urlfile)#opens the file on computer and writes the var fileurl to it html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','w') for line in fileurl.readlines(): linestring=line.decode("utf-8") #ensures written in string not byte html_file.write(linestring) html_file.close() #closes the puzzle file#just prints file to check its correct html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','r') filecontents=html_file.read() html_file.close() print (filecontents) print (type(filecontents)) #pickles the file filecontents containing the url file pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','w') pickle.dump(filecontents,pickledfile) pickledfile.close() return () # Main programurlfile=input('Please input the URL ')geturlfile(urlfile) -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Fri Nov 18 17:26:39 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Fri, 18 Nov 2011 11:26:39 -0500 Subject: [Tutor] Saving read-only or encoded text files? Message-ID: Hi. I've been using a lot of text files recently, and I'm starting to worry about a user hacking some element by editing the text files. I know that I can pickle my data instead, creating less easily editable (try saying that five times fast) .dat files, but I'd rather store individual variables rather than lists of objects. Is there a way to make my text files either read-only or saved in some way that they can't be opened, or at least not so easily as double-clicking on them? I just want some slightly more secure code, though it's not too important. I just thought I'd ask. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Nov 18 17:58:48 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 18 Nov 2011 16:58:48 +0000 Subject: [Tutor] Saving read-only or encoded text files? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474025862@SCACMX007.exchad.jpmchase.net> Hi.? I've been using a lot of text files recently, and I'm starting to worry about a user hacking some element by editing the text files.? I know that I can pickle my data instead, creating less easily editable (try saying that five times fast) .dat files, but I'd rather store individual variables rather than lists of objects.? Is there a way to make my text files either read-only or saved in some way that they can't be opened, or at least not so easily as double-clicking on them?? I just want some slightly more secure code, though it's not too important.? I just thought I'd ask. ========================================================================================== Any file will eventually be able to be reverse engineered, but it matters how much effort you care to obfuscate it. The way you can do it will vary based on your OS. For Windows, you can change the file extension to something that is not read by most text editors '.zxy'. It will still be able to be read if they try and open it with a text editor, but double clicking will not work by default. You can also try setting the file attribute directly: http://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/ For *nix/OS X, you can prepend the file with "." as those files are hidden by default on most *nix systems I have used. You can also try to use os.chmod(0###, 'filename'). Keep in mind that all of these solutions are probably user reversible since the application will have the permissions of the user account it is run as; in most cases this is the same as the logged in user. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From maxskywalker1 at gmail.com Fri Nov 18 18:17:49 2011 From: maxskywalker1 at gmail.com (Max gmail) Date: Fri, 18 Nov 2011 12:17:49 -0500 Subject: [Tutor] Saving read-only or encoded text files? In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474025862@SCACMX007.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474025862@SCACMX007.exchad.jpmchase.net> Message-ID: <1E6FAE38-DE5A-4257-A4BA-97A1DD946828@gmail.com> Thank you. This will work perfectly. On Nov 18, 2011, at 11:58 AM, Prasad, Ramit wrote: > Hi. I've been using a lot of text files recently, and I'm starting to worry about a user hacking some element by editing the text files. I know that I can pickle my data instead, creating less easily editable (try saying that five times fast) .dat files, but I'd rather store individual variables rather than lists of objects. Is there a way to make my text files either read-only or saved in some way that they can't be opened, or at least not so easily as double-clicking on them? I just want some slightly more secure code, though it's not too important. I just thought I'd ask. > ========================================================================================== > > Any file will eventually be able to be reverse engineered, but it matters how much effort you care to obfuscate it. The way you can do it will vary based on your OS. > > For Windows, you can change the file extension to something that is not read by most text editors '.zxy'. It will still be able to be read if they try and open it with a text editor, but double clicking will not work by default. You can also try setting the file attribute directly: http://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/ > > For *nix/OS X, you can prepend the file with "." as those files are hidden by default on most *nix systems I have used. You can also try to use os.chmod(0###, 'filename'). > > > Keep in mind that all of these solutions are probably user reversible since the application will have the permissions of the user account it is run as; in most cases this is the same as the logged in user. > > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Fri Nov 18 18:09:49 2011 From: d at davea.name (Dave Angel) Date: Fri, 18 Nov 2011 12:09:49 -0500 Subject: [Tutor] =?windows-1252?q?In_a_pickle_over_pickles=85=2EPython_3?= In-Reply-To: References: Message-ID: <4EC6915D.1060603@davea.name> On 11/18/2011 11:12 AM, Joe Batt wrote: > Hi All,Sorry to trouble you all again with more nooby problems! Only been programming a week so still all a haze especially since self taught?.. > I am opening a url and saving it to a file on my computer, then I am trying to pickle it. I have written the url file to a file on my computer then opened it and assigned the contents to a var 'filecontents' and tried to pickle it it is giving the error: > Traceback (most recent call last): File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in geturlfile(urlfile) File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 28, in geturlfile pickle.dump(filecontents,pickledfile)TypeError: must be str, not bytes > Yet I tested the variable filecontents using print (type(file contents)) and it is saying that it is a str yet the error seems to indicate it is a byte, can anyone point me in the right direction please? > (I know my coding is very untidy and verbose, sorry I am very new and at the moment I have to think in baby steps with little knowledge!) > Joe > #################################################################### Pickle an object- ################################################################### > import pickleimport urllib > def geturlfile(urlfile):#gets the user URL from main opens it and saves it to var fileurl from urllib.request import urlopen fileurl=urlopen(urlfile)#opens the file on computer and writes the var fileurl to it html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','w') for line in fileurl.readlines(): linestring=line.decode("utf-8") #ensures written in string not byte html_file.write(linestring) html_file.close() #closes the puzzle file#just prints file to check its correct html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','r') filecontents=html_file.read() html_file.close() print (filecontents) print (type(filecontents)) > #pickles the file filecontents containing the url file pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','w') pickle.dump(filecontents,pickledfile) pickledfile.close() > return () > > # Main programurlfile=input('Please input the URL ')geturlfile(urlfile) > You forgot to post in text mode, so everything ran together. -- DaveA From waynejwerner at gmail.com Fri Nov 18 18:16:07 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 18 Nov 2011 11:16:07 -0600 Subject: [Tutor] Saving read-only or encoded text files? In-Reply-To: <1E6FAE38-DE5A-4257-A4BA-97A1DD946828@gmail.com> References: <5B80DD153D7D744689F57F4FB69AF474025862@SCACMX007.exchad.jpmchase.net> <1E6FAE38-DE5A-4257-A4BA-97A1DD946828@gmail.com> Message-ID: On Fri, Nov 18, 2011 at 11:17 AM, Max gmail wrote: > Thank you. This will work perfectly. > > On Nov 18, 2011, at 11:58 AM, Prasad, Ramit wrote: > > > > > Any file will eventually be able to be reverse engineered, but it > matters how much effort you care to obfuscate it. The way you can do it > will vary based on your OS. > > > > For Windows, you can change the file extension to something that is not > read by most text editors '.zxy'. It will still be able to be read if they > try and open it with a text editor, but double clicking will not work by > default. You can also try setting the file attribute directly: > http://code.activestate.com/recipes/303343-changing-file-attributes-on-windows/ > > > > For *nix/OS X, you can prepend the file with "." as those files are > hidden by default on most *nix systems I have used. You can also try to use > os.chmod(0###, 'filename'). > > > > > > Keep in mind that all of these solutions are probably user reversible > since the application will have the permissions of the user account it is > run as; in most cases this is the same as the logged in user. > > As an addition, you can also create the file using the zipfile module ( http://docs.python.org/library/zipfile.html). This adds another layer of obfuscation and has the added benefit of making your files smaller. Of course, the savvy user won't have any issue getting past this (Office files are just archive files). On Ubuntu at least, if you just remove the extension then it will attempt to discover what the filetype, and can usually guess archive types. It's security through obscurity, of course, so it all depends on who you're worried about accessing this data. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Nov 18 18:29:41 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 18 Nov 2011 17:29:41 +0000 Subject: [Tutor] Encoding In-Reply-To: <4EC5D001.7070105@gmail.com> References: <4EC4FB46.2010303@pearwood.info> <4EC51DE0.2070407@pearwood.info>, , <4EC5D001.7070105@gmail.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47402590D@SCACMX007.exchad.jpmchase.net> On 11/17/2011 8:45 PM, Nidian Job-Smith wrote: Hi all, In my programme I am encoding what the user has?in-putted.? What the user inputs will in a string, which might a mixture of letters and numbers. However I only want the letters to be encoded.? ======================================================== I am assuming that you meant "only accept characters" and not actual text encoding. The following example is untested and is limited. It will not really work with non-ASCII letters (i.e. Unicode). import string input_string = raw_input( 'Enter something' ) #use input in Python3 final_input = [] # append to a list instead of concatenating a string # because it is faster to ''.join( list ) for char in input_string: if char in string.letters: final_input.append( char ) input_string = ''.join( final_input ) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From malaclypse2 at gmail.com Fri Nov 18 19:16:41 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 18 Nov 2011 13:16:41 -0500 Subject: [Tutor] =?utf-8?q?In_a_pickle_over_pickles=E2=80=A6=2EPython_3?= In-Reply-To: References: Message-ID: On Fri, Nov 18, 2011 at 11:12 AM, Joe Batt wrote: > > pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','w') > pickle.dump(filecontents,pickledfile) > pickledfile.close() > > A pickle is a binary object, so you'll need to open your picklefile in binary mode: pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','wb') -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 18 19:15:11 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 18 Nov 2011 18:15:11 +0000 (GMT) Subject: [Tutor] Shorten Code. In-Reply-To: <4EC66E09.8060702@davea.name> References: <4EC66E09.8060702@davea.name> Message-ID: <1321640111.60266.YahooMailRC@web86705.mail.ird.yahoo.com> > > for var in [value,value_1]: > > var = "green" > > Um, that won't work. You typed that example too quickly. Oops! Yes. You'd need to enumerate and access the variables via an index. yuk. Don't do it folks! :-) Excuse: It was early morning and I hadn't had any coffee... Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kinuthia.muchane at gmail.com Fri Nov 18 20:26:12 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Fri, 18 Nov 2011 22:26:12 +0300 Subject: [Tutor] A recursion question In-Reply-To: <4EC673F6.6050300@davea.name> References: <4EC65ABF.7080703@gmail.com> <4EC673F6.6050300@davea.name> Message-ID: <4EC6B154.1090003@gmail.com> On 11/18/2011 06:04 PM, Dave Angel wrote: > On 11/18/2011 08:16 AM, K?n?thia M?chane wrote: >> >> > Well, it doesn't count the number of occurrences correctly if the list > is empty. It should get zero, and it gets -1. But for any non-empty > list, nothing ever looks at the -1 value, so it doesn't matter what > you put there. This example diverges from traditional recursion in > many ways, but the chief reason it's not traditional recursion is that > it never uses the return value. within the function. >> If the list is empty, which is the base case, s.slais([], 4) returns >> -1. Now using some bush logic, in a non-empty list, in order for the >> recursion to terminate it has to 'hit' the base case and return -1. >> Where does this -1 go ? > Nowhere. You don't use it, so it gets discarded. if you were going > to use it, your internal calls to the method would look something like: > b = self.slais(lst[1:], x) > and then you'd do something with b. >> Further, why do not I get a *TypeError* when I use a simple *return* >> statement in the *if* clause? >> > You would if you actually used the value for arithmetic. But the > return itself would be perfectly legal. it's just a shortcut for > 'return None' >> The reason I am asking that is that I think(wrongly, of course :-)) >> it should be part of the answer and therefore I should be getting an >> answer that is off by one or a *TypeError*!! >> >> And by the way, the reason I used a *class* was that I could not get >> a suitable place in the program to initialise my *count* variable >> otherwise. >> > Using a class is fine. But you're abusing it. What happens if you > try to sum a second list? (Hint, it gives you a higher number) That is very true, I tried it with a second list and the value was higher. >> Thanks... >> > If you really want to recursively count, you need a structure which > uses no objects of global lifetime. The intermediate values should be > stored in local variables to that method. > > def counter(mylist, val): > if len(mylist == 0): > return 0 > prev = counter(mylist[1:], val) #this is actually using the > recursive return value > if mylist[0] == val: > return prev + 1 > else: > return prev I was trying to come up with something like this but I was totally stumped. Now I understand, perfectly. My heartfelt thanks to you, Dave, and Christian ! ;-) > > Totally untested. And there are certainly many other variants > possible. But the key is you have to do something with the value > returned to you by the lower level function. > > > > > -- K?n?thia S 1? 8' 24? E 36? 57' 36? 1522m From ramit.prasad at jpmorgan.com Fri Nov 18 20:32:45 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 18 Nov 2011 19:32:45 +0000 Subject: [Tutor] binary file query In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47401EC9C@SCACMX007.exchad.jpmchase.net> <5B80DD153D7D744689F57F4FB69AF4740236D1@SCACMX007.exchad.jpmchase.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF474025BBE@SCACMX007.exchad.jpmchase.net> >No *need* but, often convenient, regardless of whether the data was >written by a C struct or not.(*) It is a way to interpret binary data in >terms of fundamental data types such as ints, floats, strings etc. >Trying to convert raw bytes representing floats into a floating point >number without using struct would be an interesting exercise. Using >struct it's trivial. Interesting, I will keep it in mind. Thanks! Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From rhettnaxel at gmail.com Fri Nov 18 21:20:17 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Fri, 18 Nov 2011 15:20:17 -0500 Subject: [Tutor] Shorten Code. In-Reply-To: <1321640111.60266.YahooMailRC@web86705.mail.ird.yahoo.com> References: <4EC66E09.8060702@davea.name> <1321640111.60266.YahooMailRC@web86705.mail.ird.yahoo.com> Message-ID: <9AC1D2B7-CC71-4DFA-A327-632F5FF59E37@gmail.com> On Nov 18, 2011, at 13:15, ALAN GAULD wrote: > > > > for var in [value,value_1]: > > > var = "green" > > > > Um, that won't work. You typed that example too quickly. > > Oops! Yes. You'd need to enumerate and access the variables > via an index. yuk. Don't do it folks! :-) > > Excuse: It was early morning and I hadn't had any coffee... > > Alan G. > ____ In your defense Alan, after you typed that code in your response you mentioned the necessity of defining the variables: >But you need to have already created the variables >somewhere and unless there is a big list its not usually >worth while. Alexander Etter > ___________________________________________ > 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 Fri Nov 18 23:53:28 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 18 Nov 2011 14:53:28 -0800 Subject: [Tutor] urgent help!!!!!!!!!!! In-Reply-To: References: , , Message-ID: On 11/17/2011 3:26 PM ADRIAN KELLY said... > i know i'm stupid but i have tried everything to get one line of text > working, i have written out pseudo and read every website..... > now i am getting this error............ > > Traceback (most recent call last): > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", > line 24, in > main() > File "F:\VTOS ATHLONE\PYTHON_VTOS\foreign exchange\f_ex4 - Copy.py", > line 14, in main > while amount<50: > UnboundLocalError: local variable 'amount' referenced before assignment >> You've seen the fixes, but perhaps more explanation helps too. Python organizes variables into namespaces. The normal namespace resolution sequence is local, global, builtin. Assigning to a name within a function creates a local variable, otherwise accessing a name in a function will use the global or builtin namespaces. Python decides these issues in part during initial loading of the module where it sees that you assign to the variable amount within the function, thus creating a local variable. Later, during execution, you first test the value of amount (in the while statement), but amount isn't assigned to until after the test, ergo, UnboundLocalError. HTH, Emile From evosweet at hotmail.com Sat Nov 19 01:46:55 2011 From: evosweet at hotmail.com (Rayon) Date: Fri, 18 Nov 2011 20:46:55 -0400 Subject: [Tutor] python telnet In-Reply-To: <4EC59E05.7050106@pearwood.info> References: <4EC59E05.7050106@pearwood.info> Message-ID: I installed the telnet client but still the same error. Traceback (most recent call last): File "C:\Users\Rayon\Documents\projects1\super_hia\main.py", line 6, in child = winspawn('telnet 192.168.0.55:210') File "C:\Python26\lib\site-packages\winpexpect-1.5-py2.6.egg\winpexpect.py", line 346, in __init__ logfile=logfile, cwd=cwd, env=env) File "C:\Python26\lib\site-packages\winpexpect-1.5-py2.6.egg\pexpect.py", line 429, in __init__ self._spawn (command, args) File "C:\Python26\lib\site-packages\winpexpect-1.5-py2.6.egg\winpexpect.py", line 369, in _spawn raise ExceptionPexpect, 'Command not found: %s' % self.command ExceptionPexpect: Command not found: telnet -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Steven D'Aprano Sent: 17 November 2011 19:52 To: tutor at python.org Subject: Re: [Tutor] python telnet Rayon wrote: > I am trying to use winpexpect to connect a telnet session. > I keep getting this error. > > > > raise ExceptionPexpect, 'Command not found: %s' % self.command > ExceptionPexpect: Command not found: telnet Please copy and paste the entire traceback, not just the last couple of lines. But judging by just the small bit you show, it looks like "telnet" is not a command that winpexpect understands, so it raises an error "command not found". Perhaps it is a bug in winpexpect. Are you using the latest version? Do you actually have telnet available on your system? If not, then you can't expect winpexpect to use something which isn't there. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From evosweet at hotmail.com Sat Nov 19 01:37:22 2011 From: evosweet at hotmail.com (Rayon) Date: Fri, 18 Nov 2011 20:37:22 -0400 Subject: [Tutor] python telnet In-Reply-To: <4EC59E05.7050106@pearwood.info> References: <4EC59E05.7050106@pearwood.info> Message-ID: Thank you I think I understand now, thank you very much. -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Steven D'Aprano Sent: 17 November 2011 19:52 To: tutor at python.org Subject: Re: [Tutor] python telnet Rayon wrote: > I am trying to use winpexpect to connect a telnet session. > I keep getting this error. > > > > raise ExceptionPexpect, 'Command not found: %s' % self.command > ExceptionPexpect: Command not found: telnet Please copy and paste the entire traceback, not just the last couple of lines. But judging by just the small bit you show, it looks like "telnet" is not a command that winpexpect understands, so it raises an error "command not found". Perhaps it is a bug in winpexpect. Are you using the latest version? Do you actually have telnet available on your system? If not, then you can't expect winpexpect to use something which isn't there. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From pasokan at talentsprint.com Sat Nov 19 04:03:49 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Sat, 19 Nov 2011 08:33:49 +0530 Subject: [Tutor] A recursion question In-Reply-To: <4EC6B154.1090003@gmail.com> References: <4EC65ABF.7080703@gmail.com> <4EC673F6.6050300@davea.name> <4EC6B154.1090003@gmail.com> Message-ID: Another way to do that is to avoid any intermediate variables altogether That may be easier to understand YMMV def counter(mylist, val): if len(mylist == 0): return 0 if mylist[0] == val: return 1 + counter(mylist[1:], val) else: return counter(mylist[1:]) Asokan Pichai -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Nov 19 06:46:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 Nov 2011 16:46:56 +1100 Subject: [Tutor] FW: urgent help!! THANKS EVERYONE! In-Reply-To: References: <5B80DD153D7D744689F57F4FB69AF47402547F@SCACMX007.exchad.jpmchase.net> Message-ID: <4EC742D0.8000605@pearwood.info> Wayne Werner wrote: > The chances of hitting the maximum recursion depth is pretty slim, unless > your user manages to type in a wrong number about 1000 times ;) I've had to provide desktop support to people who have done that. Only-slightly-exaggerating-ly 'yrs, -- Steven From kinuthia.muchane at gmail.com Sat Nov 19 07:36:02 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Sat, 19 Nov 2011 09:36:02 +0300 Subject: [Tutor] A recursion question In-Reply-To: References: <4EC65ABF.7080703@gmail.com> <4EC673F6.6050300@davea.name> <4EC6B154.1090003@gmail.com> Message-ID: <4EC74E52.8050609@gmail.com> On 11/19/2011 06:03 AM, Asokan Pichai wrote: > Another way to do that is to avoid any intermediate variables altogether > That may be easier to understand YMMV > > def counter(mylist, val): > if len(mylist == 0): > return 0 > if mylist[0] == val: > return 1 + counter(mylist[1:], val) > else: > return counter(mylist[1:]) The intermediate variable explanation by Dave actually clinched it for me. Actually, the one I wrote is suspiciously similar to yours ;-). Anyway, thanks Asokan! > > > Asokan Pichai > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- K?n?thia S 1? 8' 24? E 36? 57' 36? 1522m -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 19 09:54:30 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 19 Nov 2011 08:54:30 +0000 (GMT) Subject: [Tutor] Shorten Code. In-Reply-To: <9AC1D2B7-CC71-4DFA-A327-632F5FF59E37@gmail.com> References: <4EC66E09.8060702@davea.name> <1321640111.60266.YahooMailRC@web86705.mail.ird.yahoo.com> <9AC1D2B7-CC71-4DFA-A327-632F5FF59E37@gmail.com> Message-ID: <1321692870.54439.YahooMailRC@web86706.mail.ird.yahoo.com> > >> > > for var in [value,value_1]: >> > > var = "green" >> >> > Um, that won't work. You typed that example too quickly. > > >> Excuse: It was early morning and I hadn't had any coffee... > >> In your defense Alan, after you typed that code in your response you >mentioned > the necessity of defining the variables: Yes, but that's still not good enough. The loop above only sets var to green >it doesn't change the values of the variables in the list. That's why you need >to use enumerate and access them via an index. Basically its just not a good >plan, best to avoid it. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Nov 19 12:04:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 19 Nov 2011 22:04:15 +1100 Subject: [Tutor] python telnet In-Reply-To: References: <4EC59E05.7050106@pearwood.info> Message-ID: <4EC78D2F.30204@pearwood.info> Rayon wrote: > I installed the telnet client but still the same error. How did you install it? Windows includes a telnet application, but it has to be enabled first: http://windows.microsoft.com/en-AU/windows-vista/Telnet-frequently-asked-questions If you run "telnet" from the Windows shell (cmd.exe), what happens? Until you can successfully run telnet from Windows, there isn't any point trying to run it from Python. -- Steven From evosweet at hotmail.com Sat Nov 19 12:44:42 2011 From: evosweet at hotmail.com (Rayon) Date: Sat, 19 Nov 2011 07:44:42 -0400 Subject: [Tutor] python telnet In-Reply-To: <4EC78D2F.30204@pearwood.info> References: <4EC59E05.7050106@pearwood.info> <4EC78D2F.30204@pearwood.info> Message-ID: I used the turn on turn off feature, and I can start a telnet session from the command line. -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Steven D'Aprano Sent: 19 November 2011 07:04 To: tutor at python.org Subject: Re: [Tutor] python telnet Rayon wrote: > I installed the telnet client but still the same error. How did you install it? Windows includes a telnet application, but it has to be enabled first: http://windows.microsoft.com/en-AU/windows-vista/Telnet-frequently-asked-que stions If you run "telnet" from the Windows shell (cmd.exe), what happens? Until you can successfully run telnet from Windows, there isn't any point trying to run it from Python. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From james at uplinkzero.com Sat Nov 19 13:23:17 2011 From: james at uplinkzero.com (James Chapman) Date: Sat, 19 Nov 2011 12:23:17 +0000 Subject: [Tutor] python telnet In-Reply-To: References: Message-ID: <1321705397.4ec79fb55c875@webmail.uplinkzero.com> traceback has: child = winspawn('telnet 192.168.0.55:210') When using telnet from CLI (on windows), you would type: telnet 192.168.0.55 210 Note the space between the IP and port number and not a :colon. Not sure this is your problem but probably worth mentioning. -- James At Saturday, 19/11/2011 on 11:44 Rayon wrote: > I used the turn on turn off feature, and I can start a telnet session from > the command line. > > -----Original Message----- > From: tutor-bounces+evosweet=hotmail.com at python.org > [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Steven > D'Aprano > Sent: 19 November 2011 07:04 > To: tutor at python.org > Subject: Re: [Tutor] python telnet > > Rayon wrote: > > I installed the telnet client but still the same error. > > How did you install it? Windows includes a telnet application, but it has to > be enabled first: > > http://windows.microsoft.com/en-AU/windows-vista/Telnet-frequently-asked-que > stions > > If you run "telnet" from the Windows shell (cmd.exe), what happens? > > Until you can successfully run telnet from Windows, there isn't any point > trying to run it from Python. > > > -- > Steven > > _______________________________________________ > 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 evosweet at hotmail.com Sat Nov 19 13:40:53 2011 From: evosweet at hotmail.com (Rayon) Date: Sat, 19 Nov 2011 08:40:53 -0400 Subject: [Tutor] python telnet In-Reply-To: <1321705397.4ec79fb55c875@webmail.uplinkzero.com> References: <1321705397.4ec79fb55c875@webmail.uplinkzero.com> Message-ID: Thanks but still not working, I am wondering if I need to give the script some kind of special permission to execute on windows 7. -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of James Chapman Sent: 19 November 2011 08:23 To: tutor at python.org Subject: Re: [Tutor] python telnet traceback has: child = winspawn('telnet 192.168.0.55:210') When using telnet from CLI (on windows), you would type: telnet 192.168.0.55 210 Note the space between the IP and port number and not a :colon. Not sure this is your problem but probably worth mentioning. -- James At Saturday, 19/11/2011 on 11:44 Rayon wrote: > I used the turn on turn off feature, and I can start a telnet session > from the command line. > > -----Original Message----- > From: tutor-bounces+evosweet=hotmail.com at python.org > [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of > Steven D'Aprano > Sent: 19 November 2011 07:04 > To: tutor at python.org > Subject: Re: [Tutor] python telnet > > Rayon wrote: > > I installed the telnet client but still the same error. > > How did you install it? Windows includes a telnet application, but it > has to be enabled first: > > http://windows.microsoft.com/en-AU/windows-vista/Telnet-frequently-ask > ed-que > stions > > If you run "telnet" from the Windows shell (cmd.exe), what happens? > > Until you can successfully run telnet from Windows, there isn't any > point trying to run it from Python. > > > -- > Steven > > _______________________________________________ > 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 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From mylesbroomes at hotmail.co.uk Sat Nov 19 13:53:40 2011 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sat, 19 Nov 2011 12:53:40 +0000 Subject: [Tutor] Guess my number game Message-ID: I am currently learning Python from the 'Python Programming for the Absolute Beginner' book. At the end of each chapter, you are given challenges and one of the challenges is to make a 'Guess My Number' game where the player thinks of a number between 1 and 100 and the computer has to guess the number. I'm having real trouble designing the 'guessing loop' where the computer guesses the players number. Here is the pseudocode I have written up: Welcome the user to the game Explain the rules of the game Wait for the user to think of a number Once the user has thought of their number, take a guess While the number has not been guessed correctly Increase the number of 'tries' by 1 Ask the user if the guess was too high or too low If the guess was too high guess lower If the guess was too low guess higher Once the number has been guessed correctly, tell the user the number of tries it took Exit the game Any help would be very much appreciated. From delegbede at dudupay.com Sat Nov 19 14:14:42 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sat, 19 Nov 2011 13:14:42 +0000 Subject: [Tutor] Guess my number game In-Reply-To: References: Message-ID: <1069654331-1321708481-cardhu_decombobulator_blackberry.rim.net-790933528-@b18.c12.bise7.blackberry> Hi Myles, Pseudocodes are what anyone would write but they only lay an idea of what you intend to achieve. To get quick help, you need to write the actual code and tell us where the trouble spot is. This way we can help you get along. Cheers. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: myles broomes Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sat, 19 Nov 2011 12:53:40 To: Subject: [Tutor] Guess my number game I am currently learning Python from the 'Python Programming for the Absolute Beginner' book. At the end of each chapter, you are given challenges and one of the challenges is to make a 'Guess My Number' game where the player thinks of a number between 1 and 100 and the computer has to guess the number. I'm having real trouble designing the 'guessing loop' where the computer guesses the players number. Here is the pseudocode I have written up: Welcome the user to the game Explain the rules of the game Wait for the user to think of a number Once the user has thought of their number, take a guess While the number has not been guessed correctly Increase the number of 'tries' by 1 Ask the user if the guess was too high or too low If the guess was too high guess lower If the guess was too low guess higher Once the number has been guessed correctly, tell the user the number of tries it took Exit the game Any help would be very much appreciated. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From joebatt at hotmail.co.uk Sat Nov 19 14:28:00 2011 From: joebatt at hotmail.co.uk (Joe Batt) Date: Sat, 19 Nov 2011 13:28:00 +0000 Subject: [Tutor] Pickling files in Python In-Reply-To: References: Message-ID: Hi all I am new to programming and on a very steep curve. I am using Python 3 to learn and I am having trouble understanding exactly what pickling is. I have written a program that asks for a URL and then writes the source code from the URL to a file, then pickles the file I just created. I am not sure why I pickle something as opposed to just saving it as a normal file? I saved the url source code file as a .txt and also the pickled file as .txt. I am not sure of the filetype I should save a pickled file as.When I look at the files (the saved source file and the pickled file) they look the same. I am viewing them in notepad on the Mac. Many thanksJoe #################################################################### Pickle an object- Puzzle 5 # Joe Batt 18 Nov 2011 - http://www.pythonchallenge.com/pc/def/peak.html################################################################### import pickleimport urllib def geturlfile(urlfile):#gets the user URL from main opens it and saves it to var fileurl from urllib.request import urlopen fileurl=urlopen(urlfile)#opens the file on computer and writes the var fileurl to it html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','w') for line in fileurl.readlines(): linestring=line.decode("utf-8") #ensures written in string not byte html_file.write(linestring) html_file.close() #closes the puzzle file#just prints file to check its correct html_file=open('///Users/joebatt/Desktop/python/puzzle5.txt','r') filecontents=html_file.read() html_file.close() print (filecontents) print (type(filecontents)) #pickles the file filecontents containing the url file pickledfile=open('///Users/joebatt/Desktop/python/pickledpuzzle5.txt','wb') pickle.dump(filecontents,pickledfile) pickledfile.close() return () # Main programurlfile=input('Please input the URL ')geturlfile(urlfile) -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Nov 19 14:42:18 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 19 Nov 2011 13:42:18 +0000 Subject: [Tutor] Pickling files in Python In-Reply-To: References: Message-ID: Hi Joe, On 19 November 2011 13:28, Joe Batt wrote: > I am new to programming and on a very steep curve. I am using Python 3 to > learn and I am having trouble understanding exactly what pickling is. > I have written a program that asks for a URL and then writes the source > code from the URL to a file, then pickles the file I just created. > I am not sure why I pickle something as opposed to just saving it as a > normal file? > Pickling is a way for you to write arbitrary Python objects (or object structures) to file without having to think about their structure when writing (and read them back as well obviously). In general programming terms this is often referred to as serializing and deserializing. Anyway, it follows then that if you're handling the writing of data to a file yourself, such as when you're directly downling the textual content of a web page and writing that directly to a simple text file "by hand", that pickling is redundant/not relevant to your intent. So, either you write and read the text yourself, or (for example) you put the web page data into a list and then pickle (or unpickle) the list object to/from a file using Python's pickling support. Aside: If (as I'm suspecting) you're busy with puzzle 5 on the Python challenge, then I'll given you this hint: IIRC, there's a pickle file that can be downloaded from the Python challenge website, hidden somewhere in the puzzle 5 page (referenced in it directly or indirectly) that you're supposed to be interrogating in order to solve the puzzle. You're not supposed to be doing any pickling of the base web page of puzzle 5 at all. You *are* supposed to get the pickle data from the site, get it loaded up into Python (e.g. make it back into a Python object) and then figure out what it contains. Hope that helps, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sat Nov 19 14:59:58 2011 From: d at davea.name (Dave Angel) Date: Sat, 19 Nov 2011 08:59:58 -0500 Subject: [Tutor] A recursion question In-Reply-To: <4EC74E52.8050609@gmail.com> References: <4EC65ABF.7080703@gmail.com> <4EC673F6.6050300@davea.name> <4EC6B154.1090003@gmail.com> <4EC74E52.8050609@gmail.com> Message-ID: <4EC7B65E.7040906@davea.name> On 11/19/2011 01:36 AM, K?n?thia M?chane wrote: > On 11/19/2011 06:03 AM, Asokan Pichai wrote: >> Another way to do that is to avoid any intermediate variables altogether >> That may be easier to understand YMMV >> >> def counter(mylist, val): >> if len(mylist == 0): >> return 0 >> if mylist[0] == val: >> return 1 + counter(mylist[1:], val) >> else: >> return counter(mylist[1:]) > The intermediate variable explanation by Dave actually clinched it for > me. Actually, the one I wrote is suspiciously similar to yours ;-). > Anyway, thanks Asokan! FWIW, Asokan's code looks exactly right to me. But I figured the version I supplied would make it clearer to you what was happening. The key to thinking recursively is to figure out exactly what the function as a whole does, then figure out how to use exactly such a function that solves a somewhat smaller problem, to solve the whole thing. Since the function as a whole takes in a list, and returns a count, that's the way to use the "smaller problem" function. Both Asokan's answer and mine do that. But his "local variable" is implied in the expressions, where I made it explicit so you could see what was happening. If you're familiar with the mathematical proof by induction, this is very analogous. -- DaveA From cranky.frankie at gmail.com Sat Nov 19 15:06:24 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Sat, 19 Nov 2011 09:06:24 -0500 Subject: [Tutor] command=F.quit not closing the sample TK program in Vista Message-ID: I'm playing around with the Tkinter examples on: http://www.alan-g.me.uk/l2p/index.htm and, at least on my Vista laptop, the sample window will not close when you click the Quit button, which is: bQuit = Button(fButtons, text="Quit", command=F.quit) Anyone else have this problem with the sample programs? Python just hangs, and Vista says it's not responding. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From cranky.frankie at gmail.com Sat Nov 19 15:59:31 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Sat, 19 Nov 2011 09:59:31 -0500 Subject: [Tutor] command=F.quit not closing the sample TK program in Vista Message-ID: More info: I added C:\Python32 to the path environment variable in Vista, rebooted, and tried the test programs at the command prompt, and it says it can't find the program. If I type Python at the command prompt it opens the Python intrepreter, but it will not run the test.py program. Now I'm really confused:) -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From bgailer at gmail.com Sat Nov 19 16:16:40 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 19 Nov 2011 10:16:40 -0500 Subject: [Tutor] Guess my number game In-Reply-To: <1069654331-1321708481-cardhu_decombobulator_blackberry.rim.net-790933528-@b18.c12.bise7.blackberry> References: <1069654331-1321708481-cardhu_decombobulator_blackberry.rim.net-790933528-@b18.c12.bise7.blackberry> Message-ID: <4EC7C858.7050902@gmail.com> On 11/19/2011 8:14 AM, delegbede at dudupay.com wrote: > Hi Myles, > > Pseudocodes are what anyone would write but they only lay an idea of what you intend to achieve. > > To get quick help, you need to write the actual code and tell us where the trouble spot is. > > This way we can help you get along. [snip] Another way of saying that is: Translate those parts of the pseudocode to Python that you can. Tell us where you are stuck. The book certainly gives you enough information to do that. -- Bob Gailer 919-636-4239 Chapel Hill NC From joebatt at hotmail.co.uk Sat Nov 19 16:33:16 2011 From: joebatt at hotmail.co.uk (Joe Batt) Date: Sat, 19 Nov 2011 15:33:16 +0000 Subject: [Tutor] Further pickle problem :0( Message-ID: Hi all again Thank you to those that have helped me previously with this problem it is appreciated. Thanks to Walter I have actually found the pickle file that I am trying to restore to a variable however I am getting the following error Traceback (most recent call last): File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in a=pickle.load(file) File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0]UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 8: ordinal not in range(128) The simple program I am using to 'depickle' is file=open('///Users/joebatt/Desktop/banner.p.webarchive','r')a=pickle.load(file)file.close()print (a) I am using Python 3 and working through the Python Challenges on www.pythonchallenge.com, the site is a few years old and I was thinking that possibly it is based around Python 2.x ??? If thats the case is the error due to me using 3 as opposed to 2.x Many thanksJoe -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 19 17:46:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Nov 2011 16:46:58 +0000 Subject: [Tutor] Guess my number game In-Reply-To: References: Message-ID: On 19/11/11 12:53, myles broomes wrote: > ...Here is the pseudocode I have written up: > > Once the user has thought of their number, take a guess > While the number has not been guessed correctly > Increase the number of 'tries' by 1 > Ask the user if the guess was too high or too low > If the guess was too high > guess lower > If the guess was too low > guess higher > Once the number has been guessed correctly, tell the user the number of tries it took Your pseudocode looks fine. Try writing that as Python. You'll need to use raw_input() if using python 2 or input() in Python 3 You will want to convert the input to an int() You will want to use the random module, and probably the randrange function within it. You will need variables to store the number of tries and the latest guess, Try it. If you get stuck show us what you've done, any error messages and tell us what you don't understand. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Nov 19 17:53:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Nov 2011 16:53:12 +0000 Subject: [Tutor] command=F.quit not closing the sample TK program in Vista In-Reply-To: References: Message-ID: On 19/11/11 14:59, Cranky Frankie wrote: I suspect you were trying to run the program from IDLE or Pythonwin? If so don't. Run the GUI examples from the command line or via Windows Explorer. If you double click the .py file a DOS Box may open in the background, just ignore it for now. But the GUI window will also appear and should work as expected. Once everything works you can rename the file .pyw to get rid of the background DOS box... Try that and let me know how it goes, either via the list or using the mail link at the bottom of the tutor pages. There is a very small chance that this is a Windows Vista/7 issue since I have only run the code in XP... But I don't thoink that should make any difference. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Nov 19 17:54:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Nov 2011 16:54:44 +0000 Subject: [Tutor] Further pickle problem :0( In-Reply-To: References: Message-ID: On 19/11/11 15:33, Joe Batt wrote: > file=open('///Users/joebatt/Desktop/banner.p.webarchive','r') Try opening it on binary mode. Pickle files are not plain text. > a=pickle.load(file) > file.close() > print (a) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From carroll at tjc.com Sat Nov 19 19:26:36 2011 From: carroll at tjc.com (Terry Carroll) Date: Sat, 19 Nov 2011 10:26:36 -0800 (PST) Subject: [Tutor] The Perennial 3.2 vs 2.7 In-Reply-To: References: Message-ID: On Thu, 17 Nov 2011, Wayne Werner wrote: > On Thu, Nov 17, 2011 at 8:45 PM, Mark Lybrand wrote: > > so, use my 2.7 and not my 3.2 for my study? Or use my 3.2 for > study and then do what I have to in 2.7 after including those > lines? > > Honestly it probably doesn't matter. Many 3rd party libraries have now > been ported to Python 3.x, so unless you have a particular library > you're interested in, I would start with 3.2 until you find something > you can't do. Personally, that's the biggy for me, and why I remain on 2.7. wxPython has not yet been ported to Python 3, and that's a substantial big deal for me. From o0MB0o at hotmail.se Sat Nov 19 20:01:50 2011 From: o0MB0o at hotmail.se (Mic) Date: Sat, 19 Nov 2011 20:01:50 +0100 Subject: [Tutor] Can I shorten this code? In-Reply-To: References: Message-ID: Hi! I am new to programming and it have recently come to my attention that alot of my code could be shortened. I have managed to shorten some of the code, but I ran into a problem with this piece of code: #Testing changing color and text on two buttons in a GUI. from tkinter import* value1=("green") click1=1 value2=("green") click2=1 class Window(Frame): def __init__(self,master): super (Window,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): #Creates hello button1 self.hello_bttn1=Button(self,bg=value1) self.hello_bttn1["text"]="Hi_1" self.hello_bttn1["command"]=self.change_value_hellobttn1 self.hello_bttn1.grid() #Creates hello button2 self.hello_bttn2=Button(self,bg=value2) self.hello_bttn2["text"]="Hi_1" self.hello_bttn2["command"]=self.change_value_hellobttn2 self.hello_bttn2.grid() def change_value_hellobttn1(self): def change_click(): global click1 click1*=-1 change_click() if click1==-1: self.hello_bttn1.configure(bg="red") self.hello_bttn1.configure(text="Hi_2") def change_global1(): global value1 value1=("red") change_global1() elif click1==1: self.hello_bttn1["text"]="Hi_1" self.hello_bttn1.configure(bg="green") def change_global2_1(): global value1 value1=("green") change_global2_1() #------------------------------------------------- def change_value_hellobttn2(self): def change_click2(): global click2 click2*=-1 change_click2() if click2==-1: self.hello_bttn2.configure(bg="red") self.hello_bttn2.configure(text="Hi_2") def change_global2(): global value2 value2=("red") change_global2() elif click2==1: self.hello_bttn2["text"]="Hi_1" self.hello_bttn2.configure(bg="green") def change_global2_2(): global value2 value2=("green") change_global2_2() Imagine now that I want to do the same thing with 8 buttons, that I did to these two buttons. How would I shorten this? Otherwise I repeat a lot of my code, and I would like to avoid that. Thank you! root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() From mlybrand at gmail.com Sat Nov 19 20:03:36 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Sat, 19 Nov 2011 11:03:36 -0800 Subject: [Tutor] Fwd: Re: The Perennial 3.2 vs 2.7 In-Reply-To: References: Message-ID: Whoops. Hit reply only again. Sorry terry. ---------- Forwarded message ---------- From: "Mark Lybrand" Date: Nov 19, 2011 11:02 AM Subject: Re: [Tutor] The Perennial 3.2 vs 2.7 To: "Terry Carroll" Based on what everyone has said and the fact that my learning material is for 3, I think I will be okay learning 3 and will stumble into the gotchas as I develop with 2.7. Luckily my experience as a programmer should keep me warm at night :) Mark PS. I shall resist the temptation to force python to use curly braces and will learn to embrace indentation. On Nov 19, 2011 10:51 AM, "Terry Carroll" wrote: > On Thu, 17 Nov 2011, Wayne Werner wrote: > > On Thu, Nov 17, 2011 at 8:45 PM, Mark Lybrand wrote: >> >> so, use my 2.7 and not my 3.2 for my study? Or use my 3.2 for >> study and then do what I have to in 2.7 after including those >> lines? >> >> Honestly it probably doesn't matter. Many 3rd party libraries have now >> been ported to Python 3.x, so unless you have a particular library you're >> interested in, I would start with 3.2 until you find something you can't do. >> > > Personally, that's the biggy for me, and why I remain on 2.7. wxPython > has not yet been ported to Python 3, and that's a substantial big deal for > me. > > ______________________________**_________________ > 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 kinuthia.muchane at gmail.com Sat Nov 19 20:11:42 2011 From: kinuthia.muchane at gmail.com (=?UTF-8?B?S8SpbsWpdGhpYSBNxaljaGFuZQ==?=) Date: Sat, 19 Nov 2011 22:11:42 +0300 Subject: [Tutor] A recursion question In-Reply-To: <4EC7B65E.7040906@davea.name> References: <4EC65ABF.7080703@gmail.com> <4EC673F6.6050300@davea.name> <4EC6B154.1090003@gmail.com> <4EC74E52.8050609@gmail.com> <4EC7B65E.7040906@davea.name> Message-ID: <4EC7FF6E.4080401@gmail.com> On 11/19/2011 04:59 PM, Dave Angel wrote: > On 11/19/2011 01:36 AM, K?n?thia M?chane wrote: >> On 11/19/2011 06:03 AM, Asokan Pichai wrote: >>> Another way to do that is to avoid any intermediate variables >>> altogether >>> That may be easier to understand YMMV >>> >>> def counter(mylist, val): >>> if len(mylist == 0): >>> return 0 >>> if mylist[0] == val: >>> return 1 + counter(mylist[1:], val) >>> else: >>> return counter(mylist[1:]) >> The intermediate variable explanation by Dave actually clinched it >> for me. Actually, the one I wrote is suspiciously similar to yours >> ;-). Anyway, thanks Asokan! > > FWIW, Asokan's code looks exactly right to me. But I figured the > version I supplied would make it clearer to you what was happening. It made it crystal clear, thank you very much. > > The key to thinking recursively is to figure out exactly what the > function as a whole does, then figure out how to use exactly such a > function that solves a somewhat smaller problem, to solve the whole > thing. Since the function as a whole takes in a list, and returns a > count, that's the way to use the "smaller problem" function. Both > Asokan's answer and mine do that. But his "local variable" is implied > in the expressions, where I made it explicit so you could see what was > happening. And I saw what was happening ;-) > > If you're familiar with the mathematical proof by induction, this is > very analogous. -- K?n?thia S 1? 8' 24? E 36? 57' 36? 1522m From joebatt at hotmail.co.uk Sat Nov 19 20:37:49 2011 From: joebatt at hotmail.co.uk (Joe Batt) Date: Sat, 19 Nov 2011 19:37:49 +0000 Subject: [Tutor] Stacks and Stack underflow/Stack overflow Message-ID: Hi All Could some kind soul please explain why you get a stack underflow and a stack overflow. I am getting the following error in Python 3 Traceback (most recent call last): File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in a=pickle.load(file)_pickle.UnpicklingError: unpickling stack underflow when I am running the following import picklefile=open('///Users/joebatt/Desktop/banner.p.webarchive','rb')a=pickle.load(file)file.close()print (a) Now I am very much a learner so please correct and explain my misunderstanding. I am visualising my program as taking the 'banner.p.webarchive' and and pushing it onto the stack byte by byte until it reaches the end of the file i.e. A B C ---> push C then B then A A B C ---> A B C Then the program pops the stack C does what it needs to do to unpickle it then pops B does what it needs to unpickle then A. A ----->C B ABC My understanding is that the stack underflow means that it is trying to pop from the top of the stack and there is nothing to pop i.e. it is empty. Why though if the stack has been loaded with the file 'banner.p' in my program does it say there is nothing to pop and thus a stack underflow? Also my understanding of the stack overflow is that the stack itself is a finite size and when it has tried to push the file to the stack it didn't fit because it was too big, i.e. in my example if the stack was only big enough for 2 letters and I tried to push ABC it would give a stack overflow because I was trying to push 3. How would I deal with this? Can I make the stack bigger or a way to just push A B pop AB then push C and pop it. Thank you guys Im sorry for probably what are very silly basic questions. Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Sat Nov 19 20:48:18 2011 From: rhettnaxel at gmail.com (Alexander) Date: Sat, 19 Nov 2011 14:48:18 -0500 Subject: [Tutor] Usenet comp.lang.python Message-ID: Hi. Does anybody know about using the comp.lang.python usenet news feed(?) ? I'd like help configuring it. I can't seem to find documentation helping me. Thanks for reading, -- Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Sat Nov 19 21:26:32 2011 From: carroll at tjc.com (Terry Carroll) Date: Sat, 19 Nov 2011 12:26:32 -0800 (PST) Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: References: Message-ID: On Sat, 19 Nov 2011, Joe Batt wrote: > Hi All? > Could some kind soul please explain why you get a stack underflow and a > stack overflow. > > I am getting the following error in Python 3 > > Traceback (most recent call last): > ? File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in > > ? ? a=pickle.load(file) > _pickle.UnpicklingError: unpickling stack underflow > > when I am running the following > > import pickle > file=open('///Users/joebatt/Desktop/banner.p.webarchive','rb') > a=pickle.load(file) > file.close() > print (a) When you created the pickle file, did you create it in binary form (with "wb")? From wprins at gmail.com Sat Nov 19 21:52:10 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 19 Nov 2011 20:52:10 +0000 Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: References: Message-ID: Hi, On 19 November 2011 19:37, Joe Batt wrote: > I am getting the following error in Python 3 > > Traceback (most recent call last): > File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in > > a=pickle.load(file) > _pickle.UnpicklingError: unpickling stack underflow > > when I am running the following > > import pickle > file=open('///Users/joebatt/Desktop/banner.p.webarchive','rb') > a=pickle.load(file) > file.close() > print (a) > > OK, there's basically 2 things you can infer from the error message: 1) The unpickling failed (to which you should ask yourself, why?), and 2) The picking/unpickling logic must use some sort of stack internally. The first is the most important bit as far as you're concerned, and the second is for the most part irrelevant from your point of view, since you're not really interested in the inner workings of pickling and unpickling. So why might the unpickling be failing? Broadly speaking, it must be one of 2 things -- either you're doing it wrong, or you're putting the wrong stuff in, so to speak. The first seems unlikely, so it's likely the second. So, I'm with Terry on this one, I'd guess that the input that you're feeding into pickle.load() is not a valid pickle file, probably because pickle files are binary files and you probably opened it as a text file. See here: http://docs.python.org/py3k/library/functions.html#open Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Sat Nov 19 23:41:37 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Sat, 19 Nov 2011 22:41:37 +0000 Subject: [Tutor] How do i show discount? Message-ID: def shop(total_spend): min_spend=25 discount_amount=150 discount=0.05 if total_spend >= min_spend and total_spend > discount_amount: checkout=total_spend-(total_spend*discount) discount=total_spend*discount else: checkout = total_spend discount = 0 return checkout def main(): spend = input('Enter the amount you spent: ') while spend<25: print "Error, min spend is ?25 in this shop!" spend = input('Enter the amount you spent: ') else: total = shop(spend) print 'Your bill comes to',total,"\n","your discount was",discount main () #program works but how would i show the discount in main? I saved as text file in notepad........! Many thanks!!!!!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: shop_discount2.py Type: text/x-script.phyton Size: 686 bytes Desc: not available URL: From alan.gauld at btinternet.com Sat Nov 19 23:47:17 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 19 Nov 2011 22:47:17 +0000 (GMT) Subject: [Tutor] Fw: Further pickle problem :0( In-Reply-To: , References: , Message-ID: <1321742837.46306.YahooMailRC@web86702.mail.ird.yahoo.com> Forwarding to list Always use ReplyAll, it keeps everyone involved. I don't know what the error means, hopefully somebody else does... Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Forwarded Message ---- From: Joe Batt To: alan.gauld at btinternet.com Sent: Saturday, 19 November, 2011 18:09:24 Subject: RE: [Tutor] Further pickle problem :0( Thanks for your help Alan, I tried that previously and get the error Traceback (most recent call last): File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in a=pickle.load(file) _pickle.UnpicklingError: unpickling stack underflow Any ideas? Thanks Joe (ps great web site, very helpful) > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sat, 19 Nov 2011 16:54:44 +0000 > Subject: Re: [Tutor] Further pickle problem :0( > > On 19/11/11 15:33, Joe Batt wrote: > > > file=open('///Users/joebatt/Desktop/banner.p.webarchive','r') > > Try opening it on binary mode. > Pickle files are not plain text. > > > a=pickle.load(file) > > file.close() > > print (a) > > -- > Alan G > 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 alan.gauld at btinternet.com Sat Nov 19 23:52:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Nov 2011 22:52:42 +0000 Subject: [Tutor] command=F.quit not closing the sample TK program in Vista In-Reply-To: References: Message-ID: On 19/11/11 14:59, Cranky Frankie wrote: > I added C:\Python32 to the path environment variable in Vista, > rebooted, and tried the test programs at the command prompt, and it > says it can't find the program. You need to provide the full path to the file. C\WINDOWS> python C:\the\full\path\to\myfile.py Either that or CD to the folder first: C\WINDOWS> CD C:\the\full\path\to C:\the\full\path\to> python myfile.py The easiest way is just to double click the file in explorer, the associations should all be set up by the installer... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Nov 20 00:17:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Nov 2011 10:17:41 +1100 Subject: [Tutor] Usenet comp.lang.python In-Reply-To: References: Message-ID: <4EC83915.7000101@pearwood.info> Alexander wrote: > Hi. Does anybody know about using the comp.lang.python usenet news feed(?) ? > I'd like help configuring it. I can't seem to find documentation helping me. > Thanks for reading, What is there to configure? It's a news group. You tell your news reader program to subscribe to the news group, that's all the configuration it needs. There's nothing *specific* to comp.lang.python that needs configuration -- all the work (if any!) is getting usenet working in the first place. (1) Do you have a news reader program? If the answer is No, then you need to get one. (2) Does your ISP offer usenet? If the answer is No, then you need to change ISPs to one that does, or use a paid usenet provider. (3) Does your firewall block news? If the answer is Yes, then you need to punch a hole in the firewall to allow it. If you don't know whether your firewall blocks news, it probably doesn't. (4) Open your news reader program and tell it where to find news, e.g. look for a Setup or Preferences or Edit News Server command, or similar. Put in the name and port number for the news server, which will probably be something like "news.MY-ISP.com" (whatever MY-ISP is). The port number is almost certainly the default 119. (5) If you need to add a username and password (you probably don't, if it is provided by your ISP), add it now. (6) Find a command like "Download Full Group List" or "Refresh Group List" or similar. Wait; this will take a while. (7) Find comp.lang.python in the list and mark it as Subscribed. If comp.lang.python isn't in the list, complain to your news provider, or change news providers. (8) Enjoy reading comp.lang.python. -- Steven From alan.gauld at btinternet.com Sun Nov 20 00:18:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Nov 2011 23:18:01 +0000 Subject: [Tutor] Can I shorten this code? In-Reply-To: References: Message-ID: On 19/11/11 19:01, Mic wrote: > Hi! > I am new to programming and it have recently come to my attention that > alot of my code could be shortened. Most peoples code could be shortened. And most of it would be the worse for it. There are a few occasions when shortening makes sense, especially if its all repeated lines or just plain superflous code. But, in general, aim to write readable code, not just short code. > from tkinter import* > > value1=("green") You don't need parentheses here, they are doing nothing. > click1=1 Rather than worrying about shortening try to think about more meaningful names for you variables. Why do they exist? Explain it in your names. In this case click1 is a flag to indicate the state of button1. And what does button1 do? Name it to make it clear. So a better name could be buttonOneClicked = True # Use True/False not 1/-1 to express boolean > value2=("green") > click2=1 Same here buttonTwoClicked = True > class Window(Frame): > def create_widgets(self): > > #Creates hello button1 > self.hello_bttn1=Button(self,bg=value1) > self.hello_bttn1["text"]="Hi_1" > self.hello_bttn1["command"]=self.change_value_hellobttn1 You could do that all in one line: self.hello_bttn1=Button(self, bg=value1, text="Hi_1", command=self.change_value_hellobttn1) > self.hello_bttn1.grid() > > #Creates hello button2 > self.hello_bttn2=Button(self,bg=value2) > self.hello_bttn2["text"]="Hi_1" > self.hello_bttn2["command"]=self.change_value_hellobttn2 > self.hello_bttn2.grid() Same again > def change_value_hellobttn1(self): > > def change_click(): > global click1 > click1*=-1 If you use boolean values this becomes click1 = not click1 > change_click() > if click1==-1: and this becomes if click1 Or with a better name if buttonOneClicked: > self.hello_bttn1.configure(bg="red") > self.hello_bttn1.configure(text="Hi_2") Again you can use a single line: self.hello_bttn1.configure(bg="red", text="Hi_2") > def change_global1(): > global value1 > value1=("red") Again a bad name for the function. It changes value1 not global1... Although I'm not sure what the purpose of these values are... Also, although legal Python its usual to define all embedded functions in one place at the top of the containing function rather than inside an if/else branch. And even more commonly to define them as methods of the class rather than embedded functions. > change_global1() > > elif click1==1: Could just be an else since click1 is alwaysd either 1 or -1 Or buttonOneClicked is always True or False using my suggestions. > self.hello_bttn1["text"]="Hi_1" > self.hello_bttn1.configure(bg="green") Again you can use one line self.hello_bttn1.configure(bg="green", text="Hi_1") > def change_global2_1(): > global value1 > value1=("green") And this is completely redundant since it does exactly the same as the other function, all you need is a parameter when you call it, like so: def setValue1(val): global value1 value1 = val > change_global2_1() And this becomes setValue1("green") But ultimately you could just have set it directly in your outer function, it's hardly worth the cost of defining a function, unless you intend to add more to it later. > def change_value_hellobttn2(self): All of the above comments apply here too. > Imagine now that I want to do the same thing with 8 buttons, that I did > to these two buttons. How would I shorten this? Generally you build a data table with all the config parameters that will varty then you build a loop to read the values from the data table. Store the created buttons in a list or dictionary. I'll leave that as an exercise :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Nov 20 00:22:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Nov 2011 10:22:14 +1100 Subject: [Tutor] How do i show discount? In-Reply-To: References: Message-ID: <4EC83A26.4050201@pearwood.info> ADRIAN KELLY wrote: > how would i show the discount in main? Look at your shop() function: > def shop(total_spend): > min_spend=25 > discount_amount=150 > discount=0.05 > if total_spend >= min_spend and total_spend > discount_amount: > checkout=total_spend-(total_spend*discount) > discount=total_spend*discount > else: > checkout = total_spend > discount = 0 > return checkout It calculates the discount, and then does nothing with it except throw the answer away. So the first thing you need is to return the checkout and the discount: return (checkout, discount) Now look at main(): > def main(): > spend = input('Enter the amount you spent: ') > while spend<25: > print "Error, min spend is ?25 in this shop!" > spend = input('Enter the amount you spent: ') > else: > total = shop(spend) > print 'Your bill comes to',total,"\n","your discount was",discount It collects the total spent, but needs to collect both total and discount: total, discount = shop(spend) -- Steven From alan.gauld at btinternet.com Sun Nov 20 00:27:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Nov 2011 23:27:42 +0000 Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: References: Message-ID: On 19/11/11 19:37, Joe Batt wrote: > File "/Users/joebatt/Desktop/python/pickling puzzle 5.py", line 39, in > > a=pickle.load(file) > _pickle.UnpicklingError: unpickling stack underflow > > when I am running the following > > import pickle > file=open('///Users/joebatt/Desktop/banner.p.webarchive','rb') I don't know why the error, it suggests the data file is corrupted. You may need to fetch another copy. Make sure you save the file rather than try to open it so that it downloads in binary format or it may be truncated... However, having downloaded it I'm not sure why you are specifying the filename with /// at the front. It looks like you are on Linux? You should only need file=open('/Users/joebatt/Desktop/banner.p.webarchive','rb') But that shouldn't really make any difference to the end result. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kellyadrian at hotmail.com Sun Nov 20 00:38:42 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Sat, 19 Nov 2011 23:38:42 +0000 Subject: [Tutor] FW: How do i show discount?(sorted) In-Reply-To: References: , Message-ID: From: kellyadrian at hotmail.com To: kellyadrian at hotmail.com Subject: RE: How do i show discount? Date: Sat, 19 Nov 2011 23:34:27 +0000 sorted it guys, used a third function.... Adrian From: kellyadrian at hotmail.com To: tutor at python.org Subject: How do i show discount? Date: Sat, 19 Nov 2011 22:41:37 +0000 def shop(total_spend): min_spend=25 discount_amount=150 discount=0.05 if total_spend >= min_spend and total_spend > discount_amount: checkout=total_spend-(total_spend*discount) discount=total_spend*discount else: checkout = total_spend discount = 0 return checkout def main(): spend = input('Enter the amount you spent: ') while spend<25: print "Error, min spend is ?25 in this shop!" spend = input('Enter the amount you spent: ') else: total = shop(spend) print 'Your bill comes to',total,"\n","your discount was",discount main () #program works but how would i show the discount in main? I saved as text file in notepad........! Many thanks!!!!!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 20 00:47:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 19 Nov 2011 23:47:25 +0000 Subject: [Tutor] Usenet comp.lang.python In-Reply-To: References: Message-ID: On 19/11/11 19:48, Alexander wrote: > Hi. Does anybody know about using the comp.lang.python usenet news feed(?) ? > I'd like help configuring it. I can't seem to find documentation helping me. > Thanks for reading, The easiest way is probably to set up your newsreader to point at the gmane server. On Thunderbird I have the following server settings: Server name: news.gmane.org Port 119 The rest are defaults. Having set up the server the rest depends on your reader, but basically you subscribe to the news groups you are interested in. For comp.lang.python its called: gmane.comp.python.general -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Nov 20 01:03:15 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Nov 2011 11:03:15 +1100 Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: References: Message-ID: <4EC843C3.8040805@pearwood.info> Joe Batt wrote: > Hi All Could some kind soul please explain why you get a stack > underflow and a stack overflow. I don't, because I never make misteaks. *grin* Stack underflow and stack overflow are generic errors. You get a stack underflow when you have (say) five items on a stack and try to retrieve six: if you try to retrieve more items than are actually there, the stack underflows. Stack overflow occurs when you fill a stack. Many, but not all, applications set their stack to have a maximum size, to prevent it growing without bounds and using all your memory. So if the maximum size is (say) 1000 items, and you push 1001 items onto it, the stack will be filled and you get an overflow. *Specifically* related to pickle, you get an stack underflow when either your pickle file is corrupt, or because you aren't using it correctly. Or (very unlikely) pickle has a bug. You can't manually change the stack. You shouldn't need to change the stack. An application could have dozens of stacks, for all you know. (Sometimes people talk about "the stack", meaning the stack used by the operating system for executing code. You don't want to touch that, even if you could, which fortunately you can't.) Without seeing how you created your pickle file, and what you did to it in the meantime, it is impossible to say why it is corrupt or how it became corrupted. But my guess is that you may have opened the file in Notepad or something, and hit save, and Notepad "helpfully" changed the contents somehow. Result: a corrupt file that pickle can no longer read correctly. Please run this code and confirm that pickle works correctly for you: # Create some data. a = {'bb': None, 'cc': [1, 2, 3], 'dd': 42} b = [None, (23, 24, 25), "spam"] # Save it to a pickle file. import pickle f = open('///Users/joebatt/Desktop/tmp12345', 'wb') pickle.dump(a, f) pickle.dump(b, f) f.close() # Read it back in. f = open('///Users/joebatt/Desktop/tmp12345', 'rb') c = pickle.load(f) d = pickle.load(f) f.close() # Confirm the values are correct. assert a == c assert b == d -- Steven From steve at pearwood.info Sun Nov 20 01:09:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 20 Nov 2011 11:09:40 +1100 Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: References: Message-ID: <4EC84544.1040508@pearwood.info> Walter Prins wrote: > pickle files are binary files and you probably opened it as a text file. > See here: http://docs.python.org/py3k/library/functions.html#open Not so. Pickle protocol 0 is text, and it happens to be the default protocol used if you don't instruct it different. So by default, pickles are text unless you specifically use a binary protocol. -- Steven From alan.gauld at btinternet.com Sun Nov 20 02:29:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Nov 2011 01:29:50 +0000 Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: <4EC84544.1040508@pearwood.info> References: <4EC84544.1040508@pearwood.info> Message-ID: On 20/11/11 00:09, Steven D'Aprano wrote: > Walter Prins wrote: > >> pickle files are binary files and you probably opened it as a text file. >> See here: http://docs.python.org/py3k/library/functions.html#open > > Not so. Pickle protocol 0 is text, and it happens to be the default > protocol used if you don't instruct it different. So by default, pickles > are text unless you specifically use a binary protocol. Now that's interesting. All the examples I've sen use binary files. And even the examples on the documentation pages use binary mode. I just assumed therefore that pickles would, by their nature, be binary... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Sun Nov 20 02:40:19 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 20 Nov 2011 02:40:19 +0100 Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: References: <4EC84544.1040508@pearwood.info> Message-ID: On Sun, Nov 20, 2011 at 2:29 AM, Alan Gauld wrote: > On 20/11/11 00:09, Steven D'Aprano wrote: >> >> Walter Prins wrote: >> >>> pickle files are binary files and you probably opened it as a text file. >>> See here: http://docs.python.org/py3k/library/functions.html#open >> >> Not so. Pickle protocol 0 is text, and it happens to be the default >> protocol used if you don't instruct it different. So by default, pickles >> are text unless you specifically use a binary protocol. > > Now that's interesting. All the examples I've sen use binary files. > And even the examples on the documentation pages use binary mode. > I just assumed therefore that pickles would, by their nature, be binary... > If you open the file in text mode and it happens to use a binary protocol, things won't work because the binary might incorporate stuff interpreted as newlines by the file object, with newline conversion and such. If you open the file in binary it'll always work because the file object doesn't touch the contents. So you always open the files in binary mode to be on the safe side. Hugo From wprins at gmail.com Sun Nov 20 02:47:22 2011 From: wprins at gmail.com (Walter Prins) Date: Sun, 20 Nov 2011 01:47:22 +0000 Subject: [Tutor] Stacks and Stack underflow/Stack overflow In-Reply-To: <4EC84544.1040508@pearwood.info> References: <4EC84544.1040508@pearwood.info> Message-ID: Hi Steve/Joe, On 20 November 2011 00:09, Steven D'Aprano wrote: > Walter Prins wrote: > > pickle files are binary files and you probably opened it as a text file. >> See here: http://docs.python.org/py3k/**library/functions.html#open >> > > Not so. Pickle protocol 0 is text, and it happens to be the default > protocol used if you don't instruct it different. So by default, pickles > are text unless you specifically use a binary protocol. Well I stand corrected, thanks! :) For some reason I thought they were binary by default too, but hey ho... will try to remember that for future reference. To Joe, another hint: Note that you can /directly/ pass the /file-like/ object returned by urllib directly to pickle.... So, pickle can effectively unpickle data read directly from the website (via a file-like object that actually reads from the webiste, not a real file), and you then needn't care what format the pickle file (on the website) is in... Neat eh? This by the way, is a small demonstration of "duck typing" -- Pickle doesn't really care whether what you pass into pickle.load() method is actually *really* a file object -- As long as it walks like a file, and quacks like a file, sufficiently well for pickle's purposes then everyone's happy and you get back an unpickled object... ;) Walter PS You can get the unpickled object in Python for this puzzle with between 1 and 3 lines of code, depending on how much nesting of calls you use... -------------- next part -------------- An HTML attachment was scrubbed... URL: From evosweet at hotmail.com Sun Nov 20 00:42:28 2011 From: evosweet at hotmail.com (Rayon) Date: Sat, 19 Nov 2011 19:42:28 -0400 Subject: [Tutor] python telnet In-Reply-To: References: <1321705397.4ec79fb55c875@webmail.uplinkzero.com> Message-ID: Hi all got my code to work. I used an in queue and an out queue passed it to the telnet session . I am sending commands to the in_q using sockets and passing them back data with the out_q. Below is the code for a nonstop python telnet session. Thanks for the help, it got me thinking and that was worth it. def end_less(): """ Start telnet session and never stop it :) """ global host global cmd_q global out_q message = """ HLR DOWN ERROR """ try: hia_tel = telnetlib.Telnet(host) hia_tel.set_debuglevel(1) hia_tel.read_until("login:") hia_tel.write('maint'+"\r") hia_tel.read_until("Password:") hia_tel.write("maint"+"\r") hia_tel.read_until("maint at atcaHLRds0 /public/users/maint>") while 1: try: command = cmd_q.get() hia_tel.write(command+"\r") data = hia_tel.read_until("maint at atcaHLRds0 /public/users/maint>") out_q.put(data) except Exception,error: error_email_mis(message) logs('error',str(error),'null') end_less() time.sleep(10) except Exception,error: error_email_mis(message) logs('error',str(error),'null') -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of Rayon Sent: 19 November 2011 08:41 To: 'James Chapman'; tutor at python.org Subject: Re: [Tutor] python telnet Thanks but still not working, I am wondering if I need to give the script some kind of special permission to execute on windows 7. -----Original Message----- From: tutor-bounces+evosweet=hotmail.com at python.org [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of James Chapman Sent: 19 November 2011 08:23 To: tutor at python.org Subject: Re: [Tutor] python telnet traceback has: child = winspawn('telnet 192.168.0.55:210') When using telnet from CLI (on windows), you would type: telnet 192.168.0.55 210 Note the space between the IP and port number and not a :colon. Not sure this is your problem but probably worth mentioning. -- James At Saturday, 19/11/2011 on 11:44 Rayon wrote: > I used the turn on turn off feature, and I can start a telnet session > from the command line. > > -----Original Message----- > From: tutor-bounces+evosweet=hotmail.com at python.org > [mailto:tutor-bounces+evosweet=hotmail.com at python.org] On Behalf Of > Steven D'Aprano > Sent: 19 November 2011 07:04 > To: tutor at python.org > Subject: Re: [Tutor] python telnet > > Rayon wrote: > > I installed the telnet client but still the same error. > > How did you install it? Windows includes a telnet application, but it > has to be enabled first: > > http://windows.microsoft.com/en-AU/windows-vista/Telnet-frequently-ask > ed-que > stions > > If you run "telnet" from the Windows shell (cmd.exe), what happens? > > Until you can successfully run telnet from Windows, there isn't any > point trying to run it from Python. > > > -- > Steven > > _______________________________________________ > 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 _______________________________________________ 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 rhettnaxel at gmail.com Sun Nov 20 04:32:24 2011 From: rhettnaxel at gmail.com (Alexander) Date: Sat, 19 Nov 2011 22:32:24 -0500 Subject: [Tutor] Usenet comp.lang.python In-Reply-To: References: Message-ID: On Sat, Nov 19, 2011 at 6:47 PM, Alan Gauld wrote: > On 19/11/11 19:48, Alexander wrote: > >> Hi. Does anybody know about using the comp.lang.python usenet news >> feed(?) ? >> I'd like help configuring it. I can't seem to find documentation helping >> me. >> Thanks for reading, >> > > The easiest way is probably to set up your newsreader to point at the > gmane server. On Thunderbird I have the following server settings: > > Server name: news.gmane.org > Port 119 > > The rest are defaults. > > Having set up the server the rest depends on your reader, but basically > you subscribe to the news groups you are interested in. For > comp.lang.python its called: gmane.comp.python.general > > > -- > Alan G > 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 > thanks Alan. -- Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Sun Nov 20 12:45:54 2011 From: o0MB0o at hotmail.se (Mic) Date: Sun, 20 Nov 2011 12:45:54 +0100 Subject: [Tutor] Tutor Digest, Vol 93, Issue 117 In-Reply-To: References: Message-ID: Message: 4 Date: Sat, 19 Nov 2011 23:18:01 +0000 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] Can I shorten this code? Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed Most peoples code could be shortened. And most of it would be the worse for it. There are a few occasions when shortening makes sense, especially if its all repeated lines or just plain superflous code. But, in general, aim to write readable code, not just short code. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ************************************** Thanks for your detailed answer, it is really appreciated :) I understand now that it is really useful to have describing names for a function so others can read/understand the code. I have done my best to make the code more readable now. Here is the result. from tkinter import* button1_color="green" button1_value=False button2_color="green" button2_value=False class Window(Frame): def __init__(self,master): super (Window,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): #Creates hello button1 self.hello_bttn1=Button(self,bg=button1_color, text="Hi_1", command=self.button1_clicked) self.hello_bttn1.grid() #Creates hello button2 self.hello_bttn2=Button(self,bg=button2_color, text="Hi_1", command=self.button2_clicked) self.hello_bttn2.grid() def button1_clicked(self): """ This method runs if button one is clicked""" def change_button1_value(): global button1_value button1_value=not button1_value change_button1_value() if button1_value: self.hello_bttn1.configure(bg="red", text="Hi_2") def change_button1_color_red(): global button1_color button1_color=("red") change_button1_color_red() else: self.hello_bttn1.configure(bg="green", text="Hi_1") def change_button1_color_green(): global button1_color button1_color=("green") change_button1_color_green() #------------------------------------------------- def button2_clicked(self): """This method runs if button two is clicked""" def change_button2_value(): global button2_value button2_value=not button2_value change_button2_value() if button2_value: self.hello_bttn2.configure(bg="red", text="Hi_2") def change_button2_color_red(): global button2_color button2_color=("red") change_button2_color_red() else: self.hello_bttn2.configure(text="Hi_1", bg="green") def change_button2_color_green(): global button2_color button2_color=("green") change_button2_color_green() root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() However, I did not understand this part of your suggestions: def change_global2_1(): > global value1 > value1=("green") And this is completely redundant since it does exactly the same as the other function, all you need is a parameter when you call it, like so: def setValue1(val): global value1 value1 = val > change_global2_1() And this becomes setValue1("green") But ultimately you could just have set it directly in your outer function, it's hardly worth the cost of defining a function, unless you intend to add more to it later. > def change_value_hellobttn2(self): All of the above comments apply here too. Generally you build a data table with all the config parameters that will varty then you build a loop to read the values from the data table. Store the created buttons in a list or dictionary. I must admit that I have never heard of a "data table" before. Is this easy to do, for a beginner like me? Thanks for your answers! From chloebeck at hotmail.com Sun Nov 20 12:58:25 2011 From: chloebeck at hotmail.com (Chloe Beck) Date: Sun, 20 Nov 2011 11:58:25 +0000 Subject: [Tutor] Help with error in ski game Message-ID: Hi, I've just begun trying to teach myself how to program with Python. I'm currently working through the book 'Hello World, Computer programming for kids and other beginners' and am stuck on one of the exercises. The exercise is a take on the SkiFree game. The error message I get is as follows and occurs in game play when my skier goes to the far left of the screen: Traceback (most recent call last): File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 99, in skier.move(speed) File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 28, in move if self.rect.centerx < 20: self.rect.centrex = 20 AttributeError: 'pygame.Rect' object has no attribute 'centrex' I can't for the life of me figure out what i've done wrong but as i said i am very new to this all. Enjoying it so far though :) I'm using Python 2.5 on a Mac Below is the code. Any help is greatly appreciated as is any advice on new things to try when attempting to learn Python Regards Chloe import pygame, sys, random skier_images = ["skier_down.png", "skier_right1.png", "skier_right2.png", "skier_left2.png", "skier_left1.png"] class SkierClass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("skier_down.png") self.rect = self.image.get_rect() self.rect.center = [320,100] self.angle = 0 def turn(self, direction): self.angle = self.angle + direction if self.angle < -2: self.angle = -2 if self.angle > 2: self.angle = 2 center = self.rect.center self.image = pygame.image.load(skier_images[self.angle]) self.rect = self.image.get_rect() self.rect.center = center speed = [self.angle, 6 - abs(self.angle) * 2] return speed def move(self, speed): self.rect.centerx = self.rect.centerx + speed[0] if self.rect.centerx < 20: self.rect.centrex = 20 if self.rect.centerx > 620: self.rect.centerx = 620 class ObstacleClass (pygame.sprite.Sprite): def __init__(self, image_file, location, type): pygame.sprite.Sprite.__init__(self) self.image_file = image_file self.image = pygame.image.load(image_file) self.location = location self.rect = self.image.get_rect() self.rect.center = location self.type = type self.passed = False def scroll(self, t_ptr): self.rect.centery = self.location[1] - t_ptr def create_map(start, end): obstacles = pygame.sprite.Group() gates = pygame.sprite.Group() locations = [] for i in range(10): row = random.randint(start, end) col = random.randint (0, 9) location = [col * 64 + 20, row * 64 + 20] if not (location in locations): locations.append(location) type = random.choice(["tree", "flag"]) if type == "tree" : img = "skier_tree.png" elif type =="flag": img = "skier_flag.png" obstacle = ObstacleClass(img, location, type) obstacles.add(obstacle) return obstacles def animate() : screen.fill([255, 255, 255]) pygame.display.update(obstacles.draw(screen)) screen.blit(skier.image, skier.rect) screen.blit(score_text, [10, 10]) pygame.display.flip() def updateObstacleGroup(map0, map1): obstacles = pygame.sprite.Group() for ob in map0: obstacles.add(ob) for ob in map1: obstacles.add(ob) return obstacles pygame.init() screen = pygame.display.set_mode([640,640]) clock = pygame.time.Clock() skier = SkierClass() speed = [0, 6] map_position = 0 points = 0 map0 = create_map(20, 29) map1 = create_map(10, 19) activeMap = 0 obstacles = updateObstacleGroup(map0, map1) font = pygame.font.Font(None,50) while True: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: speed = skier.turn(-1) elif event.key == pygame.K_RIGHT: speed = skier.turn(1) skier.move(speed) map_position += speed[1] if map_position >=640 and activeMap ==0: activeMap = 1 map0 = create_map(20, 29) obstacles = updateObstacleGroup(map0, map1) if map_position >=1280 and activeMap == 1: activeMap = 0 for ob in map0: ob.location[1] = ob.location[1] - 1280 map_position = map_position - 1280 map1 = create_map(10, 19) obstacles = updateObstacleGroup(map0,map1) for obstacle in obstacles: obstacle.scroll(map_position) hit = pygame.sprite.spritecollide(skier, obstacles, False) if hit: if hit [0]. type == "tree" and not hit[0].passed: points = points - 100 skier.image = pygame.image.load("skier_crash.png") animate() pygame.time.delay(1000) skier.image = pygame.image.load("skier_down.png") skier.angle = 0 speed = [0,6] hit[0].passed = True elif hit [0].type == "flag" and not hit [0].passed: points += 10 obstacles.remove(hit[0]) score_text = font.render("Score: " +str(points), 1, (0, 0, 0)) animate() -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Sun Nov 20 13:15:03 2011 From: bodsda at googlemail.com (Bod Soutar) Date: Sun, 20 Nov 2011 12:15:03 +0000 Subject: [Tutor] Beginner Programming Challenges Message-ID: FOA: Any aspiring new programmers looking for some inspiration or projects. There is a series of programming challenges being run on the ubuntu forums The challenges are aimed at beginners, and although they assume you are running linux, this is not always a requirement. The latest challenge can be found here: http://ubuntuforums.org/showthread.php?t=1883907 An index of all the challenges is here: http://ubuntuforums.org/showthread.php?t=1714324 Happy coding, Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Sun Nov 20 13:22:20 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Sun, 20 Nov 2011 12:22:20 +0000 Subject: [Tutor] Help with error in ski game In-Reply-To: References: Message-ID: <1528564713-1321791740-cardhu_decombobulator_blackberry.rim.net-1666360606-@b4.c12.bise7.blackberry> Just a guess but take a look at the spelling. centerx Or centrex Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Chloe Beck Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Sun, 20 Nov 2011 11:58:25 To: Subject: [Tutor] Help with error in ski game _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From Nikunj.Badjatya at emc.com Sun Nov 20 14:00:43 2011 From: Nikunj.Badjatya at emc.com (Nikunj.Badjatya at emc.com) Date: Sun, 20 Nov 2011 08:00:43 -0500 Subject: [Tutor] ProgressBar - Python and Powershell In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D187@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D187@MX34A.corp.emc.com> Message-ID: <599CEBACD49B4144A61212D837EE3C0F144604D351@MX34A.corp.emc.com> Can anyone throw some light on this please. ! ? From: tutor-bounces+nikunj.badjatya=emc.com at python.org [mailto:tutor-bounces+nikunj.badjatya=emc.com at python.org] On Behalf Of Nikunj.Badjatya at emc.com Sent: Thursday, November 17, 2011 4:21 PM To: tutor at python.org Subject: [Tutor] ProgressBar - Python and Powershell Hi All, I am using Python 2.7, windows Env. I have an Installer written in Python(45%) and Powershell(55%) which is used to install Virtual Machines at specific locations. It is single threaded. I am trying to implement a ProgressBar for this installer. So that the user will come to know the progress of the installation. I am using pypi progressbar module. The top script is in python which inturns calls powershell scripts using subprocess.call() and proceeds with the installation. I am taking a shared file between python and powershell, so that diff functions can update their %age completion level in to the file. Ex. Func1() updates it to 5%, func2() will add its own 5% to it.. and so on. At the start of the (main.py) script I am creating a thread whose sole purpose would be to keep "READ" a temp file for a new entry in it. Based on this entry I can have my thread update the progressbar on the console. My questions are: 1. Can I have a better shared mechanism between python and powershell.? As I am using a file here. Reading + writing in python and writing only in powershell. ! 2. Does this thread mechanism work.? I am yet to implement and test it.! :P What can be the possible shortfalls.? Thanks Nikunj Bangalore - India -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Sun Nov 20 14:36:41 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Sun, 20 Nov 2011 13:36:41 +0000 Subject: [Tutor] ProgressBar - Python and Powershell In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D351@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D187@MX34A.corp.emc.com> <599CEBACD49B4144A61212D837EE3C0F144604D351@MX34A.corp.emc.com> Message-ID: <1927838950-1321796200-cardhu_decombobulator_blackberry.rim.net-1822378638-@b4.c12.bise7.blackberry> This is just my opinion but I would have several (say 10) powershell scripts individually called by python, python will sit still until the powershell exits, then update the progress bar by 10% before calling the next script etc etc. Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Sun, 20 Nov 2011 08:00:43 To: ; Subject: Re: [Tutor] ProgressBar - Python and Powershell _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Nov 20 16:15:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Nov 2011 02:15:48 +1100 Subject: [Tutor] ProgressBar - Python and Powershell In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D351@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D187@MX34A.corp.emc.com> <599CEBACD49B4144A61212D837EE3C0F144604D351@MX34A.corp.emc.com> Message-ID: <4EC919A4.5050001@pearwood.info> Nikunj.Badjatya at emc.com wrote: > Can anyone throw some light on this please. ! ? This is a list for beginners learning Python. Your question is quite advanced for this list, as it involves both threads and subprocesses. It also uses a third-party module, progressbar, and a Windows-only application Powershell. You might get lucky and find somebody here that knows all of these technologies, but I think you're asking in the wrong place. Perhaps you should try in the main Python mailing list, python-list at python.org, also available on Usenet as comp.lang.python. By the way, you say that your application is single-threaded, but then describe using threads. That means it isn't single-threaded at all. Good luck. -- Steven From steve at pearwood.info Sun Nov 20 16:22:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Nov 2011 02:22:34 +1100 Subject: [Tutor] Help with error in ski game In-Reply-To: References: Message-ID: <4EC91B3A.7030201@pearwood.info> Chloe Beck wrote: > Traceback (most recent call last): > File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 99, in > skier.move(speed) > File "/Users/Chloe/Documents/SKI SKI/ski ski ski", line 28, in move > if self.rect.centerx < 20: self.rect.centrex = 20 > AttributeError: 'pygame.Rect' object has no attribute 'centrex' I'm not familiar with pygame, but my guesses are: * you have used British spelling centre instead of American spelling center; try using centerx instead of centrex; * if that fails, perhaps it should be spelled center.x * if that fails, please open a Python interactive interpreter, and at the prompt enter: import pygame dir(pygame.Rect) and show us the output. -- Steven From mylesbroomes at hotmail.co.uk Sun Nov 20 16:29:03 2011 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sun, 20 Nov 2011 15:29:03 +0000 Subject: [Tutor] Guess my number game Message-ID: I asked for advice yesterday with some pseudocode for a 'guess my number' game I wrote up, and I was told to have a go at writing up the actual code. I've had a go but im struggling... #guess my number games #the user thinks of a number between 1 and 100, #the computer then has to try and guess that number #welcome the player to the game and explain the rules print("\t\t\t Guess My Number") input("Welcome player to the 'Guess My Number' game. Think of a number between 1 and 100 and I will try to guess it. Press enter when you have thought of your number and are ready to begin.") #import the random module import random #set initial values tries = 1 attempt = random.randint(1,100) guess = input("Is your number",attempt,"? (Enter 'yes' or 'no'.)") #guessing loop while guess == 'no': tries += 1 incorrect = input("Was my guess too high or too low? (Type 'high' or 'low'.) ") if incorrect == 'high': * if incorrect == 'low': * #tell the player how many tries it took and end the game print("Aha! I guessed it! And it only took",tries,"tries!") input("Press enter to exit.") Im having trouble trying to figure out a way to make the program guess 'higher' and 'lower' (Where the two asterisks are). Any help would be much appreciated! Oh and heres my pseudocode: Welcome the user to the game Explain the rules of the game Wait for the user to think of a number Once the user has thought of their number, take a guess While the number has not been guessed correctly Increase the number of 'tries' by 1 Ask the user if the guess was too high or too low If the guess was too high guess lower If the guess was too low guess higher Once the number has been guessed correctly, tell the user the number of tries it took Exit the game Thanks again! From alan.gauld at btinternet.com Sun Nov 20 16:45:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Nov 2011 15:45:28 +0000 Subject: [Tutor] Shortening code [was Re: Tutor Digest, Vol 93, Issue 117] In-Reply-To: References: Message-ID: Please change to a sensible subject when replying to digest messages. On 20/11/11 11:45, Mic wrote: > I have done my best to make the code more readable now. > Here is the result. ############################ from tkinter import* button1_color="green" button1_value=False button2_color="green" button2_value=False ############################ buttonX_value still doesn't say much about *why* the variable is there. What are you storing in it. What does the value represent? Also, do you really need the colors, you don't actually use them for anything below except the initial color, but you might as well just hard code it to "green", it would be shorter and more explicit... ################################## class Window(Frame): def __init__(self,master):... def create_widgets(self): #Creates hello button1 self.hello_bttn1=Button(self,bg=button1_color, text="Hi_1", command=self.button1_clicked) self.hello_bttn1.grid() #Creates hello button2 self.hello_bttn2=Button(self,bg=button2_color, text="Hi_1", command=self.button2_clicked) self.hello_bttn2.grid() def button1_clicked(self): """ This method runs if button one is clicked""" def change_button1_value(): global button1_value button1_value=not button1_value change_button1_value() ############################ > if button1_value: > self.hello_bttn1.configure(bg="red", text="Hi_2") Note that this is the line that really changes the button's color. And it does not use the variable... > def change_button1_color_red(): > global button1_color > button1_color=("red") > change_button1_color_red() Whereas this function and its call do nothing but change the value of a variable that is never used after the initial creation. If you took this out the code would run with exactly the same effect. > else: > self.hello_bttn1.configure(bg="green", text="Hi_1") Same, here. You set the color explicitly, then create a function and call it just to update a variable you don't use. > def change_button1_color_green(): > global button1_color > button1_color=("green") > change_button1_color_green() ############################### def button2_clicked(self): """This method runs if button two is clicked""" def change_button2_value(): global button2_value button2_value=not button2_value change_button2_value() if button2_value: self.hello_bttn2.configure(bg="red", text="Hi_2") def change_button2_color_red(): global button2_color button2_color=("red") change_button2_color_red() else: self.hello_bttn2.configure(text="Hi_1", bg="green") def change_button2_color_green(): global button2_color button2_color=("green") change_button2_color_green() ############################################ Notice that both button handlers are identical except they work on different buttons and test values. What we'd like is a single function that gets passed the widget and test as parameters. It would look like this: def button_clicked(self, widget, test): if test: widget.configure(bg="red", text="Hi_2") else: widget.configure(text="Hi_1", bg="green") and to call it we create two short event handlers: def button1_clicked(self): self.button1_value = not self.button1_value self.button_clicked(button1,self.button1_value) def button2_clicked(self): self.button2_value = not self.button2_value self.button_clicked(button2,self.button2_value) Notice I've moved the test values to instance variables rather than globals, but thats just a style thing you could have referenced the globals within the handlers instead. I also removed those spurious functions from the main button_clicked code. > However, I did not understand this part of your suggestions: > > Generally you build a data table with all the config parameters that > > will varty then you build a loop to read the values from the > > data table. > > Store the created buttons in a list or dictionary. > > I must admit that I have never heard of a "data table" before. > Is this easy to do, for a beginner like me? Yes its just a list of tuples/lists. For your two buttons uit would look like: # buttonName text, color, command self.button_params = [ ("b1", "Hi_1", "green", self.button1_clicked), ("b2", "Hi_2", "green", self.button2_clicked) ] Now your create_widgets looks like: def create_widgets(self): self.Buttons = {} for params in self.button_params: b = Button(self, bg=params[1], text=params[2], command=params[3]) self.Buttons[params[0]] = b And now you can access your buttons at any time using self.Buttons["b1"] etc We could use a dictionary for params to make it more readable at the expense of more typing: # buttonName text, color, command self.button_params = [ { "name": "b1", "text":"Hi_1", "color":"green", "Command":self.button1_clicked }, { "name": "b1", "text":"Hi_1", "color":"green", "Command":self.button1_clicked } ] You could then put that in a separate file which you import into you GUI creation file. You could have a similar list for each type of widget you want to create. However you still need to know how to place them within the GUI, so either you create a very complex parameters structure or you just keep the complexity in the creation method. But tis technique is worth while where you are creating a list of near identical widgets - like the buttons in a calculator keybad say... To process the dictionary the creation loop changes to: for params in self.button_params: b = Button(self, bg=params["color"], text=params["text"], command=params["command"]) self.Buttons[params["name"]] = b Hopefully that makes it clear. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Nov 20 17:00:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 20 Nov 2011 16:00:00 +0000 Subject: [Tutor] Guess my number game In-Reply-To: References: Message-ID: On 20/11/11 15:29, myles broomes wrote: > ...I was told to have a go at writing up the actual code. Well done, thats a good start. > #guess my number games > #the user thinks of a number between 1 and 100, > #the computer then has to try and guess that number > > #welcome the player to the game and explain the rules > print("\t\t\t Guess My Number") > input("Welcome player to the 'Guess My Number' game. Think of a number between 1 and 100 and I will try to guess it. Press enter when you have thought of your number and are ready to begin.") First thing is that you need to store the number that the user typed. So you need a variable - lets call it userNumber - and an assignment. While we are at it lets convert the string version the user gave us to a number: userNumber = int( input(....) ) > #import the random module > import random The comment is redundant since the code is obvious. Use comments to tell us *why* you are doing things not to tell us what you are doing - we can all read the code... Its also conventional practice to put all imports at the top of the program. Its not necessary, but it saves people hunting for the imports if they are all together at the top. > #set initial values > tries = 1 > attempt = random.randint(1,100) > guess = input("Is your number",attempt,"? (Enter 'yes' or 'no'.)") The name guess is a bit misleading since its really the users response, The Guess is actually what you have already named attempt. Good naming makes a big difference to the readability of your code so it's worth really thinking about what the variables are doing and choosing descriptive names. Also the names should follow the function of the variables, not their type. > #guessing loop > while guess == 'no': > tries += 1 > incorrect = input("Was my guess too high or too low? (Type 'high' or 'low'.) ") > if incorrect == 'high': > * Here you want to generate a new value for attempt but insterad of using 1-100 you want it between 1-(attempt-1) > if incorrect == 'low': Here you want to generate a new value for attempt but instead of using 1-100 you want it between (attempt+1) - 100 And you already know how to set attempt to a number between two values... Then before you go back to the top of the loop you need to ask the user if the new attempt is ok and store that in guess. Have a go at writing that... > #tell the player how many tries it took and end the game > print("Aha! I guessed it! And it only took",tries,"tries!") > input("Press enter to exit.") And that bit is fine. :-) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Nikunj.Badjatya at emc.com Sun Nov 20 18:56:08 2011 From: Nikunj.Badjatya at emc.com (Nikunj.Badjatya at emc.com) Date: Sun, 20 Nov 2011 12:56:08 -0500 Subject: [Tutor] ProgressBar - Python and Powershell In-Reply-To: <4EC919A4.5050001@pearwood.info> References: <599CEBACD49B4144A61212D837EE3C0F144604D187@MX34A.corp.emc.com> <599CEBACD49B4144A61212D837EE3C0F144604D351@MX34A.corp.emc.com> <4EC919A4.5050001@pearwood.info> Message-ID: <599CEBACD49B4144A61212D837EE3C0F144604D357@MX34A.corp.emc.com> Thanks for the reply Steve. I mean, the installer as a sole is single threaded. They way to implement progressbar may turn it to multithreaded. Anyways, I have posted the problem in pyhton-list ml. Thanks Nikunj -----Original Message----- From: tutor-bounces+nikunj.badjatya=emc.com at python.org [mailto:tutor-bounces+nikunj.badjatya=emc.com at python.org] On Behalf Of Steven D'Aprano Sent: Sunday, November 20, 2011 8:46 PM To: tutor at python.org Subject: Re: [Tutor] ProgressBar - Python and Powershell Nikunj.Badjatya at emc.com wrote: > Can anyone throw some light on this please. ! ? This is a list for beginners learning Python. Your question is quite advanced for this list, as it involves both threads and subprocesses. It also uses a third-party module, progressbar, and a Windows-only application Powershell. You might get lucky and find somebody here that knows all of these technologies, but I think you're asking in the wrong place. Perhaps you should try in the main Python mailing list, python-list at python.org, also available on Usenet as comp.lang.python. By the way, you say that your application is single-threaded, but then describe using threads. That means it isn't single-threaded at all. Good luck. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From dave6502 at gmail.com Sun Nov 20 19:28:09 2011 From: dave6502 at gmail.com (dave selby) Date: Sun, 20 Nov 2011 18:28:09 +0000 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? Message-ID: Hi All, I have a long string which is an HTML file, I strip the HTML tags away and make a list with text = re.split('<.*?>', HTML) I then tried to search for a string with text.index(...) but it was not found, printing HTML to a terminal I get what I expect, a block of tags and text, I split the HTML and print text and I get loads of \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character. Any idea what is happening and how to get back to a list of ascii strings ? Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From steve at alchemy.com Sun Nov 20 20:15:34 2011 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 20 Nov 2011 11:15:34 -0800 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? In-Reply-To: References: Message-ID: <264A7E67-24E8-4E40-BBC9-A95461B62454@alchemy.com> Where did the string come from? It looks at first glance like you have two bytes for each character instead of the one you expect. Is this perhaps a Unicode string instead of ASCII? Sent from my iPad On 2011/11/20, at 10:28, dave selby wrote: > Hi All, > > I have a long string which is an HTML file, I strip the HTML tags away > and make a list with > > text = re.split('<.*?>', HTML) > > I then tried to search for a string with text.index(...) but it was > not found, printing HTML to a terminal I get what I expect, a block of > tags and text, I split the HTML and print text and I get loads of > > \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character. > > Any idea what is happening and how to get back to a list of ascii strings ? > > Cheers > > Dave > > -- > > Please avoid sending me Word or PowerPoint attachments. > See http://www.gnu.org/philosophy/no-word-attachments.html > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From tvssarma.omega9 at gmail.com Sun Nov 20 21:04:30 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Mon, 21 Nov 2011 01:34:30 +0530 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? In-Reply-To: References: Message-ID: Would the html parser library in python be a better idea as opposed to using split? That way you have greater control over what is in the html. On 20 Nov 2011 23:58, "dave selby" wrote: > Hi All, > > I have a long string which is an HTML file, I strip the HTML tags away > and make a list with > > text = re.split('<.*?>', HTML) > > I then tried to search for a string with text.index(...) but it was > not found, printing HTML to a terminal I get what I expect, a block of > tags and text, I split the HTML and print text and I get loads of > > \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character. > > Any idea what is happening and how to get back to a list of ascii strings ? > > Cheers > > Dave > > -- > > Please avoid sending me Word or PowerPoint attachments. > See http://www.gnu.org/philosophy/no-word-attachments.html > _______________________________________________ > 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 alchemy.com Sun Nov 20 21:26:30 2011 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 20 Nov 2011 12:26:30 -0800 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? In-Reply-To: References: Message-ID: <4EC96276.3010303@alchemy.com> On 20-Nov-11 12:04, Sarma Tangirala wrote: > Would the html parser library in python be a better idea as opposed to > using split? That way you have greater control over what is in the html. Absolutely. And it would handle improper HTML (like unmatched brackets) gracefully where the split will just do the wrong thing. > > On 20 Nov 2011 23:58, "dave selby" > wrote: > > Hi All, > > I have a long string which is an HTML file, I strip the HTML tags away > and make a list with > > text = re.split('<.*?>', HTML) > > I then tried to search for a string with text.index(...) but it was > not found, printing HTML to a terminal I get what I expect, a block of > tags and text, I split the HTML and print text and I get loads of > > \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character. > > Any idea what is happening and how to get back to a list of ascii > strings ? > > Cheers > > Dave > > -- > > Please avoid sending me Word or PowerPoint attachments. > See http://www.gnu.org/philosophy/no-word-attachments.html > _______________________________________________ > 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 -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From steve at alchemy.com Sun Nov 20 21:30:16 2011 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 20 Nov 2011 12:30:16 -0800 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? In-Reply-To: References: <264A7E67-24E8-4E40-BBC9-A95461B62454@alchemy.com> Message-ID: <4EC96358.9070104@alchemy.com> It's customary to copy the list with answers, so everyone can benefit who may run into the same issue, too. On 20-Nov-11 11:38, dave selby wrote: > It came from some automated HTML generation app ... I just had the > idea of looking at in with ghex .... every other character is \00 > !!!!, thats mad. OK will try ans replace('\00', '') in the string > before splitting Those bytes are there for a reason, it's not mad. It's using wide characters, possibly due to Unicode encoding. If there are special characters involved (multinational applications or whatever), you'll destroy them by killing the null bytes and won't handle the case of that high-order byte being something other than zero. Check out Python's Unicode handling, and character set encode/decode features for a robust way to translate the output you're getting. > > Cheers > > Dave > > On 20 November 2011 19:15, Steve Willoughby wrote: >> Where did the string come from? It looks at first glance like you have two bytes for each character instead of the one you expect. Is this perhaps a Unicode string instead of ASCII? >> >> Sent from my iPad >> >> On 2011/11/20, at 10:28, dave selby wrote: >> >>> Hi All, >>> >>> I have a long string which is an HTML file, I strip the HTML tags away >>> and make a list with >>> >>> text = re.split('<.*?>', HTML) >>> >>> I then tried to search for a string with text.index(...) but it was >>> not found, printing HTML to a terminal I get what I expect, a block of >>> tags and text, I split the HTML and print text and I get loads of >>> >>> \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character. >>> >>> Any idea what is happening and how to get back to a list of ascii strings ? >>> >>> Cheers >>> >>> Dave >>> >>> -- >>> >>> Please avoid sending me Word or PowerPoint attachments. >>> See http://www.gnu.org/philosophy/no-word-attachments.html >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> > > > -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From steve at pearwood.info Sun Nov 20 22:45:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Nov 2011 08:45:42 +1100 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? In-Reply-To: References: Message-ID: <4EC97506.1080800@pearwood.info> dave selby wrote: > I split the HTML and print text and I get loads of > > \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character. > > Any idea what is happening and how to get back to a list of ascii strings ? How did you generate the HTML file? What other applications have you used to save the document? Something in the tool chain before it reached Python has saved it using a wide (four byte) encoding, most likely UTF-16 as that is widely used by Windows and Java. With the right settings, it could take as little as opening the file in Notepad, then clicking Save. If this isn't making sense to you, you should read this: http://www.joelonsoftware.com/articles/Unicode.html If my guess is right that the file is UTF-16, then you can "fix" it by doing this: # Untested. f = open("my_html_file.html", "r") text = f.read().decode("utf-16") # convert bytes to text f.close() bytes = text.encode("ascii") # If this fails, try "latin-1" instead f = open("my_html_file2.html", "w") # write bytes back to disk f.write(bytes) f.close() Once you've inspected the re-written file my_html_file2.html and it is okay to your satisfaction, you can delete the original one. -- Steven From d at davea.name Sun Nov 20 23:01:51 2011 From: d at davea.name (Dave Angel) Date: Sun, 20 Nov 2011 17:01:51 -0500 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? In-Reply-To: <4EC97506.1080800@pearwood.info> References: <4EC97506.1080800@pearwood.info> Message-ID: <4EC978CF.9010301@davea.name> On 11/20/2011 04:45 PM, Steven D'Aprano wrote: > > > Something in the tool chain before it reached Python has saved it > using a wide (four byte) encoding, most likely UTF-16 as that is > widely used by Windows and Java. With the right settings, it could > take as little as opening the file in Notepad, then clicking Save. > UTF-16 is a two byte format. That's typically what Windows uses for Unicode. It's Unices that are more likely to use a four-byte format. -- DaveA From mlybrand at gmail.com Mon Nov 21 03:21:54 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Sun, 20 Nov 2011 18:21:54 -0800 Subject: [Tutor] Is there a way to add paths in Eric? Message-ID: I am using Windows Vista. I have some python scripts I have been developing in my learning folder. Can I add the path to the folder in eric to call them interactively, or will I need to move them? -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlybrand at gmail.com Mon Nov 21 05:26:11 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Sun, 20 Nov 2011 20:26:11 -0800 Subject: [Tutor] Is there a way to add paths in Eric? In-Reply-To: References: Message-ID: Okay, I have answered my own question.... import sys sys.append() Sorry for bothering. Mark On Sun, Nov 20, 2011 at 6:21 PM, Mark Lybrand wrote: > I am using Windows Vista. I have some python scripts I have been > developing in my learning folder. Can I add the path to the folder in eric > to call them interactively, or will I need to move them? > > > > -- > Mark :) > -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikunj.Badjatya at emc.com Mon Nov 21 06:54:02 2011 From: Nikunj.Badjatya at emc.com (Nikunj.Badjatya at emc.com) Date: Mon, 21 Nov 2011 00:54:02 -0500 Subject: [Tutor] How to get module name from ImportError Message-ID: <599CEBACD49B4144A61212D837EE3C0F144604D396@MX34A.corp.emc.com> Hi All, Please look at the following snippet. {{{ # User defined modules try: from scripts import precheck from scripts import validate from scripts import constants except ImportError: print("ERROR: One of the modules (..scripts/precheck.py, validate.py, constants) is not present.") print("INFO : Please verify the above modules, and restart the installation") sys.exit(1) }}} See the red line. I want to get the name of the particular module which is not available and hence causing ImportError. One of the ways can be to get the STDERR and process it using re. !? Is there a better alternate available .? Thanks Nikunj -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Mon Nov 21 07:06:24 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 21 Nov 2011 08:06:24 +0200 Subject: [Tutor] How to get module name from ImportError In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D396@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D396@MX34A.corp.emc.com> Message-ID: <4EC9EA60.5030603@compuscan.co.za> On 2011/11/21 07:54 AM, Nikunj.Badjatya at emc.com wrote: > > Hi All, > > Please look at the following snippet. > > {{{ > > # User defined modules > > try: > > from scripts import precheck > > from scripts import validate > > from scripts import constants > > except ImportError: > > print("ERROR: One of the modules (..scripts/precheck.py, > validate.py, constants) is not present.") > > print("INFO : Please verify the above modules, and restart the > installation") > > sys.exit(1) > > }}} > > See the red line. > I want to get the name of the particular module which is not available > and hence causing ImportError. > > One of the ways can be to get the STDERR and process it using re. !? > > Is there a better alternate available .? > > Thanks > > Nikunj > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor >>> try: ... import nothing ... except ImportError, err_msg: ... print err_msg ... No module named nothing Hope that helps. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From Nikunj.Badjatya at emc.com Mon Nov 21 07:23:21 2011 From: Nikunj.Badjatya at emc.com (Nikunj.Badjatya at emc.com) Date: Mon, 21 Nov 2011 01:23:21 -0500 Subject: [Tutor] How to get module name from ImportError In-Reply-To: <4EC9EA60.5030603@compuscan.co.za> References: <599CEBACD49B4144A61212D837EE3C0F144604D396@MX34A.corp.emc.com> <4EC9EA60.5030603@compuscan.co.za> Message-ID: <599CEBACD49B4144A61212D837EE3C0F144604D39B@MX34A.corp.emc.com> Exactly ! Thanks a lot. From: Christian Witts [mailto:cwitts at compuscan.co.za] Sent: Monday, November 21, 2011 11:36 AM To: Badjatya, Nikunj Cc: tutor at python.org Subject: Re: [Tutor] How to get module name from ImportError On 2011/11/21 07:54 AM, Nikunj.Badjatya at emc.com wrote: Hi All, Please look at the following snippet. {{{ # User defined modules try: from scripts import precheck from scripts import validate from scripts import constants except ImportError: print("ERROR: One of the modules (..scripts/precheck.py, validate.py, constants) is not present.") print("INFO : Please verify the above modules, and restart the installation") sys.exit(1) }}} See the red line. I want to get the name of the particular module which is not available and hence causing ImportError. One of the ways can be to get the STDERR and process it using re. !? Is there a better alternate available .? Thanks Nikunj _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor >>> try: ... import nothing ... except ImportError, err_msg: ... print err_msg ... No module named nothing Hope that helps. -- Christian Witts Python Developer -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Nov 21 08:11:12 2011 From: d at davea.name (Dave Angel) Date: Mon, 21 Nov 2011 02:11:12 -0500 Subject: [Tutor] How to get module name from ImportError In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D39B@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D396@MX34A.corp.emc.com> <4EC9EA60.5030603@compuscan.co.za> <599CEBACD49B4144A61212D837EE3C0F144604D39B@MX34A.corp.emc.com> Message-ID: <4EC9F990.7040309@davea.name> On 11/21/2011 01:23 AM, Nikunj.Badjatya at emc.com wrote: > Exactly ! > Thanks a lot. > 1) You really shouldn't top-post. Nor should you try to indicate something with color, since this is a text-based forum. I would suggest that you do not try to parse error messages. (If you're going to just print the message and exit, then there's no advantage in catching it.) Instead, arrange the answer to be given to you directly. Two ways come to mind: 1) use separate try/catch blocks 2) use variables to indicate how far you got before the exception happened. I think I would just start with precheck = validate= constants = None then after the exception is reported, you can check each of these with something like: if constants: One more thing. You appear to be using Python 3. So the correct syntax for the except is: except ImportError as error_obj: Note that the value is *not* a string, but is an object of some subclass of ImportError. > From: Christian Witts [mailto:cwitts at compuscan.co.za] > Sent: Monday, November 21, 2011 11:36 AM > To: Badjatya, Nikunj > Cc: tutor at python.org > Subject: Re: [Tutor] How to get module name from ImportError > > On 2011/11/21 07:54 AM, Nikunj.Badjatya at emc.com wrote: > Hi All, > > Please look at the following snippet. > {{{ > > # User defined modules > try: > from scripts import precheck > from scripts import validate > from scripts import constants > except ImportError: > print("ERROR: One of the modules (..scripts/precheck.py, validate.py, constants) is not present.") > print("INFO : Please verify the above modules, and restart the installation") > sys.exit(1) > > }}} > > See the red line. > I want to get the name of the particular module which is not available and hence causing ImportError. > One of the ways can be to get the STDERR and process it using re. !? > > Is there a better alternate available .? > > Thanks > Nikunj > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor >>>> try: > ... import nothing > ... except ImportError, err_msg: > ... print err_msg > ... > No module named nothing > > Hope that helps. > -- > > Christian Witts > Python Developer > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- DaveA From steve at pearwood.info Mon Nov 21 12:15:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 21 Nov 2011 22:15:49 +1100 Subject: [Tutor] \x00T\x00r\x00i\x00a\x00 ie I get \x00 breaking up every character ? In-Reply-To: <4EC978CF.9010301@davea.name> References: <4EC97506.1080800@pearwood.info> <4EC978CF.9010301@davea.name> Message-ID: <4ECA32E5.60703@pearwood.info> Dave Angel wrote: > On 11/20/2011 04:45 PM, Steven D'Aprano wrote: >> >> >> Something in the tool chain before it reached Python has saved it >> using a wide (four byte) encoding, most likely UTF-16 as that is >> widely used by Windows and Java. With the right settings, it could >> take as little as opening the file in Notepad, then clicking Save. >> > > UTF-16 is a two byte format. That's typically what Windows uses for > Unicode. It's Unices that are more likely to use a four-byte format. Oops, you're right of course, two bytes, not four: py> u'M'.encode('utf-16BE') '\x00M' I was thinking of four hex digits: py> u'M'.encode('utf-16BE').encode('hex') '004d' -- Steven From nidianjs at hotmail.com Tue Nov 22 06:28:56 2011 From: nidianjs at hotmail.com (John) Date: Mon, 21 Nov 2011 17:28:56 -1200 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <4ECB3135.3050702@hotmail.com> References: <4ECB3135.3050702@hotmail.com> Message-ID: Hi all, I have wriiten the following code: [Segment] >>> def survivor(names, step): index = step - 1 next = names while len(next)> 1: next.remove (next[index]) However when ever i run it i get this error message: Traceback (most recent call last): File "", line 1, in survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 4) File "", line 5, in survivor next.remove (next[index]) IndexError: list index out of range Any ideas about whats causing this error? Big thanks, From eire1130 at gmail.com Mon Nov 21 18:43:30 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 21 Nov 2011 12:43:30 -0500 Subject: [Tutor] IndexError: list index out of range In-Reply-To: References: <4ECB3135.3050702@hotmail.com> Message-ID: On Tue, Nov 22, 2011 at 12:28 AM, John wrote: > > Hi all, > > I have wriiten the following code: > [Segment] > > def survivor(names, step): >>>> >>> index = step - 1 > next = names > while len(next)> 1: > next.remove (next[index]) > > > > However when ever i run it i get this error message: > > Traceback (most recent call last): > File "", line 1, in > survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", > "Felicity", "Greg", "Harriet"], 4) > File "", line 5, in survivor > next.remove (next[index]) > IndexError: list index out of range > > Any ideas about whats causing this error? > > Big thanks, > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > I don't really know what it is you are trying to achieve, but I can tell you this, if you add a print statement you can see very clearly why you are getting the error: def survivor(names, step): index = step - 1 next = names while len(next)> 1: print next, index next.remove (next[index]) survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 4) ['Andrew', 'Brenda', 'Craig', 'Deidre', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Felicity', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig'] 3 Traceback (most recent call last): File "C:\Users\user\workspace\pricing\pricing\pricer\tests.py", line 40, in "Felicity", "Greg", "Harriet"], 4) File "C:\Users\user\workspace\pricing\pricing\pricer\tests.py", line 38, in survivor next.remove (next[index]) IndexError: list index out of range As you can see in this line: ['Andrew', 'Brenda', 'Craig'] 3 It looks for index "3" and there isn't one, so it throws an error. The indexes available are 0,1 and 2. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 21 20:00:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 21 Nov 2011 19:00:18 +0000 Subject: [Tutor] IndexError: list index out of range In-Reply-To: References: <4ECB3135.3050702@hotmail.com> Message-ID: On 22/11/11 05:28, John wrote: >>>> def survivor(names, step): > index = step - 1 > next = names > while len(next)> 1: > next.remove (next[index]) > > > > However when ever i run it i get this error message: > next.remove (next[index]) > IndexError: list index out of range > > Any ideas about whats causing this error? You are doing the programming equivalent of sitting on the branch of a tree and cutting 2 feet off the end of the branch. But you never move your position so eventually you cut off the section of branch you are sitting on... You never change index so eventually you remove enough of next that theres no longer any data at index. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Mon Nov 21 20:36:12 2011 From: d at davea.name (Dave Angel) Date: Mon, 21 Nov 2011 14:36:12 -0500 Subject: [Tutor] IndexError: list index out of range In-Reply-To: References: <4ECB3135.3050702@hotmail.com> Message-ID: <4ECAA82C.6020709@davea.name> On 11/22/2011 12:28 AM, John wrote: > > Hi all, > > I have wriiten the following code: I can't provide any more clues about your code than the two excellent replies you've already gotten. But it'd be really good if you could fix your time machine, so you're not posting in the future. Really hard to follow a thread when the responses come before the question. I suspect the date on your machine is set 12 hours or so into the future. -- DaveA From nidianjs at hotmail.com Tue Nov 22 11:50:39 2011 From: nidianjs at hotmail.com (John) Date: Mon, 21 Nov 2011 22:50:39 -1200 Subject: [Tutor] Python code trouble! Message-ID: Hi all, I have attempted to create a programme which removes every Nth person from the list until there is only one name remaining. N is inputted by the user. Here is the code: def survivor(names, step): next = names while len(next) > 1: index = step - 1 next.remove (next[index]) index = index + step - 1 while index > len(next): index = index - len(next) if index == len(next): index = 0 return names[0] To me is appears to be correct, however when i test it i get the following message: >>> survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 4) ['Andrew', 'Brenda', 'Craig', 'Deidre', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Edward', 'Felicity', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Felicity', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Greg', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig', 'Harriet'] 3 ['Andrew', 'Brenda', 'Craig'] 3 Traceback (most recent call last): File "", line 1, in survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 4) File "", line 6, in survivor next.remove (next[index]) IndexError: list index out of range Any ideas? From steve at pearwood.info Tue Nov 22 00:02:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Nov 2011 10:02:01 +1100 Subject: [Tutor] IndexError: list index out of range In-Reply-To: References: <4ECB3135.3050702@hotmail.com> Message-ID: <4ECAD869.1030004@pearwood.info> John wrote: > > Hi all, > > I have wriiten the following code: > [Segment] > >>>> def survivor(names, step): > index = step - 1 > next = names > while len(next)> 1: > next.remove (next[index]) What is the intention of this function? The name given doesn't mean anything to me. The parameters "names" and "step" don't seem meaningful. I can see what the function does: it deletes bits of something, probably a list, in a convoluted way, eventually causing an error. But I can't tell what it is *supposed* to do. Given the example you show later on: survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 4) what should the result be? > However when ever i run it i get this error message: > > Traceback (most recent call last): > File "", line 1, in > survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", > "Felicity", "Greg", "Harriet"], 4) > File "", line 5, in survivor > next.remove (next[index]) > IndexError: list index out of range > > Any ideas about whats causing this error? You attempt to delete an item that doesn't exist. -- Steven From nidianjs at hotmail.com Tue Nov 22 00:34:06 2011 From: nidianjs at hotmail.com (Nidian Job-Smith) Date: Mon, 21 Nov 2011 23:34:06 +0000 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <4ECAD869.1030004@pearwood.info> References: <4ECB3135.3050702@hotmail.com>, , <4ECAD869.1030004@pearwood.info> Message-ID: To answer your questions Steven What is the intention of this function? The name given doesn't mean anything to me. The parameters "names" and "step" don't seem meaningful. I can see what the function does: it deletes bits of something, probably a list, in a convoluted way, eventually causing an error. But I can't tell what it is *supposed* to do. Given the example you show later on: survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 4) what should the result be? To answer your questions Steven What is the intention of this function? The name given doesn't mean anything to me. The parameters "names" and "step" don't seem meaningful. The intention of the programme is to remove every Nth person from a list. N (defined as steps) is inputted by the user. I can see what the function does: it deletes bits of something, probably a list, in a convoluted way, eventually causing an error. But I can't tell what it is *supposed* to do. Given the example you show later on: survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 4) what should the result be? In the example Survivor (["Andrew", "Brenda", "Craig", "Deidre", "Edward", "Felicity", "Greg", "Harriet"], 3) He answer should be ?Greg? > Date: Tue, 22 Nov 2011 10:02:01 +1100 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] IndexError: list index out of range > > John wrote: > > > > Hi all, > > > > I have wriiten the following code: > > [Segment] > > > >>>> def survivor(names, step): > > index = step - 1 > > next = names > > while len(next)> 1: > > next.remove (next[index]) > > > What is the intention of this function? The name given doesn't mean > anything to me. The parameters "names" and "step" don't seem meaningful. > > I can see what the function does: it deletes bits of something, probably > a list, in a convoluted way, eventually causing an error. But I can't > tell what it is *supposed* to do. > > > Given the example you show later on: > > survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", > "Felicity", "Greg", "Harriet"], 4) > > > what should the result be? > > > > However when ever i run it i get this error message: > > > > Traceback (most recent call last): > > File "", line 1, in > > survivor(["Andrew", "Brenda", "Craig", "Deidre", "Edward", > > "Felicity", "Greg", "Harriet"], 4) > > File "", line 5, in survivor > > next.remove (next[index]) > > IndexError: list index out of range > > > > Any ideas about whats causing this error? > > > You attempt to delete an item that doesn't exist. > > > > > -- > 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 d at davea.name Tue Nov 22 00:49:12 2011 From: d at davea.name (Dave Angel) Date: Mon, 21 Nov 2011 18:49:12 -0500 Subject: [Tutor] Python code trouble! In-Reply-To: References: Message-ID: <4ECAE378.1000204@davea.name> You're still posting from tomorrow. On 11/22/2011 05:50 AM, John wrote: > Hi all, > > I have attempted to create a programme which removes every Nth person > from the list until there is only one name remaining. N is inputted by > the user. > > Here is the code: > > def survivor(names, step): > next = names > while len(next) > 1: > index = step - 1 > next.remove (next[index]) > index = index + step - 1 > while index > len(next): > index = index - len(next) > if index == len(next): > index = 0 > return names[0] > Lots of things wrong with that code. But first we need a complete description of what you want. If you remove every nth item from a list, you'll end up with a somewhat shorter list, but not a single item. For example, if you remove every 4th item from a 13 item list, you'll end up with a 10-item list. So presumably you're defining some kind of repeat, where you do it over and over. But even then, if you try to remove every 4th item from a 3-item list, you'll just end up with a 3-item list. -- DaveA From charleshbecker at gmail.com Tue Nov 22 00:55:57 2011 From: charleshbecker at gmail.com (Charles Karl Becker) Date: Mon, 21 Nov 2011 16:55:57 -0700 Subject: [Tutor] Question on List Comprehensions Message-ID: I'm trying to use a list comprehension to build a list with a variable number of lists nested within it (ideally eventually going several levels of nesting). However I seem to be observing some strange behavior and was wondering if anyone could take a look at this and tell me if what I'm trying to do with list comps is possible, or is a map() or for loop the best thing here? I'm not worrying about incrementing the variables in the later examples since I'm confused about their behavior (just simply adding new elements to the list rather than nesting the lists; and then setting the list to [none] in the last uncommented. The last commented one produces a syntax error, is it impossible to be recursive with list comps like that or is my syntax just faulty?) Thanks! Charles Here's the raw code with my comments : board_size = 5 master_list = [] # this block produces the desired behavior for c in range(board_size): cell = ['', c+1] master_list.append(cell) print(master_list) # I don't understand why this block behaves the way it does master_list = [] master_list = [board_size * cell] print(master_list) # I also don't understand why this block behaves the way that it does master_list = [] master_list = [master_list.append(cell)] print(master_list) # this block produces a syntax error, and I'm not sure why ''' master_list = [] master_list = [x for c in range(board_size) master_list.append(cell)] print(master_list) ''' From steve at pearwood.info Tue Nov 22 00:57:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Nov 2011 10:57:49 +1100 Subject: [Tutor] Python code trouble! In-Reply-To: References: Message-ID: <4ECAE57D.4010908@pearwood.info> Hello John, You are still posting from the future. Please fix your computer so that it is no longer set 12 hours in the future. Or perhaps your computer is just set in the wrong time zone. John wrote: > Hi all, > > I have attempted to create a programme which removes every Nth person > from the list until there is only one name remaining. N is inputted by > the user. Ah, the Josephus problem! Trickier than it seems. http://en.wikipedia.org/wiki/Josephus_permutation > Here is the code: > > def survivor(names, step): > next = names This line is pointless. It just assigns a new name to the same list. Why not just work directly with "names" instead of the misleading "next"? (Next what?) > while len(next) > 1: > index = step - 1 > next.remove (next[index]) This does not do what you think it does, but even when it does, it doesn't it slowly and inefficiently. You start of with an index. You want to delete the item at that index. So you start by retrieving the item at that index, then instruct the list to search from the beginning of the list for something which matches, then delete that. So consider what happens if you have a really huge list, with tens of thousands of items, and ask to delete the last one: even though you know you want to delete the last item, the remove() method has to check every single item first. Worse, what if there are duplicates? The *first* duplicate found will be removed, instead of the one at the given index. If you want to delete the name at an index, you should just directly delete the name at the index: del names[index] > index = index + step - 1 This line is wrong. It means that you take one fewer step each time than you expect. For instance, if you take step = 4, you should step along indexes 3, 3+4=7, 7+4=11, 11+4=15, ... but instead you step along indexes 3, 3+4-1=6, 6+4-1=9, 9+4-1=12, ... > while index > len(next): > index = index - len(next) > if index == len(next): > index = 0 You can combine both of those with a single test: while index >= len(names): index = index - len(names) > return names[0] > > > > To me is appears to be correct, however when i test it i get the > following message: Obviously it isn't correct. Here's a version which is not correct either: def eliminate(names, step): index = -1 while len(names) > 1: print names index += step while index >= len(names): index -= len(names) del names[index] return names[0] but it is simple to read. Can you see what is wrong with it? Hint: perform the elimination by hand, eliminating every fourth person: Starting names: Fred Wilma Barney Betty Scooby Shaggy Daphne Fred Wilma 1st round: Fred Wilma Barney ----- Scooby Shaggy Daphne Fred Wilma 2nd round: Fred Wilma Barney ----- Scooby Shaggy Daphne ---- Wilma 3rd round: Fred Wilma ------ ----- Scooby Shaggy Daphne ---- Wilma 4th round: Fred Wilma ------ ----- Scooby Shaggy Daphne ---- ----- 5th round: Fred Wilma ------ ----- Scooby ------ Daphne ---- ----- 6th round: Fred Wilma ------ ----- ------ ------ Daphne ---- ----- 7th round: Fred Wilma ------ ----- ------ ------ ------ ---- ----- 8th round: Fred ----- ------ ----- ------ ------ ------ ---- ----- But when I use my function: py> eliminate(['FredF', 'Wilma', 'Barney', 'Betty', 'Scooby', 'Shaggy', 'Daphne', 'Fred', 'Wilma'], 4) 'Daphne' I get the wrong person. Why? Watch when I do this instead: Starting names: Fred Wilma Barney Betty Scooby Shaggy Daphne Fred Wilma 1st round: Fred Wilma Barney Scooby Shaggy Daphne Fred Wilma 2nd round: Fred Wilma Barney Scooby Shaggy Daphne Fred 3rd round: Fred Wilma Barney Scooby Daphne Fred 4th round: Fred Wilma Scooby Daphne Fred 5th round: Fred Scooby Daphne Fred 6th round: Fred Daphne Fred 7th round: Fred Daphne 8th round: Daphne Can you see why the two processes are different? The second one is much easier to program, but it is completely different from what you would do in real life. I told you the problem was tricker than it first appears :) -- Steven From steve at pearwood.info Tue Nov 22 01:10:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Nov 2011 11:10:14 +1100 Subject: [Tutor] Question on List Comprehensions In-Reply-To: References: Message-ID: <4ECAE866.7000909@pearwood.info> Charles Karl Becker wrote: > I'm trying to use a list comprehension to build a list with a variable > number of lists nested within it (ideally eventually going several > levels of nesting). However I seem to be observing some strange > behavior and was wondering if anyone could take a look at this and > tell me if what I'm trying to do with list comps is possible, or is a > map() or for loop the best thing here? When in doubt, always use a for loop. List comps can't do anything that for loops can do, in fact they can do LESS. > I'm not worrying about incrementing the variables in the later > examples since I'm confused about their behavior (just simply adding > new elements to the list rather than nesting the lists; and then > setting the list to [none] in the last uncommented. The last > commented one produces a syntax error, is it impossible to be > recursive with list comps like that or is my syntax just faulty?) Your syntax is faulty. List comps are not full-blown replacements for for-loops, they are intentionally simple and straightforward. > board_size = 5 > master_list = [] > > # this block produces the desired behavior > for c in range(board_size): > cell = ['', c+1] > master_list.append(cell) > > print(master_list) > > # I don't understand why this block behaves the way it does > master_list = [] > master_list = [board_size * cell] > print(master_list) You start of with master_list set to an empty list. Then you immediately throw away that empty list, and set master_list to a list containing a single value, board_size * cell. Since by accident cell happens to equal a list left over from the previous part of code, you multiply a number 5 by a list ['', 5]. Multiplication of lists performs repetition: py> ['a', 'b', 'c']*3 ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c'] By the way, there is no list comprehension there. All you have is a list containing a single item. [42] is not a list comp, it is a list containing a single item, 42. [4*x] is not a list comp, it is a list containing a single item, 4*x (whatever x happens to be). [4*x for x in (25, 36, 19, 5)] is a list comp. > # I also don't understand why this block behaves the way that it does > master_list = [] > master_list = [master_list.append(cell)] > print(master_list) You call master_list.append, which modifies master_list in place and returns None. So you append cell to master_list, then you create a new list [None], and set master_list to that new list, throwing away the work you did earlier. Again, there is no list comprehension here either. > # this block produces a syntax error, and I'm not sure why > ''' > master_list = [] > master_list = [x for c in range(board_size) master_list.append(cell)] > print(master_list) > ''' Because you don't have a list comprehension. You can't put add arbitrary code inside a square brackets [ ]. You have to follow the syntax for a list comprehension: listcomp = [expression for name in sequence] not listcomp = [expression for name in sequence another_command] -- Steven From steve at pearwood.info Tue Nov 22 01:14:31 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 22 Nov 2011 11:14:31 +1100 Subject: [Tutor] How to get module name from ImportError In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D396@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D396@MX34A.corp.emc.com> Message-ID: <4ECAE967.8070700@pearwood.info> Nikunj.Badjatya at emc.com wrote: > Hi All, > > Please look at the following snippet. > {{{ > > # User defined modules > try: > from scripts import precheck > from scripts import validate > from scripts import constants > except ImportError: > print("ERROR: One of the modules (..scripts/precheck.py, validate.py, constants) is not present.") > print("INFO : Please verify the above modules, and restart the installation") > sys.exit(1) > > }}} > > See the red line. Please remember that 8% of men, and 1% of women, are colour blind and may not be able to distinguish red. In the computer community, that figure is probably higher: I have heard credible reports that red-green colour blindness is more common among mathematicians, scientists and computer programmers than normal. Please also remember that many people, especially programmers, disable HTML in email, as it is a security and privacy risk. Consequently they will not see colours, fancy fonts, dancing paperclips, coloured backgrounds, or any other superfluous junk used in HTML email. > I want to get the name of the particular module which is not available and hence causing ImportError. > One of the ways can be to get the STDERR and process it using re. !? Absolutely not. The error message is not part of the API of Python, which means it could change without warning. It should be safe to assume that the error message itself will describe the missing module in some fashion, but parsing the error is the wrong solution. The way I would do this is: # Untested try: from scripts import precheck, validate, constants except ImportError as err: msg = err.args[0] msg += '\n whatever new message you want to add' err.args = (msg,) # note the comma is important raise # re-raise the exception Hope that helps. -- Steven From beachkidken at gmail.com Tue Nov 22 01:24:57 2011 From: beachkidken at gmail.com (Ken G.) Date: Mon, 21 Nov 2011 19:24:57 -0500 Subject: [Tutor] File vs. Database (possible off topic) Message-ID: <4ECAEBD9.10504@gmail.com> It occurred to me last week while reviewing the files I made in using Python, it could be somewhat similar to a database. What would be a different between a Python files and Python databases? Granted, the access in creating them are different, I really don't see any different in the format of a file and a database. Again, this may be off topic, but where can I review the basic concepts of creating a database/file. For example, when is a back up file created, after inputting a new value? Is sorting a consider a separate program after inputting a new value? It has been some 30 years since I took a course in basic data processing and I am hazy in trying to remember the basic concepts. If this is off topic, I apologized for posting here. Ken, Kentucky, USA From d at davea.name Tue Nov 22 01:44:49 2011 From: d at davea.name (Dave Angel) Date: Mon, 21 Nov 2011 19:44:49 -0500 Subject: [Tutor] Python code trouble! In-Reply-To: <4ECAE57D.4010908@pearwood.info> References: <4ECAE57D.4010908@pearwood.info> Message-ID: <4ECAF081.1090206@davea.name> On 11/21/2011 06:57 PM, Steven D'Aprano wrote: > Hello John, > > > You are still posting from the future. Please fix your computer so > that it is no longer set 12 hours in the future. Or perhaps your > computer is just set in the wrong time zone. > > > John wrote: >> Hi all, >> >> I have attempted to create a programme which removes every Nth person >> from the list until there is only one name remaining. N is inputted >> by the user. > > Ah, the Josephus problem! Trickier than it seems. > > http://en.wikipedia.org/wiki/Josephus_permutation > > >> Here is the code: >> >> def survivor(names, step): >> next = names > > This line is pointless. It just assigns a new name to the same list. > Why not just work directly with "names" instead of the misleading > "next"? (Next what?) > >> while len(next) > 1: >> index = step - 1 >> next.remove (next[index]) > > This does not do what you think it does, but even when it does, it > doesn't it slowly and inefficiently. > > You start of with an index. You want to delete the item at that index. > So you start by retrieving the item at that index, then instruct the > list to search from the beginning of the list for something which > matches, then delete that. So consider what happens if you have a > really huge list, with tens of thousands of items, and ask to delete > the last one: even though you know you want to delete the last item, > the remove() method has to check every single item first. > > Worse, what if there are duplicates? The *first* duplicate found will > be removed, instead of the one at the given index. > > If you want to delete the name at an index, you should just directly > delete the name at the index: > > del names[index] > > >> index = index + step - 1 > > This line is wrong. It means that you take one fewer step each time > than you expect. For instance, if you take step = 4, you should step > along indexes 3, 3+4=7, 7+4=11, 11+4=15, ... but instead you step > along indexes 3, 3+4-1=6, 6+4-1=9, 9+4-1=12, ... Actually, this one is the one he got right. Since he just deleted an item from the list, he should base the step off one *before* the present one. index = (index-1) + step > > >> while index > len(next): >> index = index - len(next) >> if index == len(next): >> index = 0 > > You can combine both of those with a single test: > > while index >= len(names): > index = index - len(names) > He could simplify that using the modulo operator. > >> return names[0] >> >> I'm not familiar with the Josephus problem, and I don't have time right now to research it. So I can't help with the rest. -- DaveA From alan.gauld at btinternet.com Tue Nov 22 03:01:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Nov 2011 02:01:12 +0000 Subject: [Tutor] File vs. Database (possible off topic) In-Reply-To: <4ECAEBD9.10504@gmail.com> References: <4ECAEBD9.10504@gmail.com> Message-ID: On 22/11/11 00:24, Ken G. wrote: > It occurred to me last week while reviewing the files I made in using > Python, it could be somewhat similar to a database. Depending on how broadly you define "database" you could be right. > What would be a different between a Python files and Python databases? There is no such thing as a python database per-se. You can create databases in Python, as you can in any language. > Granted, the access in creating them are different, I really don't see > any different in the format of a file and a database. A database in its most general sense describes a type of usage of a file so ther is no difference. However in the computing sense a database usually implies either a system or library that optimises the storage and retrieval of data in a way that is more efficient than simple sequential file access in Python. One such database is SqlLite which comes with Python. (But more primitive databases are also provided like gdbms) > Again, this may be off topic, but where can I review the basic concepts > of creating a database/file. Since its about programming basics its just about on topic. But I'd start by reading wikipedia on the subject of databases. That will lead you into several different areas depending on interests. The theory of data storage/processing, the different available databases, object v relational data theory, and SQL. > For example, when is a back up file created, after inputting a new value? When the programmer creates it. In most operating systems backups are not reated automatically (VAX VMS and IBM OS./390 and a few others(Pick?) being exceptions). But that has nothing much to do with databases. > Is sorting a consider a separate program after inputting a new value? Yes, its a different operation that requires its own code - although Python does provide a sort method and most databases will provide a sort command. > It has been some 30 years since I took a course in basic > data processing... Things have moved on quite a long way! Check wikipedia. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 22 03:04:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Nov 2011 02:04:14 +0000 Subject: [Tutor] Question on List Comprehensions In-Reply-To: <4ECAE866.7000909@pearwood.info> References: <4ECAE866.7000909@pearwood.info> Message-ID: On 22/11/11 00:10, Steven D'Aprano wrote: > Because you don't have a list comprehension. You can't put add arbitrary > code inside a square brackets [ ]. You have to follow the syntax for a > list comprehension: > > listcomp = [expression for name in sequence] > > not > > listcomp = [expression for name in sequence another_command] And being picky you can add a conditional after the loop: > listcomp = [expression for name in sequence if some_condition] But it must be an if test, nothing else will do. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From modulok at gmail.com Tue Nov 22 04:14:57 2011 From: modulok at gmail.com (Modulok) Date: Mon, 21 Nov 2011 20:14:57 -0700 Subject: [Tutor] File vs. Database (possible off topic) In-Reply-To: <4ECAEBD9.10504@gmail.com> References: <4ECAEBD9.10504@gmail.com> Message-ID: On 11/21/11, Ken G. wrote: > It occurred to me last week while reviewing the files I made in using > Python, it could be somewhat similar to a database. > > What would be a different between a Python files and Python databases? > Granted, the access in creating them are different, I really don't see > any different in the format of a file and a database. > > Again, this may be off topic, but where can I review the basic concepts > of creating a database/file. For example, when is a back up file > created, after inputting a new value? Is sorting a consider a separate > program after inputting a new value? It has been some 30 years since I > took a course in basic data processing and I am hazy in trying to > remember the basic concepts. > > If this is off topic, I apologized for posting here. > > Ken, Kentucky, USA Generally speaking, If you ever even think the word 'database', your best choice 98% of the time is sqlite. (The module is called 'sqlite3' in python.) Reading up on SQL on wikipedia and sqlite3 in the python docs is a good place to start! Eventually, if you start storing a massive number of records and need things like concurrent access and load balancing across multiple physical machines and so forth, sqlite isn't going to cut the mustard. In such cases people use a dedicated database server like postgresql, mysql, etc; A totally separate program that does nothing but database black magic. Your python programs will talk to the database server through a module written for that server. The database server will fetch, sort, update and store the actual data. Python has bindings to these heavy weight database backends through third party modules that abstract the details for you. The most popular module is probably sqlalchemy. It talks to postgresql, mysql and a few others. It's a good idea to get used to sqlite and general SQL concepts before you jump into sqlalchemy! Good luck! -Modulok- From pasokan at talentsprint.com Tue Nov 22 04:22:05 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Tue, 22 Nov 2011 08:52:05 +0530 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <4ECAD869.1030004@pearwood.info> References: <4ECB3135.3050702@hotmail.com> <4ECAD869.1030004@pearwood.info> Message-ID: On Tue, Nov 22, 2011 at 4:32 AM, Steven D'Aprano wrote: > John wrote: > >> >> Hi all, >> >> I have wriiten the following code: >> [Segment] >> >> def survivor(names, step): >>>>> >>>> index = step - 1 >> next = names >> while len(next)> 1: >> next.remove (next[index]) >> > > > What is the intention of this function? The name given doesn't mean > anything to me. The parameters "names" and "step" don't seem meaningful. > I guess he is trying the Josephus problem. I am guessing from the name! If so, you have to remember that when you delete an item you change the positions of subsequent items. For example, in a 11-element list, say A, if you want to delete every third, the index numbers you *should* delete are 2, 5, 8. But if you delete A[2], then you will delete the original A[6] and then the original A[10]. So you have to think in terms of 'marking' for deletion and later deleting or deleting from the other end. A more interesting possibility is to replicate the original list and append it to itself and "delete" all occurrences. About 25 years back thats what I did in BASIC and won an honorable mention in a coding contest in a magazine :-) I replaced the cell contents with a space and in subsequent rounds counted non-space items. The first prize was won by a circular(linked-)list in Pascal, with the same repace by Space idea HTH Asokan -------------- next part -------------- An HTML attachment was scrubbed... URL: From charleshbecker at gmail.com Tue Nov 22 06:45:25 2011 From: charleshbecker at gmail.com (Charles Karl Becker) Date: Mon, 21 Nov 2011 22:45:25 -0700 Subject: [Tutor] Question on List Comprehensions In-Reply-To: References: <4ECAE866.7000909@pearwood.info> Message-ID: Steven and Alan, Thank you for your comments! Alan said: >> Because you don't have a list comprehension. You can't put add arbitrary >> code inside a square brackets [ ]. You have to follow the syntax for a >> list comprehension: This helps me understand a lot when looking back, I thought that any operation done in place of defining the list literally was a list comprehension. I'm on wikipedia and a few tutorials now to refine and will post back when I've come up with the solution I'm looking for (and a comment as to if it's worth replacing a for loop with). Thanks again! Charles On Mon, Nov 21, 2011 at 7:04 PM, Alan Gauld wrote: > On 22/11/11 00:10, Steven D'Aprano wrote: > >> Because you don't have a list comprehension. You can't put add arbitrary >> code inside a square brackets [ ]. You have to follow the syntax for a >> list comprehension: >> >> listcomp = [expression for name in sequence] >> >> not >> >> listcomp = [expression for name in sequence another_command] > > And being picky you can add a conditional after the loop: > >> listcomp = [expression for name in sequence if some_condition] > > But it must be an if test, nothing else will do. > > -- > Alan G > 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 charleshbecker at gmail.com Tue Nov 22 08:49:25 2011 From: charleshbecker at gmail.com (Charles Becker) Date: Tue, 22 Nov 2011 00:49:25 -0700 Subject: [Tutor] Question on List Comprehensions In-Reply-To: References: <4ECAE866.7000909@pearwood.info> Message-ID: Alan, Steve, future readers, After some re-reading and hacking I was able to discover the solution. Since I raised the question here it is : [['{0}'.format(x+1), x+1] for x in range(size)] This will create the list with nested lists for whatever number 'size' is set to. This should be good enough to get anyone started on future problems in this area, and yes the redundancy present does make sense in the scope of what I'm working on. :) Thanks! I'll leave future questions on the backburner a little longer. Charles Sent from my iPhone On Nov 21, 2011, at 7:04 PM, Alan Gauld wrote: > On 22/11/11 00:10, Steven D'Aprano wrote: > >> Because you don't have a list comprehension. You can't put add arbitrary >> code inside a square brackets [ ]. You have to follow the syntax for a >> list comprehension: >> >> listcomp = [expression for name in sequence] >> >> not >> >> listcomp = [expression for name in sequence another_command] > > And being picky you can add a conditional after the loop: > > > listcomp = [expression for name in sequence if some_condition] > > But it must be an if test, nothing else will do. > > -- > Alan G > 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 pasokan at talentsprint.com Tue Nov 22 11:15:28 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Tue, 22 Nov 2011 15:45:28 +0530 Subject: [Tutor] Python code trouble! In-Reply-To: <4ECAF081.1090206@davea.name> References: <4ECAE57D.4010908@pearwood.info> <4ECAF081.1090206@davea.name> Message-ID: Okay! I wrote some code. It is below so that you can avoid scrolling down and seeing it if you do not want to see any code! HTH Asokan people = list(" ABCDEFGHIJKLMN") COUNT = len(people) remove = 3 SPACE = ' ' def survivorCount(a): return len(a) - a.count(SPACE) pos = 0 men = 0 while survivorCount(people) != 1: if people[pos] != SPACE: men += 1 if men % remove == 0: print "removed", people[pos], "at", pos people[pos] = SPACE pos = (pos + 1) % COUNT print ''.join(people).strip() -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Tue Nov 22 14:17:47 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 22 Nov 2011 08:17:47 -0500 Subject: [Tutor] basic class loading question Message-ID: I have a basic question about how to load a class. If I have this class: class QB: def __init__(self, first_name='', last_name='', phone='', email='', stadium=''): self.first_name = first_name self.last_name = last_name self.phone = phone self.email = email self.stadium = stadium and this data: QB_list = [["Joe", "Montana", "415-123-4567", "joe.montana at gmail.com","Candlestick Park"], ["Fran", "Tarkington","651-321-7657", "frank.tarkington at gmail.com", "Metropolitan Stadidum"], ["Joe", "Namath", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], ["John", "Elway", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], ["Archie", "Manning", "504-888-1234", "archie.manning at gmail.com", "Louisiana Superdome"], ["Roger", "Staubach", "214-765-8989", "roger.staubach at gmail.com", "Cowboy Stadium"]] What is the best way to load it? I'm thinking there should be an append method, but I'm having trouble getting it to work. -- Frank L. "Cranky Frankie" Palmeri From steve at pearwood.info Tue Nov 22 14:13:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 23 Nov 2011 00:13:43 +1100 Subject: [Tutor] File vs. Database (possible off topic) In-Reply-To: <4ECAEBD9.10504@gmail.com> References: <4ECAEBD9.10504@gmail.com> Message-ID: <4ECBA007.50205@pearwood.info> Ken G. wrote: > It occurred to me last week while reviewing the files I made in using > Python, it could be somewhat similar to a database. > > What would be a different between a Python files and Python databases? > Granted, the access in creating them are different, I really don't see > any different in the format of a file and a database. A database is essentially a powerful managed service built on top of one or more files. There's nothing you can do with a database that you can't do with a big set of (say) Windows-style INI files and a whole lot of code to manage them. A database does all the management for you, handling all the complexity, data integrity, and security, so that you don't have to re-invent the wheel. Since database software tends to be big and complicated, there is a lot of wheel to be re-invented. To be worthy of the name "database", the service must abide by the ACID principles: Atomicity --------- The "all or nothing" principle. Every transaction must either completely succeed, or else not make any changes at all. For example, if you wish to transfer $100 from account A to account B, it must be impossible for the money to be removed from A unless it is put into B. Either both operations succeed, or neither. Consistency ----------- Any operation performed by the database must always leave the system in a consistent state at the end of the operation. For example, a database might have a table of "Money Received" containing $2, $3, $5, $1 and $2, and another field "Total" containing $13, and a rule that the Total is the sum of the Money Received. It must be impossible for an operation to leave the database in an inconsistent state by adding $5 to the Money Received table without increasing Total to $18. Isolation --------- Two transactions must always be independent. It must be impossible for two transactions to attempt to update a field at the same time, as the effect would then be unpredictable. Durability ---------- Once a transaction is committed, it must remain committed, even if the system crashes or the power goes out. Once data is written to disk, nothing short of corruption of the underlying bits on the disk should be able to hurt the database. Note that in practice, these four ACID principles may be weakened slightly, or a lot, for the sake of speed, convenience, laziness, or merely by incompetence. Generally speaking, for any program (not just databases!) the rule is: "Fast, correct, simple... pick any two." so the smaller, faster, lightweight databases tend to be not quite as bullet-proof as the big, heavyweight databases. Modern databases also generally provide an almost (but not quite) standard interface for the user, namely the SQL programming language. Almost any decent database will understand SQL. For example, this command: SELECT * FROM Book WHERE price > 100.00 ORDER BY title; is SQL to: * search the database for entries in the Book table * choose the ones where the price of the book is greater than $100 * sort the results by the book title * and return the entire record (all fields) for each book So, broadly speaking, if you learn SQL, you can drive most databases, at least well enough to get by. -- Steven From d at davea.name Tue Nov 22 14:39:22 2011 From: d at davea.name (Dave Angel) Date: Tue, 22 Nov 2011 08:39:22 -0500 Subject: [Tutor] basic class loading question In-Reply-To: References: Message-ID: <4ECBA60A.3080609@davea.name> On 11/22/2011 08:17 AM, Cranky Frankie wrote: > I have a basic question about how to load a class. If I have this class: > > class QB: > def __init__(self, first_name='', last_name='', phone='', > email='', stadium=''): > self.first_name = first_name > self.last_name = last_name > self.phone = phone > self.email = email > self.stadium = stadium > > and this data: > > QB_list = [["Joe", "Montana", "415-123-4567", > "joe.montana at gmail.com","Candlestick Park"], > ["Fran", "Tarkington","651-321-7657", > "frank.tarkington at gmail.com", "Metropolitan Stadidum"], > ["Joe", "Namath", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], > ["John", "Elway", "303-9876-333", "john.elway at gmai.com", "Mile > High Stadium"], > ["Archie", "Manning", "504-888-1234", "archie.manning at gmail.com", > "Louisiana Superdome"], > ["Roger", "Staubach", "214-765-8989", "roger.staubach at gmail.com", > "Cowboy Stadium"]] > > What is the best way to load it? I'm thinking there should be an > append method, but I'm having trouble getting it to work. > > No idea what you mean by "load a class." You can create an object by the classname and parentheses, containing the paramters as specified in the __init__() method. So since your class was called QB (which should be Qb, by naming conventions): obj = QB("Joe", "Montana", "415-213-4567", joe.montana at gmail.com","Candlestick Park") and since that happens to be one element of your list, you could use obj = QB( *QB_list[0] ) If you want a collection of such objects, you might want to write a loop, and then indeed the append method might be useful. Write some code, and show us where you get stuck. -- DaveA From cranky.frankie at gmail.com Tue Nov 22 15:20:39 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 22 Nov 2011 09:20:39 -0500 Subject: [Tutor] basic class loading question In-Reply-To: <4ECBA60A.3080609@davea.name> References: <4ECBA60A.3080609@davea.name> Message-ID: OK, but this is still not working: class Qb: def __init__(self, first_name='', last_name='', phone='', email='', stadium=''): self.first_name = first_name self.last_name = last_name self.phone = phone self.email = email self.stadium = stadium Qb_list = [["Joe", "Montana", "415-123-4567", "joe.montana at gmail.com","Candlestick Park"], ["Fran", "Tarkington","651-321-7657", "frank.tarkington at gmail.com", "Metropolitan Stadidum"], ["Joe", "Namath", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], ["John", "Elway", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], ["Archie", "Manning", "504-888-1234", "archie.manning at gmail.com", "Louisiana Superdome"], ["Roger", "Staubach", "214-765-8989", "roger.staubach at gmail.com", "Cowboy Stadium"]] len_Qb_list = len(Qb_list) for i in range(0, len_Qb_list): quarterbacks = Qb(*Qb_list[i]) i = i + 1 print(quarterbacks.last_name(2)) -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From steve at alchemy.com Tue Nov 22 15:54:53 2011 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 22 Nov 2011 06:54:53 -0800 Subject: [Tutor] Question on List Comprehensions In-Reply-To: References: <4ECAE866.7000909@pearwood.info> Message-ID: <4ECBB7BD.4020004@alchemy.com> On 21-Nov-11 23:49, Charles Becker wrote: > Alan, Steve, future readers, > > After some re-reading and hacking I was able to discover the solution. Since I raised the question here it is : > > [['{0}'.format(x+1), x+1] for x in range(size)] Just to fill out some other refinements for your information, if you're not planning to do anything special with the string formatting in each list, you don't really need to call format() when all it's doing is just making a string representation of the data value. so '{0}'.format(x+1) could just be str(x+1) Resulting in: [[str(x+1), x+1] for x in range(size)] Also, if you didn't like the repeated x+1 in there, you could just change the range call to go from 1..size directly: [[str(x), x] for x in range(1,size+1)] -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From o0MB0o at hotmail.se Tue Nov 22 16:11:59 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 22 Nov 2011 16:11:59 +0100 Subject: [Tutor] Shortening code. In-Reply-To: References: Message-ID: Please change to a sensible subject when replying to digest messages. -Yes, sorry about that. ############################ from tkinter import* button1_color="green" button1_value=False button2_color="green" button2_value=False ############################ buttonX_value still doesn't say much about *why* the variable is there. What are you storing in it. What does the value represent? Also, do you really need the colors, you don't actually use them for anything below except the initial color, but you might as well just hard code it to "green", it would be shorter and more explicit... ------------------------------------------------------------ This is a part of a larger program I am writing, where you are supposed to book chairs on a train. Button1 is supposed to represent chair one in the train. When you click at the button, which represents a chair, it is supposed to change color to show that the chair now is booked. If you press it one more time, it is supposed to change color to show that the chair is free to book. That was the idea. I am sorry if this was confusing, I will try to explain it more detailed later on in the mail. ----------------------------------------------------------------------------------------- > if button1_value: > self.hello_bttn1.configure(bg="red", text="Hi_2") Note that this is the line that really changes the button's color. And it does not use the variable... > def change_button1_color_red(): > global button1_color > button1_color=("red") > change_button1_color_red() Whereas this function and its call do nothing but change the value of a variable that is never used after the initial creation. If you took this out the code would run with exactly the same effect. > else: > self.hello_bttn1.configure(bg="green", text="Hi_1") Same, here. You set the color explicitly, then create a function and call it just to update a variable you don't use. > def change_button1_color_green(): > global button1_color > button1_color=("green") > change_button1_color_green() --------------------------------------------------------------------- I understand why you think I don't need to change the global value, since I am already changing the color with this line. self.hello_bttn1.configure(bg="green", text="Hi_1") The thing is that this window I have created is just a window in another window. I want the color to be the same that it was before I closed the window. Otherwise the color would be green when I open the window again, despite closing the window when the button was red. I hope you understand what I mean by this? ############################### def button2_clicked(self): """This method runs if button two is clicked""" def change_button2_value(): global button2_value button2_value=not button2_value change_button2_value() if button2_value: self.hello_bttn2.configure(bg="red", text="Hi_2") def change_button2_color_red(): global button2_color button2_color=("red") change_button2_color_red() else: self.hello_bttn2.configure(text="Hi_1", bg="green") def change_button2_color_green(): global button2_color button2_color=("green") change_button2_color_green() ############################################ Notice that both button handlers are identical except they work on different buttons and test values. What we'd like is a single function that gets passed the widget and test as parameters. It would look like this: def button_clicked(self, widget, test): if test: widget.configure(bg="red", text="Hi_2") else: widget.configure(text="Hi_1", bg="green") and to call it we create two short event handlers: def button1_clicked(self): self.button1_value = not self.button1_value self.button_clicked(button1,self.button1_value) def button2_clicked(self): self.button2_value = not self.button2_value self.button_clicked(button2,self.button2_value) Notice I've moved the test values to instance variables rather than globals, but thats just a style thing you could have referenced the globals within the handlers instead. I also removed those spurious functions from the main button_clicked code. ------------------------------------------------------------------------- This was exactly what I thought, that they these functions are so similiar that it should be one way to shorten this code. In reality, in my larger program, I have about 10 buttons that should change value, and colors when you click them. > However, I did not understand this part of your suggestions: > > Generally you build a data table with all the config parameters that > > will varty then you build a loop to read the values from the > > data table. > > Store the created buttons in a list or dictionary. > > I must admit that I have never heard of a "data table" before. > Is this easy to do, for a beginner like me? Yes its just a list of tuples/lists. For your two buttons uit would look like: # buttonName text, color, command self.button_params = [ ("b1", "Hi_1", "green", self.button1_clicked), ("b2", "Hi_2", "green", self.button2_clicked) ] Now your create_widgets looks like: def create_widgets(self): self.Buttons = {} for params in self.button_params: b = Button(self, bg=params[1], text=params[2], command=params[3]) self.Buttons[params[0]] = b And now you can access your buttons at any time using self.Buttons["b1"] etc We could use a dictionary for params to make it more readable at the expense of more typing: # buttonName text, color, command self.button_params = [ { "name": "b1", "text":"Hi_1", "color":"green", "Command":self.button1_clicked }, { "name": "b1", "text":"Hi_1", "color":"green", "Command":self.button1_clicked } ] You could then put that in a separate file which you import into you GUI creation file. You could have a similar list for each type of widget you want to create. However you still need to know how to place them within the GUI, so either you create a very complex parameters structure or you just keep the complexity in the creation method. But tis technique is worth while where you are creating a list of near identical widgets - like the buttons in a calculator keybad say... To process the dictionary the creation loop changes to: for params in self.button_params: b = Button(self, bg=params["color"], text=params["text"], command=params["command"]) self.Buttons[params["name"]] = b ---------------------------------------------------------------------------------- Thank you for this detailed explaination. I have tried to get your suggestions above to work but I feel I should explain a little more detailed why I am asking these questions. As I mentioned at the top of my email, I am writing a larger program. This program is supposed to be a GUI online booking program for train tickets. I want to move up on year in school so I am trying to finish this program that is supposed to be finished in a long, long time. These buttons I have created above are supposed to represent a chair. So when you click at one of the chairs it is supposed to change color from green to red, and at the same time create a file with the chair's number, price and so on. I have managed to create this file without any problem. But the thing is that I have written a function for each of the chairs that does nearly the same thing. That is not good, because I want one function to do this for all chairs. I know you tried to explain this, and you did it very good, it is just that I don't understand how I should implement this in my program. If you want to I could send you my real program, and you would perhaps get a better understanding of what I am trying to accomplish and why I ask these questions. However, I understand if you don't have time to answer these probably stupid and simple questions, I am still grateful for your previous answers! Thank you! Mic From d at davea.name Tue Nov 22 17:26:03 2011 From: d at davea.name (Dave Angel) Date: Tue, 22 Nov 2011 11:26:03 -0500 Subject: [Tutor] basic class loading question In-Reply-To: References: <4ECBA60A.3080609@davea.name> Message-ID: <4ECBCD1B.7020405@davea.name> On 11/22/2011 09:20 AM, Cranky Frankie wrote: > OK, but this is still not working: > > class Qb: > def __init__(self, first_name='', last_name='', phone='', > email='', stadium=''): > self.first_name = first_name > self.last_name = last_name > self.phone = phone > self.email = email > self.stadium = stadium > > > > Qb_list = [["Joe", "Montana", "415-123-4567", > "joe.montana at gmail.com","Candlestick Park"], > ["Fran", "Tarkington","651-321-7657", > "frank.tarkington at gmail.com", "Metropolitan Stadidum"], > ["Joe", "Namath", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], > ["John", "Elway", "303-9876-333", "john.elway at gmai.com", "Mile > High Stadium"], > ["Archie", "Manning", "504-888-1234", "archie.manning at gmail.com", > "Louisiana Superdome"], > ["Roger", "Staubach", "214-765-8989", "roger.staubach at gmail.com", > "Cowboy Stadium"]] > > > > len_Qb_list = len(Qb_list) > > for i in range(0, len_Qb_list): > quarterbacks = Qb(*Qb_list[i]) > i = i + 1 > > print(quarterbacks.last_name(2)) > > You'll generally get better responses by saying in what way it's not working. In this case, I get an exception in the print statement at the end. So your message ought to state that, and show the traceback. The specific error that causes that exception is you're trying to call a string. What's that (2) all about anyway? quarterbacks is an objext of type Qb, and quarterbacks.last_name is a string. Your variable quarterbacks currently contains an object representing the last line of the list, the one for Roger Staubach. You kept replacing the value in quarterbacks with the next item from the original list. If you actually want a list of the objects, you need to say so. quarterbacks = [] for .... quarterbacks.append( ) Now that you really have a list, then you can print a particular one with: print (quarterbacks[2].last_name) (I tested my own variant using python 2.7. And i'm not saying your code can't be improved. You're learning, and getting it correct is much more important than getting it "optimal.") -- DaveA From cranky.frankie at gmail.com Tue Nov 22 18:09:53 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 22 Nov 2011 12:09:53 -0500 Subject: [Tutor] basic class loading question In-Reply-To: <4ECBCD1B.7020405@davea.name> References: <4ECBA60A.3080609@davea.name> <4ECBCD1B.7020405@davea.name> Message-ID: On Tue, Nov 22, 2011 at 11:26 AM, Dave Angel wrote: snip > quarterbacks = [] > for .... > ? ? quarterbacks.append( ? ? ? ) > > > Now that you really have a list, then you can print a particular one with: > > print (quarterbacks[2].last_name) Dave I'm sorry but I just don't get this. I have virtually no experience with classes. What seems like it shoud work is this: ####################### len_Qb_list = len(Qb_list) for i in range(0, len_Qb_list): quarterbacks = Qb(*Qb_list[i]) i = i + 1 print (quarterbacks[2].last_name) ############################ In other words, define an instance of the Qb class called quarterbacks, and then "load" or instantiate instances of the class using the 6 sets of values from Qb_list. My error message is: Traceback (most recent call last): File "D:/Python31/q", line 27, in print (quarterbacks[2].last_name) TypeError: 'Qb' object does not support indexing -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From d at davea.name Tue Nov 22 19:48:56 2011 From: d at davea.name (Dave Angel) Date: Tue, 22 Nov 2011 13:48:56 -0500 Subject: [Tutor] basic class loading question In-Reply-To: References: <4ECBA60A.3080609@davea.name> <4ECBCD1B.7020405@davea.name> Message-ID: <4ECBEE98.7050004@davea.name> On 11/22/2011 12:09 PM, Cranky Frankie wrote: > On Tue, Nov 22, 2011 at 11:26 AM, Dave Angel wrote: > snip >> quarterbacks = [] >> for .... >> quarterbacks.append( ) >> >> >> Now that you really have a list, then you can print a particular one with: >> >> print (quarterbacks[2].last_name) > Dave I'm sorry but I just don't get this. I have virtually no > experience with classes. > > What seems like it shoud work is this: > > ####################### > len_Qb_list = len(Qb_list) > > for i in range(0, len_Qb_list): > quarterbacks = Qb(*Qb_list[i]) That creates one quarterback, not a list of them. So you need to append that to some list. As I said in my earlier message, you might want to append it to a list called quarterbacks, not replace the earlier object. > i = i + 1 > > print (quarterbacks[2].last_name) > ############################ > > In other words, define an instance of the Qb class called > quarterbacks, and then "load" or instantiate instances of the class > using the 6 sets of values from Qb_list. > > My error message is: > > Traceback (most recent call last): > File "D:/Python31/q", line 27, in > print (quarterbacks[2].last_name) > TypeError: 'Qb' object does not support indexing > > As long as it's a single object of your class, you can't index it. Do you have any experience building a list in Python? If you're trying to do it in a for loop. you'd have something like objects= [] #create empty list for .........whatever.......... newobject = ......something.... objects.append(newobject) Now you have a list called objects. You also have a newobject, which is the last one added. -- DaveA From mayoadams at gmail.com Tue Nov 22 19:50:51 2011 From: mayoadams at gmail.com (Mayo Adams) Date: Tue, 22 Nov 2011 13:50:51 -0500 Subject: [Tutor] write list of tuples to file (beginner) Message-ID: I have a list of tuples of the form (string,integer) that I would like to write to a file with a line break between each. Simply writing to a file object thus for item in tuplelist outputfile.write (item) doesn't work, and I suppose I scarcely expect it should, but I am at a loss to find out how to do it. -- Mayo Adams mayoadams at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 22 20:00:09 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Nov 2011 19:00:09 +0000 Subject: [Tutor] Shortening code. In-Reply-To: References: Message-ID: On 22/11/11 15:11, Mic wrote: > > Also, do you really need the colors, you don't actually use them for > > anything below except the initial color, but you might as well just hard > Button1 is supposed to represent chair one in the train. So call it chair_1 or put it in a list called chairs so that you can access them as chairs[0] or whatever. But get a name that reflects what its actually used for. > When you click at the button, which represents a chair, > it is supposed to change color to show that the chair now is booked. If > you press it one more time, it is supposed to > change color to show that the chair is free to book. Thats all fine but you are not doing that, so the variable is currently pointless. Either change the code to use the variable or delete the variable which is simply wasting space and time and making the code less readable. > --------------------------------------------------------------------- > I understand why you think I don't need to change the global value, > since I am already changing the color with this line. > self.hello_bttn1.configure(bg="green", text="Hi_1") > > The thing is that this window I have created is just a window in another > window. I want the color to be the same that it was before I closed the > window. > Otherwise the color would be green when I open the window again, despite > closing the window when the button was red. I hope you understand what I > mean by this? Yes, but the point is that you are not using the variable just now. So use it even if its not part of your master plan just yet. Or, if the code is only to demonstrate a point leave it out completely > at the top of my email, I am writing a larger program. This program is > supposed to be a GUI online booking program for train tickets. OK, That's a pity. A Tkinter program is never going to be an online GUI, it only works on the desktop. For that you need to use HTML5/Flash/Javascript/Java etc. And its all a lot more messy. > However, I understand if you don't have time to answer these probably > stupid and simple questions, I am still grateful for your previous answers! They are neither simple nor stupid, they are very sensible questions and you are tackling a significant program. Sadly I don't think your approach will work for an 0nline solution (ie a web based one). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Tue Nov 22 20:12:24 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 22 Nov 2011 20:12:24 +0100 Subject: [Tutor] write list of tuples to file (beginner) In-Reply-To: References: Message-ID: On Tue, Nov 22, 2011 at 7:50 PM, Mayo Adams wrote: > I have a list of tuples of the form (string,integer) that I would like to > write? to? a file with a line break between each. Simply writing to a file > object thus > > for item in tuplelist > ?????????? outputfile.write (item) > > doesn't work, and I suppose I scarcely expect it should, but I am at a loss > to find out how to do it. > Pro tip: When you seek programming help, never, ever write "it doesn't work." For us, it is the least helpful problem description ever. Instead, you should describe to us two things: 1) what you expected to happen 2) what happened instead under 2, make sure you include any possible error messages you got. For example, when I tried to write a tuple to a file, I got this: Traceback (most recent call last): File "", line 1, in f.write((1, 2)) TypeError: expected a character buffer object Well, hello, a TypeError! Now we have some idea of what's going on. A TypeError means that a function argument you supplied is of an incorrect type. And well, that makes sense, since the write function expects a "character buffer object" (in most cases, that'll be a string), and we supplied a tuple. So how do we solve this? Well, the easiest way is to convert our tuple into a string: f.write(str(item)) that'll write your item to the file formatted like a tuple, i.e. enclosed in parentheses and with a comma separating the items. We could also write it in a different way, like only separated by a space: f.write("%s %s" % item) This uses the string formatting operator % (you might want to read up on it). You can choose tons of different formats using this same formatting technique, pick what you like. You can even mimic what we did with the str() function up above: f.write("(%s, %s)" % item) though that's a bit redundant, of course. But the important point is that the file is just text, so you can format the data you write to it however you like, as long as you write it as text. If you want to write actual python objects rather than text representations of them, you should look at the pickle module. Hugo From alan.gauld at btinternet.com Tue Nov 22 20:14:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Nov 2011 19:14:16 +0000 Subject: [Tutor] basic class loading question In-Reply-To: References: <4ECBA60A.3080609@davea.name> <4ECBCD1B.7020405@davea.name> Message-ID: On 22/11/11 17:09, Cranky Frankie wrote: > Dave I'm sorry but I just don't get this. I have virtually no > experience with classes. You need to step back and rethink the terminology a bit. A class is a cookie cutter for creating objects. Objects are instances of the class. > What seems like it should work is this: > > ####################### > len_Qb_list = len(Qb_list) > > for i in range(0, len_Qb_list): > quarterbacks = Qb(*Qb_list[i]) > i = i + 1 This repeatedly creates an instance of Qb and assigns it to the variable quarterbacks. quarterbacks always holds the last instance to be created, the previous instance is destroyed. You want to create a list (not an instance of Qb but an ordinary list) which will hold these quarterback objects you are creating. > print (quarterbacks[2].last_name) This tries to print the second something of quarterbacks. But since quarterbacks is a single object it fails. So you need sometjing like this quarterbacks = [] # an empty list # get each list entry in turn for data in Qb_list: # create an object and add to the list of quarterbacks quarterbacks.append(Qb(*data)) And now print quarterbacks[2].last_name makes sense. It will print the last name of the 3rd entry. > In other words, define an instance of the Qb class called > quarterbacks, and then "load" or instantiate instances of the class > using the 6 sets of values from Qb_list. An instance of Qb is just a quarterback object. You can't load it with instances of anything. You might find it useful to read the OOP topic in my tutorial for a different explanation of OOP... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From matt.gregory at oregonstate.edu Tue Nov 22 20:12:29 2011 From: matt.gregory at oregonstate.edu (Gregory, Matthew) Date: Tue, 22 Nov 2011 11:12:29 -0800 Subject: [Tutor] calling modules in different minor versions of Python Message-ID: <1D673F86DDA00841A1216F04D1CE70D646FB6EABDB@EXCH2.nws.oregonstate.edu> Hi all, We work with a python package (ESRI geoprocessor) that only releases their packages tied to specific minor version of Python (e.g. 2.5). We are predominantly working with 2.6, but have Python 2.5 installed as well. When we want to call modules that use the geoprocessor package, we are using subprocess.call from 2.6: subprocess.call('C:/Python25/Python spam.py ') where spam.py is a module that uses the geoprocessor and are the arguments to pass. Apart from moving our code base to 2.5, is there a better way to handle this that doesn't require a separate subprocess call? thanks, matt From alan.gauld at btinternet.com Tue Nov 22 20:20:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Nov 2011 19:20:06 +0000 Subject: [Tutor] write list of tuples to file (beginner) In-Reply-To: References: Message-ID: On 22/11/11 18:50, Mayo Adams wrote: > for item in tuplelist > outputfile.write (item) > > doesn't work, and I suppose I scarcely expect it should, but I am at a > loss to find out how to do it. You need to convert the tuple to a string. And you need to add a newline at the end. A simple way is: for item in tuplelist outputfile.write (str(item) + '\n') But the formatting may not be exactly as you'd like. In that case write your own string convertor, call it tuple2string or something and use it like for item in tuplelist outputfile.write (tuple2string(item) ) Of course, if you ever want to read the data back you'll need a corresponding string2tuple() function that unpicks your formatting back to a tuple... HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cranky.frankie at gmail.com Tue Nov 22 20:25:12 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 22 Nov 2011 14:25:12 -0500 Subject: [Tutor] basic class loading question In-Reply-To: <4ECBEE98.7050004@davea.name> References: <4ECBA60A.3080609@davea.name> <4ECBCD1B.7020405@davea.name> <4ECBEE98.7050004@davea.name> Message-ID: Dave thank you for your patience. It really is appreciated. In the interest of closing this thread I'm posting the final version that works, and achieves the goal of showing how to represent data both in a list and in an object: # # Example to show the difference between list data and object data # class Qb: def __init__(self, first_name='', last_name='', phone='', email='', stadium=''): self.first_name = first_name self.last_name = last_name self.phone = phone self.email = email self.stadium = stadium Qb_list = [["Joe", "Montana", "415-123-4567", "joe.montana at gmail.com","Candlestick Park"], ["Fran", "Tarkington","651-321-7657", "frank.tarkington at gmail.com", "Metropolitan Stadidum"], ["Joe", "Namath", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], ["John", "Elway", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], ["Archie", "Manning", "504-888-1234", "archie.manning at gmail.com", "Louisiana Superdome"], ["Roger", "Staubach", "214-765-8989", "roger.staubach at gmail.com", "Cowboy Stadium"]] quarterbacks = [] # Create an empty object list len_Qb_list = len(Qb_list) # Get the lenght of the list of lists which is the # number of rows in the input data for i in range(0, len_Qb_list): # Iterate for the number of rows nq = Qb(*Qb_list[i]) # Create an instance of class Qb called "nq" # and populate each field quarterbacks.append(nq) # Append an instance of object "nq" into object list "quarterbacks" i = i + 1 # Iterate for each row in "Qb_list" print (quarterbacks[3].phone) # Print an item from the object list "quarterbacks" print (Qb_list[3][2]) # Print the same object from the original list of lists -- Frank L. "Cranky Frankie" Palmeri From o0MB0o at hotmail.se Tue Nov 22 20:41:19 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 22 Nov 2011 20:41:19 +0100 Subject: [Tutor] Shorten Code In-Reply-To: References: Message-ID: > Button1 is supposed to represent chair one in the train. >So call it chair_1 or put it in a list called chairs >so that you can access them as chairs[0] or whatever. >But get a name that reflects what its actually used for. Yes, perhaps that is a good way to go. I didn't think about that. > at the top of my email, I am writing a larger program. This program is > supposed to be a GUI online booking program for train tickets. >OK, That's a pity. >A Tkinter program is never going to be an online GUI, it only works on >the desktop. For that you need to use HTML5/Flash/Javascript/Java etc. >And its all a lot more messy. ----------------------------------------------------------------------------- No, I didn't mean that it have to work online. It is just fine if it works on the desktop. I can only imagine how much more complicated things would be then. But if I understood it correctly, with the help and information I got from you in this mail and in your previous mail, I can manage to solve my problems? It is a bit hard right now to understand, because I am unfamiliar with using tuples/lists and data tables. I will do my best to get it to work. >> However, I understand if you don't have time to answer these probably >> stupid and simple questions, I am still grateful for your previous >> answers! >They are neither simple nor stupid, they are very sensible questions and >you are tackling a significant program. Sadly I don't think your >approach will work for an 0nline solution (ie a web based one). I just got my program to work today, but I want to shorten the code using your suggestions in this and your previous email. I still find this hard to do because that way of thinking is completely new to me. I have one of these functions below for each chair. I just want to use one instead of so many functions. That is why I am trying to understand and implement your suggestions. def chair1_clicked(self): """This method runs if chair one is clicked""" def change_chair1_value(): global chair1_value button2_value=not chair1_value chair1_clicked () if chair_value: self.chair1.configure(bg="yellow") text_file=open("Hamburg_Dortmund20_00","w") text_file.write("Hamburg-Dortmund") text_file.close() def chair_color_red(): global chair1_color chair1_color=("yellow") change_button2_color_red() else: self.chair1.configure(bg="green") os.remove ("Hamburg_Dortmund20_00") def chair1_color_green(): global chair1_color chair_color=("green") chair1_color_green() From alan.gauld at btinternet.com Tue Nov 22 21:43:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 22 Nov 2011 20:43:27 +0000 Subject: [Tutor] Shorten Code In-Reply-To: References: Message-ID: On 22/11/11 19:41, Mic wrote: >> A Tkinter program is never going to be an online GUI, it only works on >> the desktop. For that you need to use HTML5/Flash/Javascript/Java etc. >> And its all a lot more messy. > > No, I didn't mean that it have to work online. It is just fine if it > works on the desktop. OK, So I'll guess you want a desktop program that eventually sends commands to an online service? If so thats a lot easier to do with Tkinter... :-) > > def chair1_clicked(self): > """This method runs if chair one is clicked""" First thing to do is take the variable out of the function name and pass it as a parameter. def chair_clicked(self, chairID): Now you can call that and pass in the actual chair that was clicked as a parameter. (I'm going to assume you went for a list of chairs so the actual value of aChair is the index in the list) > def change_chair1_value(): > global chair1_value > button2_value=not chair1_value You really want to stop using global values. Make them attributes of your class. Life will be much easier! And you won;t need all these little functions cluttering up your code. > if chair_value: Becomes if self.chairs[chairID][0] This assumes you store the value and button as a tuple and value is the first element. So when you create the chairs your code looks like: for ch in ch_data: chairs.append((ch_data[0], Button(self, text=ch_data[1],....) ) > self.chair1.configure(bg="yellow") You are still hard coding the color rather than using your variables > text_file=open("Hamburg_Dortmund20_00","w") > text_file.write("Hamburg-Dortmund") > text_file.close() Hmmm, that looks suspicious. You just created a text file with one line. > def chair_color_red(): > global chair1_color > chair1_color=("yellow") > change_button2_color_red() The function says red but the code says 'yellow'???? Again take the value out of the function name and make it a parameter. def set_chair_color(chairID, col): chairs[chairID][1] = col And now I'm assuming the second value of chairs is the color. Its getting complicated. Maybe time we introduced dictionaries(*).... Then it looks like: def set_chair_color(chairID, col): chairs[chairID]['color'] = col and your initialisation code looks like: for id,ch in enumerate(ch_data): chairs[id] = {'value':0, 'color':'white', 'button' = Button(self, text=ch_data[0],....) ) > self.chair1.configure(bg="green") > os.remove ("Hamburg_Dortmund20_00") And now you delete that file you created without having done anything with it? I suspect this is all a bit much in one go, if so, we can break it down into more manageable chunks. (*)Instead of a dictionary we could have used a class but I think that's a leap too far for you just yet. But this is a project that would be easier using classes and objects. An exercise for the future. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From o0MB0o at hotmail.se Tue Nov 22 22:17:18 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 22 Nov 2011 22:17:18 +0100 Subject: [Tutor] Shortening the code In-Reply-To: References: Message-ID: >OK, So I'll guess you want a desktop program that eventually sends >commands to an online service? >If so thats a lot easier to do with Tkinter... :-) Well, it is enough if the program can run on my desktop. However, there are courses about learning how to make programs like these online, but I feel like that is too hard for me at the moment, right? :) >> text_file=open("Hamburg_Dortmund20_00","w") >> text_file.write("Hamburg-Dortmund") >> text_file.close() >Hmmm, that looks suspicious. You just created a text file with one line. I thought I should make it as simple as possible when posting here? If you would have liked me to I can paste all the information I store in the file, but it would have been a lot of lines then, which would had been unnecessary? >> def chair_color_red(): >> global chair1_color >> chair1_color=("yellow") >> change_button2_color_red() >The function says red but the code says 'yellow'???? My bad. It is supposed the be red there. >> self.chair1.configure(bg="green") >> os.remove ("Hamburg_Dortmund20_00") >And now you delete that file you created without having >done anything with it? The meaning is that when the button is pressed once, it changes color and creates the file. That means you have booked the chair. If you click the button once more, the button removes the file, and changes color to green which indicates that you have un booked your chair. I hope you understand now why I delete the file :) (*)Instead of a dictionary we could have used a class but I think that's a leap too far for you just yet. But this is a project that would be easier using classes and objects. An exercise for the future. I have made simple programs with classes before. I know how to use these instance variables (correct name in english?) and how to create objects of the class, but nothing more. >I suspect this is all a bit much in one go, if so, we can break it down into more manageable chunks. Yes, it feels like a lot to take in at once, but tomorrow I will try your suggestions for a couple of hours and hopefully get it to work. If I fail at that, perhaps we could "break it down into more manageable chunks". Thanks for your help once again! Mic From beachkidken at gmail.com Wed Nov 23 01:14:53 2011 From: beachkidken at gmail.com (Ken G.) Date: Tue, 22 Nov 2011 19:14:53 -0500 Subject: [Tutor] File vs. Database (possible off topic) In-Reply-To: <4ECBA007.50205@pearwood.info> References: <4ECAEBD9.10504@gmail.com> <4ECBA007.50205@pearwood.info> Message-ID: <4ECC3AFD.7090509@gmail.com> On 11/22/2011 08:13 AM, Steven D'Aprano wrote: > Ken G. wrote: >> It occurred to me last week while reviewing the files I made in using >> Python, it could be somewhat similar to a database. >> >> What would be a different between a Python files and Python >> databases? Granted, the access in creating them are different, I >> really don't see any different in the format of a file and a database. > > A database is essentially a powerful managed service built on top of > one or more files. There's nothing you can do with a database that you > can't do with a big set of (say) Windows-style INI files and a whole > lot of code to manage them. A database does all the management for > you, handling all the complexity, data integrity, and security, so > that you don't have to re-invent the wheel. Since database software > tends to be big and complicated, there is a lot of wheel to be > re-invented. > I wish to thank those whom replied to my previous question regarding database vs. file. The responses received was quite useful and helpful. Ken From g.nius.ck at gmail.com Wed Nov 23 01:19:31 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Tue, 22 Nov 2011 19:19:31 -0500 Subject: [Tutor] Quacks like an object In-Reply-To: References: Message-ID: > > You want to persist data changes to a file? Thats easy enough. Yes, but I want it built in to the objects built in methods like for example doing *listquacker[3]="This string needs to be updated immediately**."* Should write the new data to a file. It should also work for all data types, not just list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Wed Nov 23 01:22:27 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Tue, 22 Nov 2011 19:22:27 -0500 Subject: [Tutor] Physics Engine Message-ID: Does anyone know a good physics engine that works with livewires, or a good reference on how to build 2-D physic engines (preferably the former.) It needs to work well with rope objects. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Wed Nov 23 01:37:38 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Wed, 23 Nov 2011 00:37:38 +0000 Subject: [Tutor] Physics Engine In-Reply-To: References: Message-ID: <1093041269-1322008662-cardhu_decombobulator_blackberry.rim.net-203678148-@b28.c28.bise6.blackberry> I think python- ogre has a physics engine? Its 3d though Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Christopher King Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Tue, 22 Nov 2011 19:22:27 To: python mail list Subject: [Tutor] Physics Engine _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From pasokan at talentsprint.com Wed Nov 23 04:49:46 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Wed, 23 Nov 2011 09:19:46 +0530 Subject: [Tutor] Shortening the code In-Reply-To: References: Message-ID: On Wed, Nov 23, 2011 at 2:47 AM, Mic wrote: > [LOTS OF STUFF SNIPPED] >>> self.chair1.configure(bg="green") >>> os.remove ("Hamburg_Dortmund20_00") > >> And now you delete that file you created without having >> done anything with it? > > The meaning is that when the button is pressed once, ?it changes color and > creates the file. That means you have > booked the chair. If you click the button once more, the button removes the > file, and changes color to green > which indicates that you have un booked your chair. I hope you understand > now why I delete the file :) Often if you [name things]/[write code] in terms of WHAT you want to do, rather than HOW you want to do, you will find the going easier For example, a function that is named *bookChair(chairId)*, inside which you change color to green or whatever is worth considering. HTH Asokan Pichai From ckava1 at msn.com Wed Nov 23 05:15:49 2011 From: ckava1 at msn.com (Chris Kavanagh) Date: Tue, 22 Nov 2011 23:15:49 -0500 Subject: [Tutor] Variables (with lists??) Message-ID: I was going over one of Derek Banas' tutorials on youtube, and came across something I hadn't seen before. A variable with a list beside it (see code below). He sets the variable, customer , equal to a dict. Then uses the variable with ['firstname'],['lastname'], ect. I've never seen this in my short programming life. What is this called? And is there any documentation on it?? I tried to google it, but had no idea what to google, lol. The code below is just partial code. . . Thanks for the help, and I hope everyone has a happy Thanksgiving! customer = {} print ?Add a new customer to the database\n? custNum = raw_input(?Enter a customer number: ?) customer['firstName'] = raw_input(?Customer First Name: ?) customer['lastName'] = raw_input(?Customer Last Name: ?) customer['streetAdd'] = raw_input(?Customer Street Address: ?) customer['city'] = raw_input(?Customer City: ?) customer['state'] = raw_input(?Customer State: ?) customer['zip'] = raw_input(?Customer Zip Code: ?) From andreas.perstinger at gmx.net Wed Nov 23 06:56:15 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Wed, 23 Nov 2011 06:56:15 +0100 Subject: [Tutor] Variables (with lists??) In-Reply-To: References: Message-ID: <4ECC8AFF.40008@gmx.net> On 2011-11-23 05:15, Chris Kavanagh wrote: > I was going over one of Derek Banas' tutorials on youtube, and came > across something I hadn't seen before. A variable with a list beside it > (see code below). He sets the variable, customer , equal to a dict. Then > uses the variable with ['firstname'],['lastname'], ect. I've never seen > this in my short programming life. What is this called? That's the Python syntax to indexing dictionary keys (comparable to the index of lists, tuples, ...) In general, you set a value with dictionary[key] = value where "key" can be any immutable type (strings, numbers, tuples if they just contain strings, numbers and other tuples) and "value" anything you want to save for that key. To get the value of a key, just use dictionary[key] Example: >>> customer = {} >>> customer["name"] = "Chris" >>> customer["name"] 'Chris' > And is there any documentation on it?? The tutorial on dictionaries: http://docs.python.org/tutorial/datastructures.html#dictionaries The library reference on dictionaries: http://docs.python.org/library/stdtypes.html#mapping-types-dict Bye, Andreas From delegbede at dudupay.com Wed Nov 23 07:14:58 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Wed, 23 Nov 2011 06:14:58 +0000 Subject: [Tutor] Variables (with lists??) In-Reply-To: References: Message-ID: <158253468-1322028895-cardhu_decombobulator_blackberry.rim.net-1877497555-@b18.c12.bise7.blackberry> Hi Chris, Straight to the point, this is how to populate a python dictionary. customer = {} This statement makes a new dictionary, which is empty though, called customer. A python dictionary has a pair of key and value linked with semicolon and seperated from other pairs by a comma. print ?Add a new customer to the database\n? custNum = raw_input(?Enter a customer number: ?) This expects an input from the user and then sets that to the variable custName. Here is a thing to note here, whatever the user enters is treated as a string because of raw_input. That's another lesson as a whole. What's in the parenthesis would be shown at the prompt when the program is run. It tells the user what to do. customer['firstName'] = raw_input(?Customer First Name: ?) This creates a pair of key value in a dictionary. Initially, the dictionary customer was empty. This statement now creates a key 'firstname' that has the value of whatever is entered by the user as the Customer First Name. customer['lastName'] = raw_input(?Customer Last Name: ?) The same explanation for the above explains this and the rest all through the customer['zip'] = raw_input(?Customer Zip Code: ?) You can also look at what others would say. While searching google, search, creating python dictionary. HTH. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Chris Kavanagh Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Tue, 22 Nov 2011 23:15:49 To: Subject: [Tutor] Variables (with lists??) I was going over one of Derek Banas' tutorials on youtube, and came across something I hadn't seen before. A variable with a list beside it (see code below). He sets the variable, customer , equal to a dict. Then uses the variable with ['firstname'],['lastname'], ect. I've never seen this in my short programming life. What is this called? And is there any documentation on it?? I tried to google it, but had no idea what to google, lol. The code below is just partial code. . . Thanks for the help, and I hope everyone has a happy Thanksgiving! customer = {} print ?Add a new customer to the database\n? custNum = raw_input(?Enter a customer number: ?) customer['firstName'] = raw_input(?Customer First Name: ?) customer['lastName'] = raw_input(?Customer Last Name: ?) customer['streetAdd'] = raw_input(?Customer Street Address: ?) customer['city'] = raw_input(?Customer City: ?) customer['state'] = raw_input(?Customer State: ?) customer['zip'] = raw_input(?Customer Zip Code: ?) _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From cranky.frankie at gmail.com Wed Nov 23 14:04:48 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 23 Nov 2011 08:04:48 -0500 Subject: [Tutor] Python 3 dictionary questions Message-ID: In playing around with Pyton 3 dictionaries I've come up with 2 questions 1) How are duplicate keys handled? For example: Qb_Dict = {"Montana": ["Joe", "Montana", "415-123-4567", "joe.montana at gmail.com","Candlestick Park"], "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com", "Metropolitan Stadidum"], "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com", "Louisiana Superdome"], "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com", "Cowboy Stadium"]} print(Qb_Dict["Elway"],"\n") # print a dictionary entry In the above the "wrong" Elway entry, the second one, where the first name is Ed, is getting printed. I just added that second Elway row to see how it would handle duplicates and the results are interesting, to say the least. 2) Is there a way to print out the actual value of the key, like Montana would be 0, Tarkington would be 1, etc? -- Frank L. "Cranky Frankie" Palmeri From bgailer at gmail.com Wed Nov 23 14:27:14 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 23 Nov 2011 08:27:14 -0500 Subject: [Tutor] Python 3 dictionary questions In-Reply-To: References: Message-ID: <4ECCF4B2.6010108@gmail.com> On 11/23/2011 8:04 AM, Cranky Frankie wrote: > In playing around with Pyton 3 dictionaries I've come up with 2 questions > > 1) How are duplicate keys handled? For example: > > Qb_Dict = {"Montana": ["Joe", "Montana", "415-123-4567", > "joe.montana at gmail.com","Candlestick Park"], > "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com", > "Metropolitan Stadidum"], > "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], > "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], > "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile High > Stadium"], > "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com", > "Louisiana Superdome"], > "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com", > "Cowboy Stadium"]} > > print(Qb_Dict["Elway"],"\n") # print a dictionary entry > > In the above the "wrong" Elway entry, the second one, where the first > name is Ed, is getting printed. I just added that second Elway row to > see how it would handle duplicates and the results are interesting, to > say the least. Seems like you answered your first question. Dictionaries do not have duplicate keys. Your 2nd assignment using the key "Elway" replaced the first. > > 2) Is there a way to print out the actual value of the key, like > Montana would be 0, Tarkington would be 1, etc? Actual value? The actual value of Montana" is "Montana". Sounds like you want the index of the entry as though it were in a list. Dictionaries are not ordered so you can't get that unless you store it as part of the value. -- Bob Gailer 919-636-4239 Chapel Hill NC From cwitts at compuscan.co.za Wed Nov 23 14:27:42 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 23 Nov 2011 15:27:42 +0200 Subject: [Tutor] Python 3 dictionary questions In-Reply-To: References: Message-ID: <4ECCF4CE.9030409@compuscan.co.za> On 2011/11/23 03:04 PM, Cranky Frankie wrote: > In playing around with Pyton 3 dictionaries I've come up with 2 questions > > 1) How are duplicate keys handled? For example: > > Qb_Dict = {"Montana": ["Joe", "Montana", "415-123-4567", > "joe.montana at gmail.com","Candlestick Park"], > "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com", > "Metropolitan Stadidum"], > "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], > "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], > "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile High > Stadium"], > "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com", > "Louisiana Superdome"], > "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com", > "Cowboy Stadium"]} > > print(Qb_Dict["Elway"],"\n") # print a dictionary entry > > In the above the "wrong" Elway entry, the second one, where the first > name is Ed, is getting printed. I just added that second Elway row to > see how it would handle duplicates and the results are interesting, to > say the least. > > 2) Is there a way to print out the actual value of the key, like > Montana would be 0, Tarkington would be 1, etc? > A dictionary is simply a Key:Value store and keys are unique. You're overwriting your first "Elway" entry with the second one when it's being "captured". If you want to keep duplicate "key" values you'll need to re-look at what data structure you want to use, you can keep using a dictionary but then you'll need to change the value side of it perhaps like `{key: {key: value, key: value}}` so you end up with `{'Elway': {'John': [tel_num, email, home_ground], 'Ed': [tel_num, email, home_ground]}}` or some other implementation specific to your requirements. As for your second question, the value of the key is a hash. So to get the value, you'll need to find what hashing algorithm is used by default for dictionaries and use that to get the value of it yourself. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Nov 23 14:30:25 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 23 Nov 2011 07:30:25 -0600 Subject: [Tutor] Python 3 dictionary questions In-Reply-To: References: Message-ID: On Wed, Nov 23, 2011 at 7:04 AM, Cranky Frankie wrote: > In playing around with Pyton 3 dictionaries I've come up with 2 questions > > 1) How are duplicate keys handled? For example: > > Qb_Dict = {"Montana": ["Joe", "Montana", "415-123-4567", > "joe.montana at gmail.com","Candlestick Park"], > "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com", > "Metropolitan Stadidum"], > "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], > "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High > Stadium"], > "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile High > Stadium"], > "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com", > "Louisiana Superdome"], > "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com", > "Cowboy Stadium"]} > > print(Qb_Dict["Elway"],"\n") # print a dictionary > entry > > In the above the "wrong" Elway entry, the second one, where the first > name is Ed, is getting printed. I just added that second Elway row to > see how it would handle duplicates and the results are interesting, to > say the least. > > 2) Is there a way to print out the actual value of the key, like > Montana would be 0, Tarkington would be 1, etc? I'm not sure about #1, but I can tell you about #2. Dictionaries are not ordered, so you have absolutely no guarantee which order they'll appear in when you print them out, or if you iterate over the dictionary. If you want to maintain some type of order you have a few options. First, store the keys in a list, which does maintain order: keys = ['Elway', 'Montana', ... ] Then you would do something like: Qb_Dict[keys[0]] (As a slight aside, I'll direct you to PEP 8 which is the Python style guide which contains things like naming conventions. If you want your code to look Pythonic, you should take a look there.) If you just want them to be sorted, you can run sorted on the keys() collection from the dictionary: for key in sorted(Qb_Dict.keys()): print(Qb_Dict[key]) In Python 3 this will only work if your collection contains comparable types - if you have {1:'Hello', 'Goodbye':2} then you'll get a TypeError when it tries to compare 1 and 'Goodbye' HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Nov 23 14:32:38 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Nov 2011 14:32:38 +0100 Subject: [Tutor] Python 3 dictionary questions References: Message-ID: Cranky Frankie wrote: > In playing around with Pyton 3 dictionaries I've come up with 2 questions > > 1) How are duplicate keys handled? For example: > > Qb_Dict = {"Montana": ["Joe", "Montana", "415-123-4567", > "joe.montana at gmail.com","Candlestick Park"], > "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com", > "Metropolitan Stadidum"], > "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], > "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High > Stadium"], "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile > High Stadium"], > "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com", > "Louisiana Superdome"], > "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com", > "Cowboy Stadium"]} > > print(Qb_Dict["Elway"],"\n") # print a dictionary > entry > > In the above the "wrong" Elway entry, the second one, where the first > name is Ed, is getting printed. I just added that second Elway row to > see how it would handle duplicates and the results are interesting, to > say the least. The last one always wins. Perhaps it becomes clearer if you think of d = {1:1, 1:2} as syntactic sugar for d = dict() d[1] = 1 d[1] = 2 If you want to allow for multiple values per key use a list as the value and append to that: >>> d = {} >>> for k, v in [(1, 1), (2, 2), (1, 3)]: ... d.setdefault(k, []).append(v) ... >>> d {1: [1, 3], 2: [2]} > 2) Is there a way to print out the actual value of the key, like > Montana would be 0, Tarkington would be 1, etc? No, the actual key *is* "Montana" or "Tarkington". The dictionary does not record the insertion order. There is a collections.OrderedDict, but I recommend that you don't try out that until you have grokked the builtin dict. As a rule of thumb there are less usecases for an OrderedDict than you think ;) From cranky.frankie at gmail.com Wed Nov 23 15:45:33 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 23 Nov 2011 09:45:33 -0500 Subject: [Tutor] sensing EOF in Python 3.1 Message-ID: I'm reading in a pickled file. The program works but I'm having trouble sensing end of file. Here's the program: # # pickle_in.py # program to read in a pickled file # # Frank L. Palmeri # import pickle # import the pickle module pickle_file = open("d:/Work/pickle_file", "rb") # open the pickled input file read_file = pickle.load(pickle_file) # read the first input record new_list=[] # create a new empty list while pickle_file: # loop until end of file for i in range(0, 4): # iterate for each field new_list.append(read_file[i]) # append each field to the new list i = i + 1 # increment loop counter print(new_list) # print the input record from the new list new_list=[] # initialize the new list for the next record read_file = pickle.load(pickle_file) # read the next record in the input file here's the error: Traceback (most recent call last): File "D:\MyDocs\Python\pickle_in.py", line 21, in read_file = pickle.load(pickle_file) # read the next record in the input file File "D:\Python31\lib\pickle.py", line 1365, in load encoding=encoding, errors=errors).load() EOFError -- Frank L. "Cranky Frankie" Palmeri From o0MB0o at hotmail.se Wed Nov 23 16:35:13 2011 From: o0MB0o at hotmail.se (Mic) Date: Wed, 23 Nov 2011 16:35:13 +0100 Subject: [Tutor] How to shorten this code using classes? In-Reply-To: References: Message-ID: Hi. I have written a simple GUI program. It works just like it is intended to do, but there is a problem, I feel like I could make it shorter. I thought of using classes instead of doing it the way I have done. Here is my code: from tkinter import* button1_color="green" button1_value=False button2_color="green" button2_value=False class Window(Frame): def __init__(self,master): super (Window,self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): #Creates hello button1 self.hello_bttn1=Button(self,bg=button1_color, text="Hi_1", command=self.button1_clicked) self.hello_bttn1.grid() #Creates hello button2 self.hello_bttn2=Button(self,bg=button2_color, text="Hi_1", command=self.button2_clicked) self.hello_bttn2.grid() def button1_clicked(self): """ This method runs if button one is clicked""" def change_button1_value(): global button1_value button1_value=not button1_value change_button1_value() if button1_value: self.hello_bttn1.configure(bg="red", text="Hi_2") def change_button1_color_red(): global button1_color button1_color=("red") change_button1_color_red() else: self.hello_bttn1.configure(bg="green", text="Hi_1") def change_button1_color_green(): global button1_color button1_color=("green") change_button1_color_green() #------------------------------------------------- def button2_clicked(self): """This method runs if button two is clicked""" def change_button2_value(): global button2_value button2_value=not button2_value change_button2_value() if button2_value: self.hello_bttn2.configure(bg="red", text="Hi_2") def change_button2_color_red(): global button2_color button2_color=("red") change_button2_color_red() else: self.hello_bttn2.configure(text="Hi_1", bg="green") def change_button2_color_green(): global button2_color button2_color=("green") change_button2_color_green() As you can button1_clicked and button2_clicked are very similiar. Imagine that I would use more buttons than just the two that I am using now. It would be a lot of functions then, one for each button. How do I accomplish the same thing as my code does now, but using one function for all buttons instead of one function for each button? Is it possible? I hope these questions aren't stupid. Thank you for your time! Mic root=Tk() root.title("Test") root.geometry("200x200") app=Window(root) root.mainloop() From __peter__ at web.de Wed Nov 23 16:36:54 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Nov 2011 16:36:54 +0100 Subject: [Tutor] sensing EOF in Python 3.1 References: Message-ID: Cranky Frankie wrote: > I'm reading in a pickled file. The program works but I'm having > trouble sensing end of file. Here's the program: > > # > # pickle_in.py > # program to read in a pickled file > # > # Frank L. Palmeri > # > > import pickle # import the pickle module > pickle_file = open("d:/Work/pickle_file", "rb") # open the pickled input > file > > read_file = pickle.load(pickle_file) # read the first input > record > > new_list=[] # create a new empty list > > while pickle_file: # loop until end of file > for i in range(0, 4): # iterate for each field > new_list.append(read_file[i]) # append each field to > the new list > i = i + 1 # increment loop counter > print(new_list) # print the input > record from the new list > new_list=[] # initialize the new > list for the next record > read_file = pickle.load(pickle_file) # read the next record > in the input file > > > here's the error: > > Traceback (most recent call last): > File "D:\MyDocs\Python\pickle_in.py", line 21, in > read_file = pickle.load(pickle_file) # read the next record > in the input file > File "D:\Python31\lib\pickle.py", line 1365, in load > encoding=encoding, errors=errors).load() > EOFError How did you write the data into the pickle file? The normal approach is to write all your data in one step, e. g. (all code snippets untested) # write list with open(filename, "wb") as out: pickle.dump(list_of_records, out) You can then read back all records with # read list with open(filename, "rb") as instream: list_of_records = pickle.load(instream) A second approach is also possible, but not appropriate for a newbie: # write list entries with open(filename, "wb") as out: for record in list_of_records: pickle.dump(record, out) # read list entries to rebuild the list list_of_records = [] with open(filename, "rb") as instream: while True: try: record = pickle.load(instream) except EOFError: break else: list_of_records.append(record) By the way > new_list=[] > for i in range(0, 4): > new_list.append(read_file[i]) > i = i + 1 - Here the for-loop is taking care of the value of i, you don't have to increment it manually. - A simpler way to achieve the same is new_list = read_file[:4] From g.nius.ck at gmail.com Wed Nov 23 16:37:27 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Wed, 23 Nov 2011 10:37:27 -0500 Subject: [Tutor] Physics Engine In-Reply-To: <1093041269-1322008662-cardhu_decombobulator_blackberry.rim.net-203678148-@b28.c28.bise6.blackberry> References: <1093041269-1322008662-cardhu_decombobulator_blackberry.rim.net-203678148-@b28.c28.bise6.blackberry> Message-ID: I'm more of a beginner, so it would be nice for it to work with Livewires. It doesn't need to be that complex (no need for air pressure, elasticity, or energy.) I just need enough that I will stay on the ground and that when I swing sprites around on a rope, they swing in a circle, not a square. A good reference for making one would be good to. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Nov 23 17:34:07 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 23 Nov 2011 17:34:07 +0100 Subject: [Tutor] How to shorten this code using classes? References: Message-ID: Mic wrote: > Hi. > I have written a simple GUI program. It works just like it is intended to > do, but there > is a problem, I feel like I could make it shorter. I thought of using > classes instead of > doing it the way I have done. > > Here is my code: > > from tkinter import* > > button1_color="green" > button1_value=False > > button2_color="green" > button2_value=False > > > class Window(Frame): > def __init__(self,master): > super (Window,self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > > #Creates hello button1 > self.hello_bttn1=Button(self,bg=button1_color, text="Hi_1", > command=self.button1_clicked) > self.hello_bttn1.grid() > > #Creates hello button2 > self.hello_bttn2=Button(self,bg=button2_color, text="Hi_1", > command=self.button2_clicked) > self.hello_bttn2.grid() > > > > def button1_clicked(self): > """ This method runs if button one is clicked""" > > def change_button1_value(): > global button1_value > button1_value=not button1_value > > change_button1_value() > > if button1_value: > > self.hello_bttn1.configure(bg="red", text="Hi_2") > > def change_button1_color_red(): > global button1_color > button1_color=("red") > change_button1_color_red() > > else: > self.hello_bttn1.configure(bg="green", text="Hi_1") > > def change_button1_color_green(): > global button1_color > button1_color=("green") > change_button1_color_green() > > #------------------------------------------------- > > def button2_clicked(self): > """This method runs if button two is clicked""" > > def change_button2_value(): > global button2_value > button2_value=not button2_value > > change_button2_value() > > if button2_value: > > self.hello_bttn2.configure(bg="red", text="Hi_2") > > def change_button2_color_red(): > global button2_color > button2_color=("red") > change_button2_color_red() > > else: > self.hello_bttn2.configure(text="Hi_1", bg="green") > > def change_button2_color_green(): > global button2_color > button2_color=("green") > change_button2_color_green() > root=Tk() > root.title("Test") > root.geometry("200x200") > app=Window(root) > root.mainloop() > As you can button1_clicked and button2_clicked are very similiar. Imagine > that I would use more buttons than just the two that I am using now. > > It would be a lot of functions then, one for each button. How do I > accomplish > the same thing as my code does now, but using one function for all buttons > instead of one function for each button? Is it possible? I chose to ignore the "using classes" part. If you like you can turn the button_clicked() function into a method of a subclass of Button. You can also move the Button configuration done in create_widgets() into the __init__() method of that subclass. import tkinter as tk from functools import partial def button_clicked(button): if button["bg"] == "green": button.configure(bg="red", text="Hi 2") else: button.configure(bg="green", text="Hi 1") class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for _ in range(2): button = tk.Button(self) command = partial(button_clicked, button) button["command"] = command button.grid() command() root = tk.Tk() root.title("Test") root.geometry("200x200") app = Window(root) root.mainloop() From eire1130 at gmail.com Wed Nov 23 18:09:14 2011 From: eire1130 at gmail.com (James Reynolds) Date: Wed, 23 Nov 2011 12:09:14 -0500 Subject: [Tutor] How to shorten this code using classes? In-Reply-To: References: Message-ID: On Wed, Nov 23, 2011 at 10:35 AM, Mic wrote: > Hi. > I have written a simple GUI program. It works just like it is intended to > do, but there > is a problem, I feel like I could make it shorter. I thought of using > classes instead of > doing it the way I have done. > > Here is my code: > > from tkinter import* > > button1_color="green" > button1_value=False > > button2_color="green" > button2_value=False > > > class Window(Frame): > def __init__(self,master): > super (Window,self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > > #Creates hello button1 > self.hello_bttn1=Button(self,**bg=button1_color, text="Hi_1", > command=self.button1_clicked) > self.hello_bttn1.grid() > > #Creates hello button2 > self.hello_bttn2=Button(self,**bg=button2_color, text="Hi_1", > command=self.button2_clicked) > self.hello_bttn2.grid() > > > > def button1_clicked(self): > """ This method runs if button one is clicked""" > > def change_button1_value(): > global button1_value > button1_value=not button1_value > > change_button1_value() > > if button1_value: > > self.hello_bttn1.configure(bg=**"red", text="Hi_2") > > def change_button1_color_red(): > global button1_color > button1_color=("red") > change_button1_color_red() > > > > > else: > self.hello_bttn1.configure(bg=**"green", text="Hi_1") > > > > > def change_button1_color_green(): > global button1_color > button1_color=("green") > change_button1_color_green() > > #-----------------------------**-------------------- > > def button2_clicked(self): > """This method runs if button two is clicked""" > > def change_button2_value(): > global button2_value > button2_value=not button2_value > > change_button2_value() > > if button2_value: > > self.hello_bttn2.configure(bg=**"red", text="Hi_2") > > > > def change_button2_color_red(): > global button2_color > button2_color=("red") > change_button2_color_red() > > > > > else: > self.hello_bttn2.configure(**text="Hi_1", bg="green") > > > > > def change_button2_color_green(): > global button2_color > button2_color=("green") > change_button2_color_green() > > > > > As you can button1_clicked and button2_clicked are very similiar. Imagine > that I would use more buttons than just the two that I am using now. > > It would be a lot of functions then, one for each button. How do I > accomplish > the same thing as my code does now, but using one function for all buttons > instead of one function for each button? Is it possible? > > I hope these questions aren't stupid. > > Thank you for your time! > > > Mic > > > > > > > > > > > > > > > root=Tk() > root.title("Test") > root.geometry("200x200") > app=Window(root) > root.mainloop() > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Button 1 and Button 2 already are classes, so unless you need to subclass, you are simply being redundant. A couple things first: don't use globals all over the place unless you want to have a serious headache. You have a wicked about of redundancy in your code, you don't need an object oriented approach to condense, but it can be helpful at times. However, as far as your question. For the two functions, you could subclass Button and add them to your new Button object: (untested) class MyButton(Button): button_color="green" button_value=False def __init__(self, *args, **kwargs): super(Button, self).__init__(*args, **kwargs) def change_value_and_color(self): self.button_value = not self.button_value if self.button_value: self.button_color="red" self.configure(bg=self.button_color, text="Hi_2") else: self.button_color="green" self.hello_bttn1.configure(bg=self.button_value, text="Hi_1") def button_clicked(self): """ This method runs if button one is clicked""" self.change_value_and_color() I left in the button_clicked method, but as you can see it is utterly pointless to have it. Just rename your first function and call it directly. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Wed Nov 23 19:03:22 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 23 Nov 2011 13:03:22 -0500 Subject: [Tutor] sensing EOF in Python 3.1 Message-ID: From: Peter Otten <__peter__ at web.de> wrote: snip <> Thanks Peter, that was it. I was treating pickle like standard file i/o when it's not that at all. The reason why I'm "pickling" is I'm trying to include information on Python data structures in the presentaton I'm preparing. Here are the two programs that now work correctly together: import pickle pickle_file = open("d:/Work/pickle_file", "wb") Qb_dict = {"Montana": ["Joe", "Montana", "415-123-4567", "joe.montana at gmail.com","Candlestick Park"], "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com", "Metropolitan Stadidum"], "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com", "Louisiana Superdome"], "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com", "Cowboy Stadium"]} pickle.dump(Qb_dict, pickle_file) pickle_file.close() # # pickle_in.py # program to read in a pickled file # # Frank L. Palmeri # import pickle # import the pickle module pickle_file = open("d:/Work/pickle_file", "rb") # open the pickled file read_list = pickle.load(pickle_file) # read the first pickled row print(read_list) # print the input row from the pickled file pickle_file.close() # close the pickled file -- Frank L. "Cranky Frankie" Palmeri From kliateni at gmail.com Wed Nov 23 19:04:54 2011 From: kliateni at gmail.com (Karim) Date: Wed, 23 Nov 2011 19:04:54 +0100 Subject: [Tutor] Template class and class design on concrete example xl2csv writer Message-ID: <4ECD35C6.4070306@gmail.com> Hello All, I have the following code and I am quite satisfied with its design BUT I have the feeling I can do better. Basically the, main() execute the program (I did not put the parsing of arguments function). I am opening an Excel document and writing content in a CSV one w/ different format. The design is an abstract template class XLWriter, and derived 'Xl2Csv', 'Xl2Scsv', 'Xl2text' classes to write the correct ASCII DOCUMENT to correct format. The property hook method file_format is implement in these classes and return an object of type 'XlCsvFileFormat' or 'XlTabFileFormat'. It allows to put the right file extension and delimiter. These class are derived from standard csv.excel and csv.excel_tab. At last a Factory class MakeXlWriter has the job to create the correct writer. For now I did not add a strategy pattern which usually goes with the Template pattern. Except from that all better design or others critics will be welcome. Regards karim _______________________________________________________________________________________________________________________________________ from __future__ import print_function import sys, os, argparse, csv, xlrd __all__ = ['main', 'Xl2CsvError', 'XLWriter', 'XlCsvFileFormat', 'XlTabFileFormat', 'Xl2Csv', 'Xl2Scsv', 'Xl2text', 'MakeXlWriter'] class Xl2CsvError(Exception): """The exception class to manage the internal program errors.""" pass class XlWriter(object): """Abstract template class.""" def __init__(self, xlfilename=None, sheets=None): """Initializer.""" if self.__class__.__name__ == 'XlWriter': raise TypeError('Abstract template Class XlWriter could not be instanciated directly!') if not xlfilename: raise Xl2CsvError('Please provide a non empty file name!') else: self._source_name = xlfilename self._book = xlrd.open_workbook(xlfilename) if sheets is not None: if isinstance(sheets[0], int): self._selected_sheets = [self._book.sheet_by_index(sheetnum-1) for sheetnum in sheets] elif isinstance(sheets[0], str): try: self._selected_sheets = [self._book.sheet_by_name(sheetname) for sheetname in sheets] except xlrd.biffh.XLRDError, e: print('{0} in file document {1}'.format(e, xlfilename)) sys.exit(1) else: raise Xl2CsvError('Sheets element type not recognized!') else: self._selected_sheets = self._book.sheets() def write(self): """The file extraction public method.""" for sheet in self._selected_sheets: xlfilename = '{sheet}{ext}'.format(sheet=sheet.name, ext='.'+self.file_format.extension.lower()) try: writer = csv.writer(open(xlfilename, 'wb'), delimiter=self.file_format.delimiter) print("Creating csv file '{file}' for sheet '{sheet}' contained in document {src} ...".format( sheet=sheet.name, file=xlfilename, src=self._source_name), end=' ') for row in xrange(sheet.nrows): writer.writerow(sheet.row_values(row)) print('Done.') except csv.Error, e: print(e) return 1 return 0 @property def file_format(self): """Hook method. Need to implement in derived classes. Should return an XLAsciiFileFormat object to get file extension and inner delimiter. """ pass class XlCsvFileFormat(csv.excel): """Add file extension to the usual properties of Excel-generated CSV files.""" extension = 'CSV' class XlTabFileFormat(csv.excel_tab): """Add file extension to the usual properties of Excel-generated delimited files.""" extension = 'TXT' class Xl2Csv(XlWriter): @property def file_format(self): """Hook factory method""" return XlCsvFileFormat() class Xl2Scsv(XlWriter): @property def file_format(self): """Hook factory method""" _format = XlCsvFileFormat() _format.extension = 'SCSV' _format.delimiter = ';' return _format class Xl2Text(XlWriter): @property def file_format(self): """Hook factory method""" return XlTabFileFormat() class MakeXlWriter(object): """Factory class for XLWriter objects. """ @staticmethod def make(xlfilename=None, sheets=None, extension='CSV'): if extension == "TXT": return Xl2Text(xlfilename=xlfilename, sheets=sheets) elif extension == "SCSV": return Xl2Scsv(xlfilename=xlfilename, sheets=sheets) elif extension == "CSV": return Xl2Csv(xlfilename=xlfilename, sheets=sheets) def main(): """Main of this application""" args = _process_command_line() args.xl.close() writer = MakeXlWriter.make(xlfilename=args.xl.name, sheets=args.sheets, extension=args.ext) return writer.write() ___________________________________________________________________________________________________________________________ From waynejwerner at gmail.com Wed Nov 23 19:43:36 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 23 Nov 2011 12:43:36 -0600 Subject: [Tutor] sensing EOF in Python 3.1 In-Reply-To: References: Message-ID: On Wed, Nov 23, 2011 at 12:03 PM, Cranky Frankie wrote: > [...] > The reason why I'm "pickling" is I'm trying to include information on > Python data structures in the presentaton I'm preparing. [...] > In your context why not just use modules? # data.py Qb_dict = {"Montana": ["Joe", "Montana", "415-123-4567", "joe.montana at gmail.com","Candlestick Park"], "Tarkington": ["Fran", "651-321-7657", "frank.tarkington at gmail.com", "Metropolitan Stadidum"], "Namath": ["Joe", "212-222-7777", "joe.namath at gmail.com", "Shea Stadium"], "Elway": ["John", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], "Elway": ["Ed", "303-9876-333", "john.elway at gmai.com", "Mile High Stadium"], "Manning": ["Archie","504-888-1234", "archie.manning at gmail.com", "Louisiana Superdome"], "Staubach": ["Roger","214-765-8989", "roger.staubach at gmail.com", "Cowboy Stadium"]} # program.py from data import Qb_dict print(Qb_dict) Then you can put whatever comments or data you want. Just make sure that you don't name your data.py file the same as something built-in. It's pretty horrible when you try to 'import random' and it doesn't randint() or anything else that you're looking for. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Nov 23 20:17:30 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 23 Nov 2011 11:17:30 -0800 Subject: [Tutor] basic class loading question In-Reply-To: References: <4ECBA60A.3080609@davea.name> <4ECBCD1B.7020405@davea.name> <4ECBEE98.7050004@davea.name> Message-ID: On 11/22/2011 11:25 AM Cranky Frankie said... > quarterbacks = [] # Create an empty object list In the interest of preferred techniques, your loop will be more pythonic when you write this part... > > len_Qb_list = len(Qb_list) # Get the lenght of the list of > lists which is the > # number of rows in the input data > > for i in range(0, len_Qb_list): # Iterate for the number of rows > > nq = Qb(*Qb_list[i]) # Create an instance of class Qb called "nq" > # and populate each field > quarterbacks.append(nq) # Append an instance of object > "nq" into object list "quarterbacks" > i = i + 1 # Iterate for each row in "Qb_list" ...like this... for this_qb in Qb_list: # Iterate over Qb_list quarterbacks.append(Qb(*this_qb)) # append Qb instance to quarterbacks ...or even drop the quarterbacks declaration above... quarterbacks = [Qb(*this_qb) for this_qb in Qb_list Emile > > print (quarterbacks[3].phone) # Print an item from the object > list "quarterbacks" > print (Qb_list[3][2]) # Print the same object from the > original list of lists > > > > From o0MB0o at hotmail.se Wed Nov 23 21:38:18 2011 From: o0MB0o at hotmail.se (Mic) Date: Wed, 23 Nov 2011 21:38:18 +0100 Subject: [Tutor] How to shorten this code using classes? In-Reply-To: References: Message-ID: >I chose to ignore the "using classes" part. If you like you can turn the >button_clicked() function into a method of a subclass of Button. You can >also move the Button configuration done in create_widgets() into the >__init__() method of that subclass. import tkinter as tk from functools import partial def button_clicked(button): if button["bg"] == "green": button.configure(bg="red", text="Hi 2") else: button.configure(bg="green", text="Hi 1") class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for _ in range(2): button = tk.Button(self) command = partial(button_clicked, button) button["command"] = command button.grid() command() root = tk.Tk() root.title("Test") root.geometry("200x200") app = Window(root) root.mainloop() ___________________________________________________________ A very elegant solution. Much better than my previous one. However, I am a bit unfamiliar with your way of coding, I assume you are used to a version other than Python 3.2? Because, never before have I seen either of those import tkinter as tk from functools import partial I also wonder, if I implement your solution, is there anyway I can place the buttons in the program as I would like, or will they be played in a straight, vertical row always? Also, assume that I have a already have a window with a button in it. If you press this button, this window is supposed to open. So, if I press the button, will this window open? Because I created the previous window using from tkinter import* and not import tkinter as tk. I hope my English is understandable, because it is not my primary language. Thanks for your help, it is greatly appreciated! From steve at pearwood.info Wed Nov 23 23:02:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Nov 2011 09:02:04 +1100 Subject: [Tutor] sensing EOF in Python 3.1 In-Reply-To: References: Message-ID: <4ECD6D5C.3060403@pearwood.info> Cranky Frankie wrote: > I'm reading in a pickled file. The program works but I'm having > trouble sensing end of file. Here's the program: [...] > Traceback (most recent call last): > File "D:\MyDocs\Python\pickle_in.py", line 21, in > read_file = pickle.load(pickle_file) # read the next record > in the input file > File "D:\Python31\lib\pickle.py", line 1365, in load > encoding=encoding, errors=errors).load() > EOFError Seems to me that you have successfully found the end of file. I'm not be facetious here. "Easier to ask forgiveness afterwards than permission before hand" is generally (but not necessarily always) the preferred way of coding things in Python. So instead of trying to predict the end of file ahead of time: while some_hard_to_calculate_condition(): do_stuff_with_pickle() you can catch the error instead: try: while True: # Loop forever, until interrupted do_stuff_with_pickle() except EOFError: # no more pickles, so we must be done pass -- Steven From steve at pearwood.info Wed Nov 23 23:44:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 24 Nov 2011 09:44:23 +1100 Subject: [Tutor] sensing EOF in Python 3.1 In-Reply-To: References: Message-ID: <4ECD7747.9020401@pearwood.info> Cranky Frankie wrote: > From: Peter Otten <__peter__ at web.de> wrote: > snip > < write all your data in one step, e. g. (all code snippets untested)>> > > Thanks Peter, that was it. I was treating pickle like standard file > i/o when it's not that at all. I don't understand what you mean by this. Pickle does standard file I/O in the same way that opening a JPEG in an image view does standard file I/O: both programs read data from a file the standard, ordinary way, but expect data of a certain format. If you provide it too little data, you will get an EOF error. If you provide too much data, or messed up data, then you will some other error. But the file I/O is exactly the same. It's just that pickle, or your image viewer, handle it for you. > The reason why I'm "pickling" is I'm trying to include information on > Python data structures in the presentaton I'm preparing. Pickling won't tell you anything about Python data structures. Pickling takes Python data structures, bashes them with a hammer until they stop wiggling, then runs them through a serialiser turning them into a stream of text or binary codes. Pickles tell you only about pickles. You won't learn anything about (say) dicts by looking at a pickled dict except the bare fact that dicts can be pickled. py> import pickle py> d = {"key": "value", "another key": 42} py> pickle.dumps(d) "(dp0\nS'another key'\np1\nI42\nsS'key'\np2\nS'value'\np3\ns." I don't know what you expect to learn about dicts from that. > Here are the two programs that now work correctly together: > > import pickle > pickle_file = open("d:/Work/pickle_file", "wb") > > Qb_dict = { ... contents of dict skipped ... } > pickle.dump(Qb_dict, pickle_file) > pickle_file.close() Take note that you are pickling a dict. This is important later on. > # > # pickle_in.py > # program to read in a pickled file > # > # Frank L. Palmeri > # > > import pickle # import the pickle module Really? Wow! I thought "import pickle" meant sort the database!!! *wink* Sarcasm aside, what else could "import pickle" mean other than import the pickle module? The comment adds absolutely nothing to the code. At best it is superfluous. At worst it is harmful, because code and comments have a regrettable tendency to get out of sync. Every comment should carry its weight. If the code is particularly convoluted, you might write comments explaining *how* you do something, but generally the code speaks for itself regarding the how, so comments should explain *why* you do something. If a comment doesn't tell you something that the code doesn't, that you need to know (or at least should know). Otherwise it should be throw out into the back alley for the stray cats to eat. > pickle_file = open("d:/Work/pickle_file", "rb") # open the pickled file > read_list = pickle.load(pickle_file) # read the first pickled row And this is what I'm talking about. It does NOT read the first pickled row. Pickles don't have rows. In this case, you are reading the first and only pickled object, which happens to be a dict. > print(read_list) # print the input row from the pickled file > pickle_file.close() # close the pickled file Every comment in your second file is either unnecessary, or wrong. This is a good example of the need to "comment smart" rather than "comment hard". # Bad: i += 1 # Add one to i. # Good: i += 1 # Adjust i for one-based indexing. -- Steven From __peter__ at web.de Thu Nov 24 12:14:41 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 24 Nov 2011 12:14:41 +0100 Subject: [Tutor] How to shorten this code using classes? References: Message-ID: Mic wrote: >>I chose to ignore the "using classes" part. If you like you can turn the >>button_clicked() function into a method of a subclass of Button. You can >>also move the Button configuration done in create_widgets() into the >>__init__() method of that subclass. > > import tkinter as tk > from functools import partial > > def button_clicked(button): > if button["bg"] == "green": > button.configure(bg="red", text="Hi 2") > else: > button.configure(bg="green", text="Hi 1") > > class Window(tk.Frame): > def __init__(self, master): > super (Window, self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > for _ in range(2): > button = tk.Button(self) > command = partial(button_clicked, button) > button["command"] = command > button.grid() > command() > > root = tk.Tk() > root.title("Test") > root.geometry("200x200") > app = Window(root) > root.mainloop() > A very elegant solution. Much better than my previous one. However, I am a > bit unfamiliar with your way of > coding, I assume you are used to a version other than Python 3.2? Yes, though I don't think the difference between 2.x and 3.x matters here. > Because, never before have I seen either of those Most tkinter tutorials seem to use from tkinter import * which I don't like because it doesn't make explict which names are put into the current module's namespace. The alternative import tkinter leads to long qualified names. > import tkinter as tk is a popular compromise. > from functools import partial I use this kind of explicit import for a few names that I use frequently, namely defaultdict, contextmanager, everything from itertools... I think of these as my personal extended set of builtins ;) As to the actual partial() function, you probably don't see it a lot because it has been in the standard library for only three years. The older idiom for making a function that calls another function with a fixed argument is command = lambda button=button: button_clicked(button) > I also wonder, if I implement your solution, is there anyway I can place > the buttons in the program as I would like, or will they be played in a > straight, vertical row > always? You can iterate over (row, column) pairs instead of the dummy _ variable: def create_widgets(self): for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: button = tk.Button(self) command = partial(button_clicked, button) button["command"] = command button.grid(row=row, column=column) command() > Also, assume that I have a already have a window with a button in it. If > you press this button, this window is supposed to open. > So, if I press the button, will this window open? Because I created the > previous window using > from tkinter import* and not import tkinter as tk. You can make the decision what style you want to use on a per-module basis. In that module you can then access (for example) a tkinter button with either tkinter.Button, tk.Button or just Button. You can even mix styles if you put the respective imports at the beginning of the module (not recommended). What approach you take has no consequences on the execution of the program. > I hope my English is understandable, because it is not my primary > language. Thanks for your help, it is greatly appreciated! Many posters aren't native speakers, so you can never be sure that what you pick up here is actually English ;) I didn't have any problems with your command of the language, but I'm not a native speaker either. From karim.meiborg at googlemail.com Tue Nov 22 18:13:02 2011 From: karim.meiborg at googlemail.com (Karim Meiborg) Date: Tue, 22 Nov 2011 18:13:02 +0100 Subject: [Tutor] basic class loading question References: <4ECBA60A.3080609@davea.name> Message-ID: Cranky Frankie wrote: > OK, but this is still not working: > > class Qb: > def __init__(self, first_name='', last_name='', phone='', > email='', stadium=''): > self.first_name = first_name > self.last_name = last_name > self.phone = phone > self.email = email > self.stadium = stadium > > > > Qb_list = [["Joe", "Montana", "415-123-4567", > "joe.montana at gmail.com","Candlestick Park"], > ["Fran", "Tarkington","651-321-7657", > "frank.tarkington at gmail.com", "Metropolitan Stadidum"], > ["Joe", "Namath", "212-222-7777", "joe.namath at gmail.com", "Shea > [Stadium"], "John", "Elway", "303-9876-333", "john.elway at gmai.com", > ["Mile > High Stadium"], > ["Archie", "Manning", "504-888-1234", "archie.manning at gmail.com", > "Louisiana Superdome"], > ["Roger", "Staubach", "214-765-8989", "roger.staubach at gmail.com", > "Cowboy Stadium"]] > > > > len_Qb_list = len(Qb_list) > > for i in range(0, len_Qb_list): > quarterbacks = Qb(*Qb_list[i]) > i = i + 1 > > print(quarterbacks.last_name(2)) > > > > Hi, this is my first post in this group so hopefully I don't mess up. I think your real problem here is the for-loop and not the class instantiation itself. Below is the minimally modified working version of your code: len_Qb_list = len(Qb_list) for i in range(0, len_Qb_list): quarterbacks = Qb(*Qb_list[i]) print(quarterbacks.last_name) Have a look at the differences: - The for-loop itself increments i, you don't have to do it yourself - The printed expression is different: quarterbacks.last_name(2) implies a function call, whereas quarterbacks.last_name refers to an attribute - The indentation was modified by me to print every last name. With your indentation only the last last name would be printed. Since I'm not sure what you want to accomplish this may be wrong for you. Here is a somewhat nicer version, which does exactly the same: quarterbacks = [Qb(*quarterback) for quarterback in Qb_list] for quarterback in quarterbacks: print(quarterback.last_name) It is easier to read (at least in my opinion) and less typing too. If you'd like to understand the syntax, i'd recommend you to look up "list comprehension" in your book of choice. This would be the minimal version of code to print out all the last names(at least at my level of understanding): [print(Qb(*quarterback).last_name) for quarterback in Qb_list] I hope this helps. I'm new to python, so please take my advice with a grain of salt. Cheers From o0MB0o at hotmail.se Thu Nov 24 17:20:48 2011 From: o0MB0o at hotmail.se (Mic) Date: Thu, 24 Nov 2011 17:20:48 +0100 Subject: [Tutor] Shortening the code of a finsihed program. In-Reply-To: References: Message-ID: Good afternoon! I have previously asked questions about how I can shorten my code. I have recieved a lot of good answers, but there is one thing that never works. I can never implement the suggestions into my code, and that is my fault. I have in my previous questions only asked how to shorten certain parts of a larger program. And while the suggestions have managed to solve these problems. I can't never get it to work when in my real program. So I figured that instead of asking questions about how I can shorten certain parts of my programs, and then try to put these parts togheter into a large program, I decided to post my entire program. It is already fullfilling its purpose, but I want to make the code a lot shorter. The program is supposed to be an online ticket booking system. To book a chair, click on a green chair. It then turns red, which means that you have booked the chair. if you wish to unbook your chair, press the red button once. It will then turn green, which means that you have unbooked your ticket, and the chair is now bookable again. If the button is red, a file is being created with information about the chair. If the buttons turns green, the file is removed, which means that your ticket is unbooked. Hopefully, you will get a better overlook of what I am trying to achieve. I apologize if my English is flawed, but I hope it is understandable. Also, I have translated the entire program into English from my own languge. Thanks a lot your help and time! #Program translated into English. #Importing necessary modules. from tkinter import* import os chair1_color="green" chair1_value=False chair2_color="green" chair2_value=False #Creates the Main Menu Window. class Main_Menu_Window(Frame): def __init__(self,master): super(Main_Menu_Window,self).__init__(master) self.grid() self.create_mainmenu_widgets() #Creates the widgets in the window. def create_mainmenu_widgets(self): self.instructions=Label(self, text="Welcome to our online booking system") self.instructions.grid() self.to_booking_window=Button(self, text="Book/Unbook your ticket", command=self.book_unbookmode) self.to_booking_window.grid() self.exit_program=Button(self, text="Exit Program", command=self.exit_program) self.exit_program.grid() #Creates a method that quits the program if the user presses the button "Exit Program" def exit_program(self): root.destroy() #Creates a new window where you book your tickets if you press the button "Book/Unbook your ticket". def book_unbookmode(self): class BookOrUnbookTicketWindow(Frame): def __init__(self,master): super(BookOrUnbookTicketWindow,self).__init__(master) self.grid() self.create_book_unbookmode_widgets() #Creates widgets to place in the BookOrUnBookTicketWindow. def create_book_unbookmode_widgets(self): self.instructions_bookticket=Label(self, text="""To book a chair, click on a green chair. It then turns red, which means that you have booked the chair. if you wish to unbook your chair, press the red button once. It will then turn green, which means that you have unbooked your ticket, and the chair is now bookable again.""") self.instructions_bookticket.grid() #Creates two chairs. It should be more, but this is just used as an example. To get more chairs, this code in the section below #this comment will need to be shortened somehow, otherwise the code would be way too long. self.chair1=Button(self, bg=chair1_color, text="01", command=self.chair1_clicked) self.chair1.grid() self.chair2=Button(self, bg=chair2_color, text="02", command=self.chair2_clicked) self.chair2.grid() def chair1_clicked(self): """ This method runs if chair one is clicked""" def change_chair1_value(): global chair1_value chair1_value=not chair1_value change_chair1_value() if chair1_value: self.chair1.configure(bg="Red") text_file=open("New_York_Canada_15_00_Chair1","w") text_file.write( "New York-Canada\nSeat:1")#Notice that I want the Seat number written into the #textfile should be 1, if you press chair one, #2 if you press chair 2, 3 if you press chair 3 and so on. #However, the text should be "New York-Canada should # be the same for all chairs. text_file.close() def change_chair1_color_red(): global chair1_color chair1_color=("red") change_chair1_color_red() else: self.chair1.configure(bg="green") os.remove ("New_York_Canada_15_00_Chair1") #The file is supposed to be removed because #it means that you have unbooked your ticket. def change_chair1_color_green(): global chair1_color chair1_color=("green") change_chair1_color_green() #------------------------------------------------- def chair2_clicked(self): """ Ths method runs if chair two is clicked""" def change_chair2_value(): global chair2_value chair2_value=not chair2_value change_chair2_value() if chair2_value: self.chair2.configure(bg="Red") text_file=open("New_York_Canada_15_00_Chair2","w")#The file name should end with 1 if chair one is pressed. #if chair2 is pressed, it should end with chair2. If chair three is #pressed it should end with chair3, and so on. The start of the filname #"New_York_Canada_15_00_ should be the same for all chairs. text_file.write( "New York-Canada\nSeat:2")#Notice that I want the Seat number written into the #textfile should be 1, if you press chair one, #2 if you press chair 2, 3 if you press chair 3 and so on. #However, the text should be "New York-Canada should # be the same for all chairs. text_file.close() def change_chair2_color_red(): global chair2_color chair2_color=("red") change_chair2_color_red() else: self.chair2.configure(bg="green") os.remove ("New_York_Canada_15_00_Chair2") #The file is supposed to be removed because #it means that you have unbooked your ticket. def change_chair2_color_green(): global chair2_color chair2_color=("green") change_chair2_color_green #------------------------------------------------- #As seen above, the two functions are very similiar. I have no #idea how to make this code shorter and more elegant. The program #is already fullfilling its purpose. But instead of writing a function #for each chair I want to solve it somehow. root=Tk() root.title("Book/Unbooking Mode") root.geometry("800x800") app=BookOrUnbookTicketWindow(root) root.mainloop() root=Tk() root.title("Online Booking System") root.geometry("200x200") app=Main_Menu_Window(root) root.mainloop() From alan.gauld at btinternet.com Fri Nov 25 01:37:09 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Nov 2011 00:37:09 +0000 Subject: [Tutor] How to shorten this code using classes? In-Reply-To: References: Message-ID: On 23/11/11 17:09, James Reynolds wrote: > However, as far as your question. For the two functions, you could > subclass Button and add them to your new Button object: > > (untested) > > > class MyButton(Button): > button_color="green" > button_value=False But I'd move these into __init__() since otherwise all buttons will have the same color/value. Usually we want to change color/value of each button independently. Also the button_ bit is redundant because they are now attributes of a Button, so we don;t need to repeat that in the name. > def __init__(self, *args, **kwargs): > super(Button, self).__init__(*args, **kwargs) self.color="green" self.value=False So this becomes: > def change_value_and_color(self): > self.button_value = not self.button_value self.value = not self.value > if self.button_value: if self.value: > self.button_color="red" self.color="red" > self.configure(bg=self.button_color, text="Hi_2") > self.configure(bg=self.color, text="Hi_2") > else: > self.button_color="green" self.color="green" > self.hello_bttn1.configure(bg=self.button_value, text="Hi_1") > self.configure(bg=self.color, text="Hi_2") But notice both self.configure lines are identical (assuming the second is not really supposed to be setting the background to value...)so we can pull them out of the if/else and add them after: self.configure(bg=self.button_color, text="Hi_2") > def button_clicked(self): > """ This method runs if button one is clicked""" > self.change_value_and_color() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Nov 25 02:01:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Nov 2011 01:01:05 +0000 Subject: [Tutor] Shortening the code of a finsihed program. In-Reply-To: References: Message-ID: On 24/11/11 16:20, Mic wrote: > and then try to put these parts togheter into a large program, I decided > to post my entire program. Its usually better to paste long programs into a pastebin web site and give us a link. This saves cluttering up people mail with long messages, and also the pastebin rendering will usually be easier to read with syntax coloring etc. > achieve. I apologize if my English is flawed, but I hope it is > understandable. Your English is excellent and no barrier to understanding what you are trying to do. > #Importing necessary modules. > from tkinter import* > import os > > chair1_color="green" > chair1_value=False > > chair2_color="green" > chair2_value=False You already got some help on how to avoid these global variables by creating a subclass of Button. These then become two attributes of the new ChairButton class > #Creates the Main Menu Window. > class Main_Menu_Window(Frame): > def __init__(self,master): > super(Main_Menu_Window,self).__init__(master) > self.grid() > self.create_mainmenu_widgets() > > #Creates the widgets in the window. > def create_mainmenu_widgets(self): > > self.instructions=Label(self, text="Welcome to our online booking system") > self.instructions.grid() > > self.to_booking_window=Button(self, text="Book/Unbook your ticket", > command=self.book_unbookmode) > self.to_booking_window.grid() > > self.exit_program=Button(self, text="Exit Program", > command=self.exit_program) > self.exit_program.grid() > > #Creates a method that quits the program if the user presses the button > "Exit Program" > def exit_program(self): > root.destroy() > > #Creates a new window where you book your tickets if you press the > # button "Book/Unbook your ticket". > def book_unbookmode(self): > class BookOrUnbookTicketWindow(Frame): While its perfectly legal Python to create a class inside a method its very unusual in practice and very restricting in the use of the class. Its nearly always better to declare all your classes at the top level of the program. > def __init__(self,master): > super(BookOrUnbookTicketWindow,self).__init__(master) > self.grid() > self.create_book_unbookmode_widgets() > > #Creates widgets to place in the BookOrUnBookTicketWindow. > def create_book_unbookmode_widgets(self): > self.instructions_bookticket=Label(self, text="""To book a chair, click > on a green chair. It then turns red, which means that you have booked > the chair. > if you wish to unbook your chair, press the red button once. It will > then turn green, which means that you have unbooked > your ticket, and the chair is now bookable again.""") > self.instructions_bookticket.grid() > > #Creates two chairs. It should be more, but this is just used as an > example. To get more chairs, this code in the section below > #this comment will need to be shortened somehow, otherwise the code > would be way too long. Because you post lost all the formatting, I'm not sure where this code is supposed to sit... This is again where a pastebin would help. > self.chair1=Button(self, bg=chair1_color, text="01", > command=self.chair1_clicked) > self.chair1.grid() > > self.chair2=Button(self, bg=chair2_color, text="02", > command=self.chair2_clicked) > self.chair2.grid() > > def chair1_clicked(self): > """ This method runs if chair one is clicked""" > > def change_chair1_value(): > global chair1_value > chair1_value=not chair1_value And this is repeating all the bad habits from your original posts. If you adopt the ChairButton class approach all of this becomes much clearer and simpler. > change_chair1_value() > > if chair1_value: > > self.chair1.configure(bg="Red") > text_file=open("New_York_Canada_15_00_Chair1","w") > text_file.write( "New York-Canada\nSeat:1")#Notice that I want the Seat > number written into the > #textfile should be 1, if you press chair one, > #2 if you press chair 2, 3 if you press chair 3 and so on. > #However, the text should be "New York-Canada should > # be the same for all chairs. > text_file.close() > > def change_chair1_color_red(): > global chair1_color > chair1_color=("red") > change_chair1_color_red() > > > > > else: > self.chair1.configure(bg="green") > os.remove ("New_York_Canada_15_00_Chair1") > #The file is supposed to be removed because > #it means that you have unbooked your ticket. > > > > > def change_chair1_color_green(): > global chair1_color > chair1_color=("green") > change_chair1_color_green() > > > #------------------------------------------------- > def chair2_clicked(self): > """ Ths method runs if chair two is clicked""" > > def change_chair2_value(): > global chair2_value > chair2_value=not chair2_value > > change_chair2_value() > > if chair2_value: > > self.chair2.configure(bg="Red") > text_file=open("New_York_Canada_15_00_Chair2","w")#The file name should > end with 1 if chair one is pressed. > #if chair2 is pressed, it should end with chair2. If chair three is > #pressed it should end with chair3, and so on. The start of the filname > #"New_York_Canada_15_00_ should be the same for all chairs. > > text_file.write( "New York-Canada\nSeat:2")#Notice that I want the Seat > number written into the > #textfile should be 1, if you press chair one, > #2 if you press chair 2, 3 if you press chair 3 and so on. > #However, the text should be "New York-Canada should > # be the same for all chairs. > text_file.close() > > def change_chair2_color_red(): > global chair2_color > chair2_color=("red") > change_chair2_color_red() > > else: > self.chair2.configure(bg="green") > os.remove ("New_York_Canada_15_00_Chair2") > #The file is supposed to be removed because > #it means that you have unbooked your ticket. > > def change_chair2_color_green(): > global chair2_color > chair2_color=("green") > change_chair2_color_green > #------------------------------------------------- > #As seen above, the two functions are very similiar. I have no > #idea how to make this code shorter and more elegant. The program > #is already fullfilling its purpose. But instead of writing a function > #for each chair I want to solve it somehow. Use the ChairButton technique from the earlier thread. def ChairButton(Button): def __init__(self, *args, **kwargs): self.value = False self.color = "green" super.... etc... > root=Tk() > root.title("Book/Unbooking Mode") > root.geometry("800x800") > app=BookOrUnbookTicketWindow(root) > root.mainloop() > > root=Tk() You should only ever have one Tk() object in a Tkinter program. If you need two windows open at the same time you should either make one a child of the other and launch the second from the firsts initialiser. Or make one a subclass of TopLevel rather than Frame > root.title("Online Booking System") > root.geometry("200x200") > app=Main_Menu_Window(root) > root.mainloop() And again you should only have one mainloop running, otherwise things would get very confusing with events winding up in the wrong windows event queue etc. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Fri Nov 25 09:41:52 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 25 Nov 2011 16:41:52 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys Message-ID: >>> pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str(k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, From steve at pearwood.info Fri Nov 25 10:06:13 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Nov 2011 20:06:13 +1100 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: Message-ID: <4ECF5A85.4040901@pearwood.info> lina wrote: >>>> pairs > {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} > > > such as here ('66', '69') and ('69', '66') is one key, > > I wanna keep only one and add the value of those two keys, above is a > very simple example: Which one do you want to keep? If the order ('66', '69') is unimportant, you should use a frozenset instead of a tuple. In your code, where you set the pairs in the first place, instead of doing: pair = ('66', '69') # however you build the pair pairs[pair] = value (or how ever you set the initial values), change it to this: pair = frozenset(('66', '69')) pairs[pair] = pairs.get(pair, 0) + value -- Steven From cwitts at compuscan.co.za Fri Nov 25 10:05:23 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 25 Nov 2011 11:05:23 +0200 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: Message-ID: <4ECF5A53.4080209@compuscan.co.za> On 2011/11/25 10:41 AM, lina wrote: >>>> pairs > {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} > > > such as here ('66', '69') and ('69', '66') is one key, > > I wanna keep only one and add the value of those two keys, above is a > very simple example: > > here is the (failed) code: > > for k, v in pairs.items(): > if str(k)[1]+str(k)[0] in pairs.keys(): > print(pairs[str(k)[1]+str(k)[0]]) > pairs[k]+=pairs[str(k)[1]+str(k)[0]] > del pairs[str(k)[1]+str(k)[0]] > print(v,k) > > > Thanks for any advice, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > pairs.items() is fine if it's a small dictionary but for larger ones it's going to slow things down as it generates the entire list of items before you continue, rather use .iteritems() as it creates an iterator which only yields one item at a time making it more efficient. str(k)[1]+str(k)[0] is string concatenation so your first key tested is '6669' and not ('66', '69') as you intended, you would have to create a new tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. Also, your check to "in pairs.keys()" is wasteful as you generate a new list of keys for every key and you will be better off using `in pairs:` directly as it performs a dictionary lookup to test if the key exists. With that in mind, this is how I would re-write that code segment. YMMV for key in pairs.iterkeys(): # The [::-1] creates a reverse of the iterable so ('66', '69') will be ('69', '66') if key[::-1] in pairs: try: # The first instance of the pair gets kept and the reversed gets added pairs[key] += pairs[key[::-1]] del pairs[::-1] except KeyError: print "Key ('%s', '%s') already accumulated)" % key Hope that helps. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Nov 25 10:15:25 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 25 Nov 2011 17:15:25 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: <4ECF5A53.4080209@compuscan.co.za> References: <4ECF5A53.4080209@compuscan.co.za> Message-ID: On Fri, Nov 25, 2011 at 5:05 PM, Christian Witts wrote: > On 2011/11/25 10:41 AM, lina wrote: > > pairs > > {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} > > > such as here ('66', '69') and ('69', '66') is one key, > > I wanna keep only one and add the value of those two keys, above is a > very simple example: > > here is the (failed) code: > > for k, v in pairs.items(): > if str(k)[1]+str(k)[0] in pairs.keys(): > print(pairs[str(k)[1]+str(k)[0]]) > pairs[k]+=pairs[str(k)[1]+str( > k)[0]] > del pairs[str(k)[1]+str(k)[0]] > print(v,k) > > > Thanks for any advice, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > pairs.items() is fine if it's a small dictionary but for larger ones it's > going to slow things down as it generates the entire list of items before > you continue, rather use .iteritems() as it creates an iterator which only > yields one item at a time making it more efficient. > > str(k)[1]+str(k)[0] is string concatenation so your first key tested is > '6669' and not ('66', '69') as you intended, you would have to create a new > tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. > Also, your check to "in pairs.keys()" is wasteful as you generate a new list > of keys for every key and you will be better off using `in pairs:` directly > as it performs a dictionary lookup to test if the key exists. > > With that in mind, this is how I would re-write that code segment. YMMV > > for key in pairs.iterkeys(): > ??? # The [::-1] creates a reverse of the iterable so ('66', '69') will be > ('69', '66') $ python3 dehydron_data_stastic.py | sort -nr Traceback (most recent call last): File "dehydron_data_stastic.py", line 44, in for k in pairs.iterkeys(): AttributeError: 'dict' object has no attribute 'iterkeys' > ??? if key[::-1] in pairs: > ??????? try: > ??????????? # The first instance of the pair gets kept and the reversed gets > added > ??????????? pairs[key] += pairs[key[::-1]] > ??????????? del pairs[::-1] > ??????? except KeyError: > ??????????? print "Key ('%s', '%s') already accumulated)" % key > > Hope that helps. > > -- > > Christian Witts > Python Developer > From stm.at.oc at googlemail.com Fri Nov 25 10:16:20 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Fri, 25 Nov 2011 10:16:20 +0100 Subject: [Tutor] Do loop in Python Message-ID: Hi there, I am a new python user. I have a question regarding do loop..... This is a simple program that I have written: ----------------- N=10 h=10.0 # [micrometer] z=-200.0 # [micrometer] num = 0.05 #m**2/s dz = 1.0 nuh=[] tmax=3600 dt=20. nu=[]height = arange(z*dz,0,dz) outfile=open('nu.dat','w') outfile.write('height, nu, nuh') for z,when in enumerate(height): for h in range(10): for N in range(10): for z in range((N-z)+(N-h)): nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) ----------------------- What I like to do with this program is do loop like the fortran version of as follows: do i = 2, N z(i) = z(i-1) +h(i-1) end do write(0,*) 'z ', z(1:N) write(0,*) 'when ', 'nu ','Conc ' do i= 1, N nuh(i)= 0.01d0*exp(-0.005d2*(z(i)+200)) ! turbulence diffusivity m**2/s nu(i)= num(1) + nuh(i) end do ---------- My problem is I am notable have the curve in the output plot as I have as a result of FORTRAN program. What happens is just having a straight line....! the whole problem is in z part, which is supposed to be changed and i do not see it! So, would it be possible to take a look at it please. any suggestion would greatly appreciated. Thank you, Sue From cwitts at compuscan.co.za Fri Nov 25 10:19:27 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 25 Nov 2011 11:19:27 +0200 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: <4ECF5A53.4080209@compuscan.co.za> Message-ID: <4ECF5D9F.7050101@compuscan.co.za> On 2011/11/25 11:15 AM, lina wrote: > On Fri, Nov 25, 2011 at 5:05 PM, Christian Witts wrote: >> On 2011/11/25 10:41 AM, lina wrote: >> >> pairs >> >> {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} >> >> >> such as here ('66', '69') and ('69', '66') is one key, >> >> I wanna keep only one and add the value of those two keys, above is a >> very simple example: >> >> here is the (failed) code: >> >> for k, v in pairs.items(): >> if str(k)[1]+str(k)[0] in pairs.keys(): >> print(pairs[str(k)[1]+str(k)[0]]) >> pairs[k]+=pairs[str(k)[1]+str( >> k)[0]] >> del pairs[str(k)[1]+str(k)[0]] >> print(v,k) >> >> >> Thanks for any advice, >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> pairs.items() is fine if it's a small dictionary but for larger ones it's >> going to slow things down as it generates the entire list of items before >> you continue, rather use .iteritems() as it creates an iterator which only >> yields one item at a time making it more efficient. >> >> str(k)[1]+str(k)[0] is string concatenation so your first key tested is >> '6669' and not ('66', '69') as you intended, you would have to create a new >> tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. >> Also, your check to "in pairs.keys()" is wasteful as you generate a new list >> of keys for every key and you will be better off using `in pairs:` directly >> as it performs a dictionary lookup to test if the key exists. >> >> With that in mind, this is how I would re-write that code segment. YMMV >> >> for key in pairs.iterkeys(): >> # The [::-1] creates a reverse of the iterable so ('66', '69') will be >> ('69', '66') > $ python3 dehydron_data_stastic.py | sort -nr > Traceback (most recent call last): > File "dehydron_data_stastic.py", line 44, in > for k in pairs.iterkeys(): > AttributeError: 'dict' object has no attribute 'iterkeys' > >> if key[::-1] in pairs: >> try: >> # The first instance of the pair gets kept and the reversed gets >> added >> pairs[key] += pairs[key[::-1]] >> del pairs[::-1] >> except KeyError: >> print "Key ('%s', '%s') already accumulated)" % key >> >> Hope that helps. >> >> -- >> >> Christian Witts >> Python Developer >> > Ah, should have mentioned .iterkeys() / .itervalues() are in Python 2.x and .keys() and .values() have been changed in Py3 to match .iter* from Py2.x. Just change that line to `for key in pairs.keys():` then. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Fri Nov 25 10:24:31 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 25 Nov 2011 17:24:31 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: <4ECF5A85.4040901@pearwood.info> References: <4ECF5A85.4040901@pearwood.info> Message-ID: On Fri, Nov 25, 2011 at 5:06 PM, Steven D'Aprano wrote: > lina wrote: >>>>> >>>>> pairs >> >> {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} >> >> >> such as here ('66', '69') and ('69', '66') is one key, >> >> I wanna keep only one and add the value of those two keys, above is a >> very simple example: > > > Which one do you want to keep? > It does not matter, the order is not important, > If the order ('66', '69') is unimportant, you should use a frozenset instead > of a tuple. In your code, where you set the pairs in the first place, > instead of doing: > > pair = ('66', '69') ?# however you build the pair > pairs[pair] = value > > (or how ever you set the initial values), change it to this: > > pair = frozenset(('66', '69')) > pairs[pair] = pairs.get(pair, 0) + value I don't get this "pairs.get" part. pairs[pair]=pairs.get(pair,0)+parts[2] TypeError: unsupported operand type(s) for +: 'int' and 'str' or line in f.readlines(): parts=line.split() #pair=set((parts[0],parts[1])) if (parts[0],parts[1]) not in dehydrons.keys(): dehydrons[(parts[0],parts[1])]=parts[2] occurence[(parts[0],parts[1])]=1 pair=frozenset(('parts[0]','parts[1]')) pairs[pair]=pairs.get(pair,0)+parts[2] else: occurence[(parts[0],parts[1])]+=1 I upload the file in: https://docs.google.com/open?id=0B93SVRfpVVg3NTg5YTkwMGUtMzdiNi00ZGI2LWE5ZGYtMTFmMTc0OTZhMzZl https://docs.google.com/open?id=0B93SVRfpVVg3NGQwZDRhNDMtMDUzZi00NDIxLWE2MDAtZGM0ZWEzZDczYTMz > > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lina.lastname at gmail.com Fri Nov 25 10:29:45 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 25 Nov 2011 17:29:45 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: <4ECF5D9F.7050101@compuscan.co.za> References: <4ECF5A53.4080209@compuscan.co.za> <4ECF5D9F.7050101@compuscan.co.za> Message-ID: On Fri, Nov 25, 2011 at 5:19 PM, Christian Witts wrote: > On 2011/11/25 11:15 AM, lina wrote: > > On Fri, Nov 25, 2011 at 5:05 PM, Christian Witts > wrote: > > On 2011/11/25 10:41 AM, lina wrote: > > pairs > > {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} > > > such as here ('66', '69') and ('69', '66') is one key, > > I wanna keep only one and add the value of those two keys, above is a > very simple example: > > here is the (failed) code: > > for k, v in pairs.items(): > if str(k)[1]+str(k)[0] in pairs.keys(): > print(pairs[str(k)[1]+str(k)[0]]) > pairs[k]+=pairs[str(k)[1]+str( > k)[0]] > del pairs[str(k)[1]+str(k)[0]] > print(v,k) > > > Thanks for any advice, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > pairs.items() is fine if it's a small dictionary but for larger ones it's > going to slow things down as it generates the entire list of items before > you continue, rather use .iteritems() as it creates an iterator which only > yields one item at a time making it more efficient. > > str(k)[1]+str(k)[0] is string concatenation so your first key tested is > '6669' and not ('66', '69') as you intended, you would have to create a new > tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. > Also, your check to "in pairs.keys()" is wasteful as you generate a new list > of keys for every key and you will be better off using `in pairs:` directly > as it performs a dictionary lookup to test if the key exists. > > With that in mind, this is how I would re-write that code segment. YMMV > > for key in pairs.iterkeys(): > ??? # The [::-1] creates a reverse of the iterable so ('66', '69') will be > ('69', '66') > > $ python3 dehydron_data_stastic.py | sort -nr > Traceback (most recent call last): > File "dehydron_data_stastic.py", line 44, in > for k in pairs.iterkeys(): > AttributeError: 'dict' object has no attribute 'iterkeys' > > ??? if key[::-1] in pairs: > ??????? try: > ??????????? # The first instance of the pair gets kept and the reversed gets > added > ??????????? pairs[key] += pairs[key[::-1]] > ??????????? del pairs[::-1] > ??????? except KeyError: > ??????????? print "Key ('%s', '%s') already accumulated)" % key > > Hope that helps. > > -- > > Christian Witts > Python Developer > > > Ah, should have mentioned .iterkeys() / .itervalues() are in Python 2.x and > .keys() and .values() have been changed in Py3 to match .iter* from Py2.x. > > Just change that line to `for key in pairs.keys():` then. for key in pairs.keys(): if key[::-1] in pairs: pairs[key] += pairs[key[::-1]] del pairs[key[::-1]] print(pairs) Traceback (most recent call last): File "dehydron_data_stastic.py", line 47, in for key in pairs.keys(): RuntimeError: dictionary changed size during iteration > -- > > Christian Witts > Python Developer > From lina.lastname at gmail.com Fri Nov 25 10:34:25 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 25 Nov 2011 17:34:25 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: <4ECF5A53.4080209@compuscan.co.za> <4ECF5D9F.7050101@compuscan.co.za> Message-ID: #!/usr/bin/python3 dehydrons={} pairs={} #frozen set way pairs fs_pairs={} occurence={} total=0 dictionary={} candidate_dehydron={} if __name__=="__main__": with open("dehydron_refined_data_18.txt","r") as f: for line in f.readlines(): parts=line.split() #pair=set((parts[0],parts[1])) if (parts[0],parts[1]) not in dehydrons.keys(): dehydrons[(parts[0],parts[1])]=parts[2] occurence[(parts[0],parts[1])]=1 #pair=frozenset(('parts[0]','parts[1]')) #pairs[pair]=pairs.get(pair,0)+parts[2] else: occurence[(parts[0],parts[1])]+=1 #for k, v in dehydrons.items(): #print(k,v) for k, v in occurence.items(): if v>=25: #print(v,k) candidate_dehydron[k]=v #print("{:.2f}".format(v/2768*100),k) total+=v print(total) for k, v in candidate_dehydron.items(): pairs[k] = v '''for key in pairs.keys(): if key[::-1] in pairs: pairs[key] += pairs[key[::-1]] del pairs[key[::-1]] print(pairs)''' #for k, v in pairs.items(): #print(v,k) I attached the not working code, Thanks for any advice, best regards, From charleshbecker at gmail.com Fri Nov 25 10:41:09 2011 From: charleshbecker at gmail.com (Charles Becker) Date: Fri, 25 Nov 2011 02:41:09 -0700 Subject: [Tutor] Do loop in Python In-Reply-To: References: Message-ID: <479DBBDE-417F-46C1-83F7-6D1F175747D4@gmail.com> Sue, I'm not familiar with FORTRAN, and since I'm not completely sure what you're trying to accomplish please take this simply as an 'educated guess'. My guess is that you're not getting the curve because Z is only defined to one decimal location (1/10th) precision and probably needs higher precision (and is likely getting it) in the FORTRAN version. http://docs.python.org/tutorial/floatingpoint.html this should help Charles Sent from my iPhone On Nov 25, 2011, at 2:16 AM, stm atoc wrote: > Hi there, > > I am a new python user. > I have a question regarding do loop..... > > This is a simple program that I have written: > > ----------------- > N=10 > h=10.0 # [micrometer] > z=-200.0 # [micrometer] > num = 0.05 #m**2/s > dz = 1.0 > nuh=[] > tmax=3600 > dt=20. > nu=[]height = arange(z*dz,0,dz) > > outfile=open('nu.dat','w') > outfile.write('height, nu, nuh') > > for z,when in enumerate(height): > for h in range(10): > for N in range(10): > for z in range((N-z)+(N-h)): > > nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence > diffusivity m**2/s > nu.append(num + nuh[z]) > > ----------------------- > What I like to do with this program is do loop like the fortran > version of as follows: > > do i = 2, N > z(i) = z(i-1) +h(i-1) > > end do > > write(0,*) 'z ', z(1:N) > write(0,*) 'when ', 'nu ','Conc ' > > > do i= 1, N > > nuh(i)= 0.01d0*exp(-0.005d2*(z(i)+200)) ! turbulence diffusivity m**2/s > nu(i)= num(1) + nuh(i) > > > end do > > ---------- > My problem is I am notable have the curve in the output plot as I have > as a result of FORTRAN program. What happens is just having a > straight line....! > the whole problem is in z part, which is supposed to be changed and i > do not see it! > > So, would it be possible to take a look at it please. any suggestion > would greatly appreciated. > > Thank you, > Sue > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From lina.lastname at gmail.com Fri Nov 25 10:50:20 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 25 Nov 2011 17:50:20 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: <4ECF5A53.4080209@compuscan.co.za> <4ECF5D9F.7050101@compuscan.co.za> Message-ID: for key, value in pairs.items(): if key[::-1] in pairs.keys() and pairs[key] != 0: pairs[key] += pairs[key[::-1]] pairs[key[::-1]]=0 for k, v in pairs.items(): if v != 0: print(v,k) Now very trivial, but works. On Fri, Nov 25, 2011 at 5:34 PM, lina wrote: > #!/usr/bin/python3 > > dehydrons={} > pairs={} > #frozen set way pairs > fs_pairs={} > occurence={} > total=0 > dictionary={} > candidate_dehydron={} > > > if __name__=="__main__": > > ? ?with open("dehydron_refined_data_18.txt","r") as f: > ? ? ? ?for line in f.readlines(): > ? ? ? ? ? ?parts=line.split() > ? ? ? ? ? ?#pair=set((parts[0],parts[1])) > ? ? ? ? ? ?if (parts[0],parts[1]) not in dehydrons.keys(): > ? ? ? ? ? ? ? ?dehydrons[(parts[0],parts[1])]=parts[2] > ? ? ? ? ? ? ? ?occurence[(parts[0],parts[1])]=1 > ? ? ? ? ? ? ? ?#pair=frozenset(('parts[0]','parts[1]')) > ? ? ? ? ? ? ? ?#pairs[pair]=pairs.get(pair,0)+parts[2] > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?occurence[(parts[0],parts[1])]+=1 > ? ? ? ? ? ?#for k, v in dehydrons.items(): > ? ? ? ? ? ?#print(k,v) > > > ? ? ? ?for k, v in occurence.items(): > ? ? ? ? ? ?if v>=25: > ? ? ? ? ? ? ? ?#print(v,k) > ? ? ? ? ? ? ? ?candidate_dehydron[k]=v > ? ? ? ? ? ?#print("{:.2f}".format(v/2768*100),k) > ? ? ? ? ? ?total+=v > ? ? ? ?print(total) > > ? ? ? ?for k, v in candidate_dehydron.items(): > ? ? ? ? ? ?pairs[k] = v > > > ? ? ? ?'''for key in pairs.keys(): > ? ? ? ? ? ?if key[::-1] in pairs: > ? ? ? ? ? ? ? ?pairs[key] += pairs[key[::-1]] > ? ? ? ? ? ? ? ?del pairs[key[::-1]] > ? ? ? ? ? ?print(pairs)''' > > > ? ? ? ?#for k, v in pairs.items(): > ? ? ? ? ? ?#print(v,k) > > > > ? ? ? ? ? ?I attached the not working code, ?Thanks for any advice, > > > best regards, > From stm.at.oc at googlemail.com Fri Nov 25 12:13:44 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Fri, 25 Nov 2011 12:13:44 +0100 Subject: [Tutor] Do loop in Python In-Reply-To: References: Message-ID: regarding to the last email: what I am trying to do is seeing the variation of 'nu' over (changes of) 'z'. My concern is how to arrange this! Basically, I am not able to define the variation of nu by z ( 1 to 200). I am looking for a statement to show the changes of 'nu' for each step of z (as height). On the other hand, for each step, 'h' is supposed to be subtracted from 'z' (like: 200-10, 190-10...) as well, at least 10 times (which was trying to be defined as N)! I hope this is somehow clear.... Thanks in advance, Sue - Show quoted text - On Fri, Nov 25, 2011 at 10:16 AM, stm atoc wrote: > Hi there, > > I am a new python user. > I have ?a question regarding ?do loop..... > > This is a simple program that I have written: > > ----------------- > N=10 > h=10.0 # [micrometer] > z=-200.0 # [micrometer] > num = 0.05 #m**2/s > dz = 1.0 > nuh=[] > tmax=3600 > dt=20. > nu=[]height = arange(z*dz,0,dz) > > outfile=open('nu.dat','w') > outfile.write('height, nu, nuh') > > for z,when in enumerate(height): > ? for h in range(10): > ? ? ? for N in range(10): > ? ? ? ? ? for z in range((N-z)+(N-h)): > > ? ? ? ? ? ? ? nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence > diffusivity m**2/s > ? ? ? ? ? ? ? nu.append(num + nuh[z]) > > ----------------------- > What I like to do with this program is do loop like the fortran > version of ?as follows: > > do i = 2, N > ?z(i) = z(i-1) +h(i-1) > > end do > > write(0,*) 'z ', z(1:N) > write(0,*) 'when ', 'nu ','Conc ' > > > do i= 1, N > > ?nuh(i)= 0.01d0*exp(-0.005d2*(z(i)+200)) ! turbulence diffusivity m**2/s > ?nu(i)= num(1) + nuh(i) > > > end do > > ---------- > My problem is I am notable have the curve in the output plot as I have > as a result of ?FORTRAN program. What happens is just having a > straight line....! > the whole problem is in z part, which is supposed to be changed and i > do not see it! > > ?So, would it be possible to take a look at it please. any suggestion > would greatly appreciated. > > Thank you, > Sue > From steve at pearwood.info Fri Nov 25 12:19:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Nov 2011 22:19:28 +1100 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: <4ECF5A85.4040901@pearwood.info> Message-ID: <4ECF79C0.7090104@pearwood.info> lina wrote: > On Fri, Nov 25, 2011 at 5:06 PM, Steven D'Aprano wrote: >> pair = frozenset(('66', '69')) >> pairs[pair] = pairs.get(pair, 0) + value > > I don't get this "pairs.get" part. The "get" method does a look-up on a dict, but instead of failing if the key is missing, it returns a default value: py> d = {'a': 2} py> d['b'] # fails Traceback (most recent call last): File "", line 1, in KeyError: 'b' py> d.get('b', 3) # use 3 as the default 3 > pairs[pair]=pairs.get(pair,0)+parts[2] > TypeError: unsupported operand type(s) for +: 'int' and 'str' Lina, in your original example, the values of the dict are integers: {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} The error you show above can only happen if they are not integers, but strings. When you show us examples, please get the examples right. If you give us wrong information, how do you expect us to help? You should convert all the strings into ints. > or line in f.readlines(): > parts=line.split() > #pair=set((parts[0],parts[1])) > if (parts[0],parts[1]) not in dehydrons.keys(): > dehydrons[(parts[0],parts[1])]=parts[2] > occurence[(parts[0],parts[1])]=1 > pair=frozenset(('parts[0]','parts[1]')) > pairs[pair]=pairs.get(pair,0)+parts[2] > else: > occurence[(parts[0],parts[1])]+=1 f = open("some file") dehydrons = {} occurrence = {} pairs = {} for line in f.readlines(): parts = line.split() # convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) # order doesn't matter if pair in dehydrons: occurrence[pair] += 1 else: dehydrons[pair] = parts[2] occurrence[pair] = 1 pairs[pair] = pairs.get(pair, 0) + parts[2] f.close() -- Steven From steve at pearwood.info Fri Nov 25 12:36:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 25 Nov 2011 22:36:21 +1100 Subject: [Tutor] Do loop in Python In-Reply-To: References: Message-ID: <4ECF7DB5.60305@pearwood.info> stm atoc wrote: > Hi there, > > I am a new python user. > I have a question regarding do loop..... > > This is a simple program that I have written: > > ----------------- > N=10 > h=10.0 # [micrometer] > z=-200.0 # [micrometer] You define N, h and z here, but later on you use them as loop variables. So these three values never get used: they are thrown away, and replaced by the values of the loops: h -> 0, 1, 2, ... 9 N -> 0, 1, 2, ... 9 z is especially troublesome, because it gets used for TWO loop variables, one inside the other. The inner z loop depends on the outer z loop, which makes it tricky to predict what values z will take. > num = 0.05 #m**2/s > dz = 1.0 > nuh=[] > tmax=3600 > dt=20. > nu=[]height = arange(z*dz,0,dz) What is arange? In physics, "height" is a scalar. But later on, you seen to use height as if it were a collection of values. > outfile=open('nu.dat','w') > outfile.write('height, nu, nuh') > > for z,when in enumerate(height): > for h in range(10): > for N in range(10): > for z in range((N-z)+(N-h)): > > nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence > diffusivity m**2/s > nu.append(num + nuh[z]) > > ----------------------- > What I like to do with this program is do loop like the fortran > version of as follows: > > do i = 2, N > z(i) = z(i-1) +h(i-1) > > end do How is z initialised? What is h? I *think* you are trying to add a small increment to each value, based on the previous value. Am I close? Does this example help? zvalues = [1] # starting value increments = [0.01, 0.01, 0.02, 0.01, 0.01, 0.02, 0.01, 0.01] for h in increments: z = zvalues[-1] + h zvalues.append(z) print(zvalues) (Note: beware of floating point rounding.) -- Steven From Nikunj.Badjatya at emc.com Fri Nov 25 12:43:21 2011 From: Nikunj.Badjatya at emc.com (Nikunj.Badjatya at emc.com) Date: Fri, 25 Nov 2011 06:43:21 -0500 Subject: [Tutor] Weird Try..Except Error Message-ID: <599CEBACD49B4144A61212D837EE3C0F144604D87C@MX34A.corp.emc.com> Hi All, Please look at the snippet below. When I am running my module its giving me following error. Using : Python 2.7, windows Env. {{{ # User defined modules try: from scripts import precheck from scripts import input from scripts import validate from scripts import logsetup from scripts.constants import * except ImportError, err_msg: ==> line 38 print("ERROR {0}".format(err_msg)) print("INFO Please verify the presence of above module, and restart the installation") sys.exit(1) }}} {{{ Output: C:\> install.py -f input.xml File " C:\>install.py", line 38 except ImportError, err_msg: ^ SyntaxError: invalid syntax }}} I checked the comma and spacing and didn't find any problem. Any idea.? Thanks Nikunj -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Nov 25 12:58:07 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Nov 2011 12:58:07 +0100 Subject: [Tutor] Weird Try..Except Error References: <599CEBACD49B4144A61212D837EE3C0F144604D87C@MX34A.corp.emc.com> Message-ID: Nikunj.Badjatya at emc.com wrote: > Please look at the snippet below. > When I am running my module its giving me following error. > Using : Python 2.7, windows Env. > > {{{ > # User defined modules > try: > from scripts import precheck > from scripts import input > from scripts import validate > from scripts import logsetup > from scripts.constants import * > except ImportError, err_msg: ==> line 38 > print("ERROR {0}".format(err_msg)) > print("INFO Please verify the presence of above module, and restart > the installation") sys.exit(1) > > }}} > > {{{ > Output: > > C:\> install.py -f input.xml > File " C:\>install.py", line 38 > except ImportError, err_msg: > ^ > SyntaxError: invalid syntax > }}} > > I checked the comma and spacing and didn't find any problem. > > Any idea.? You are likely mistaken about the Python version you are using. The above error will be triggered by Python 3.x which expects try: ... except ImportError as err_msg: ... From alan.gauld at btinternet.com Fri Nov 25 13:06:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Nov 2011 12:06:35 +0000 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: Message-ID: On 25/11/11 08:41, lina wrote: >>>> pairs > {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} > > > such as here ('66', '69') and ('69', '66') is one key, > > I wanna keep only one and add the value of those two keys, above is a > very simple example: > > here is the (failed) code: > > for k, v in pairs.items(): > if str(k)[1]+str(k)[0] in pairs.keys(): I don;t think this does what you think it does. k is a key from pairs which looks like ('66', '69') You convert that to a string (with str(k)) which yields : "('66', '69')" You then add the first two characters of that string. Those are ( and ' so you get a value of (' and ask whether that appeats in pairs.keys() which it will not because the keys are tuples. So the if block never happens > print(pairs[str(k)[1]+str(k)[0]]) > pairs[k]+=pairs[str(k)[1]+str(k)[0]] > del pairs[str(k)[1]+str(k)[0]] > print(v,k) And you print the original value followed by the tuple key. I'm pretty sure thats not what you want. Maybe you are trying to add the two elements of the tuple? But even that won't disambiguate between (66,69) and (69,66) You would need to sort the tuples first so that both would render 66,69. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Fri Nov 25 13:40:39 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 25 Nov 2011 20:40:39 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: <4ECF79C0.7090104@pearwood.info> References: <4ECF5A85.4040901@pearwood.info> <4ECF79C0.7090104@pearwood.info> Message-ID: On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Aprano wrote: > lina wrote: >> >> On Fri, Nov 25, 2011 at 5:06 PM, Steven D'Aprano >> wrote: > >>> pair = frozenset(('66', '69')) >>> pairs[pair] = pairs.get(pair, 0) + value >> >> I don't get this "pairs.get" part. > > The "get" method does a look-up on a dict, but instead of failing if the key > is missing, it returns a default value: > > py> d = {'a': 2} > py> d['b'] ?# fails > Traceback (most recent call last): > ?File "", line 1, in > KeyError: 'b' > py> d.get('b', 3) ?# use 3 as the default > 3 > > >> ?pairs[pair]=pairs.get(pair,0)+parts[2] >> TypeError: unsupported operand type(s) for +: 'int' and 'str' > > Lina, in your original example, the values of the dict are integers: Ha ... it's me. > > {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} > > The error you show above can only happen if they are not integers, but > strings. When you show us examples, please get the examples right. If you > give us wrong information, how do you expect us to help? Sorry, I was confused at that time. > > You should convert all the strings into ints. > > >> or line in f.readlines(): >> ? ? ? ? ? ?parts=line.split() >> ? ? ? ? ? ?#pair=set((parts[0],parts[1])) >> ? ? ? ? ? ?if (parts[0],parts[1]) not in dehydrons.keys(): >> ? ? ? ? ? ? ? ?dehydrons[(parts[0],parts[1])]=parts[2] >> ? ? ? ? ? ? ? ?occurence[(parts[0],parts[1])]=1 >> ? ? ? ? ? ? ? ?pair=frozenset(('parts[0]','parts[1]')) >> ? ? ? ? ? ? ? ?pairs[pair]=pairs.get(pair,0)+parts[2] >> ? ? ? ? ? ?else: >> ? ? ? ? ? ? ? ?occurence[(parts[0],parts[1])]+=1 > > > f = open("some file") > dehydrons = {} > occurrence = {} > pairs = {} > for line in f.readlines(): > ? ?parts = line.split() > ? ?# convert to ints > ? ?parts = [int(s) for s in parts] > ? ?pair = frozenset(parts[:2]) ?# order doesn't matter > ? ?if pair in dehydrons: > ? ? ? ?occurrence[pair] += 1 > ? ?else: > ? ? ? ?dehydrons[pair] = parts[2] > ? ? ? ?occurrence[pair] = 1 > ? ? ? ?pairs[pair] = pairs.get(pair, 0) + parts[2] > f.close() > for line in f.readlines(): parts = line.split() #pair=set((parts[0],parts[1])) #convert to ints parts = [int(s) for s in parts] pair = frozenset(parts[:2]) print(pair) if pair in dehydrons: occurence[pair] += 1 else: dehydrons[pair] = parts[2] pairs[pair] = pairs.get(pair,0) + parts[2] print(pairs) $ python3 dehydron_data_frozenset_version.py frozenset({2, 15}) frozenset({2, 15}) Traceback (most recent call last): File "dehydron_data_frozenset_version.py", line 35, in occurence[pair] += 1 KeyError: frozenset({2, 15}) Thanks, > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From Nikunj.Badjatya at emc.com Fri Nov 25 13:42:18 2011 From: Nikunj.Badjatya at emc.com (Nikunj.Badjatya at emc.com) Date: Fri, 25 Nov 2011 07:42:18 -0500 Subject: [Tutor] Weird Try..Except Error In-Reply-To: References: <599CEBACD49B4144A61212D837EE3C0F144604D87C@MX34A.corp.emc.com> Message-ID: <599CEBACD49B4144A61212D837EE3C0F144604D888@MX34A.corp.emc.com> Hi All, Thanks for the info. I had Python27 and Python32 both installed togethar. In Windows the PATH env variable, I had set Python27 exe and lib path. But When I do C:\> Python [PressEnter] I get 2.7 But when I run C:\> script.py [PressEnter] The script is running with Python3.2 , thts weird because I have set my Path variable with Pytho27 exe and lib. Which was causing the problem. Thanks Nikunj -----Original Message----- From: tutor-bounces+nikunj.badjatya=emc.com at python.org [mailto:tutor-bounces+nikunj.badjatya=emc.com at python.org] On Behalf Of Peter Otten Sent: Friday, November 25, 2011 5:28 PM To: tutor at python.org Subject: Re: [Tutor] Weird Try..Except Error Nikunj.Badjatya at emc.com wrote: > Please look at the snippet below. > When I am running my module its giving me following error. > Using : Python 2.7, windows Env. > > {{{ > # User defined modules > try: > from scripts import precheck > from scripts import input > from scripts import validate > from scripts import logsetup > from scripts.constants import * > except ImportError, err_msg: ==> line 38 > print("ERROR {0}".format(err_msg)) > print("INFO Please verify the presence of above module, and restart > the installation") sys.exit(1) > > }}} > > {{{ > Output: > > C:\> install.py -f input.xml > File " C:\>install.py", line 38 > except ImportError, err_msg: > ^ > SyntaxError: invalid syntax > }}} > > I checked the comma and spacing and didn't find any problem. > > Any idea.? You are likely mistaken about the Python version you are using. The above error will be triggered by Python 3.x which expects try: ... except ImportError as err_msg: ... _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From cranky.frankie at gmail.com Fri Nov 25 13:59:34 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Fri, 25 Nov 2011 07:59:34 -0500 Subject: [Tutor] sensing EOF in Python 3.1 Message-ID: From: Steven D'Aprano wrote: <> Right, thanks. <> I want to include this info in my presentation because it shows how data structures can be externalized. <> Still though, that is important. < Sarcasm aside, what else could "import pickle" mean other than import > the pickle module?>> I was trying to put a comment on every line because the audience who will be looking at this will have never seen any Python before. <> I know what you mean. The commens could be meaningful at first, then the code gets edited over the years and the comments don't get updated. I've seen that many times. <> Again, in this specific instance, this simple example code is intended to be looked at not by Python programmers, or even programmers, but rather by database professionals who I am attempting to expose Python to for the first time. <> You are of course, correct, thanks. I'll be fixing that. Steven thanks for your comments about comments, I'll be doing them over for sure. -- Frank L. "Cranky Frankie" Palmeri From stm.at.oc at googlemail.com Fri Nov 25 14:46:09 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Fri, 25 Nov 2011 14:46:09 +0100 Subject: [Tutor] Do loop in Python In-Reply-To: <4ECF7DB5.60305@pearwood.info> References: <4ECF7DB5.60305@pearwood.info> Message-ID: Thank you so much for your reply. It was very helpful information and I used it in order to improve the program.... Here is the new version of the program: zvalues = [-200] # starting value hvalues = [10] # starting value increments = [1, 1, 1, 1, 1, 1, 1, 1] for N in increments: h = hvalues[-1] - N hvalues.append(h) z = zvalues[-1] + h zvalues.append(z) height = arange((z)*dz,0,dz) for z,when in enumerate(height): nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) The story is like this: I should define layers and thickness and see how the diffusion profile changes over the z. height (or depth) of the total thickness or 'z'. I basically, define 'z' in 10 layers and each layer is called ' N' . Difference between each layer is 'h', which is equal 10 micrometer. Now, what I like to do is the modification of nu based on each zvalue In fact, for each 'zvalue' o'z' step, I need to calculate a different value for 'nu' based on the available equation in the program. BUT, I am not sure, exactly, how to add the new do loop of z inside another loop of nu. I have done this way as well (the other way around): height = arange((z)*dz,0,dz) for z,when in enumerate(height): for N in increments: h = hvalues[-1] - N hvalues.append(h) z = zvalues[-1] + h zvalues.append(z) nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence diffusivity m**2/s nu.append(num + nuh[z]) but still no sign of 'nu changes' over 'z'! So, would it be possible to check that again? Thanks, Sue On Fri, Nov 25, 2011 at 12:36 PM, Steven D'Aprano wrote: > stm atoc wrote: >> >> Hi there, >> >> I am a new python user. >> I have ?a question regarding ?do loop..... >> >> This is a simple program that I have written: >> >> ----------------- >> N=10 >> h=10.0 # [micrometer] >> z=-200.0 # [micrometer] > > You define N, h and z here, but later on you use them as loop variables. So > these three values never get used: they are thrown away, and replaced by the > values of the loops: > > h -> 0, 1, 2, ... 9 > N -> 0, 1, 2, ... 9 > > z is especially troublesome, because it gets used for TWO loop variables, > one inside the other. The inner z loop depends on the outer z loop, which > makes it tricky to predict what values z will take. > > >> num = 0.05 #m**2/s >> dz = 1.0 >> nuh=[] >> tmax=3600 >> dt=20. >> nu=[]height = arange(z*dz,0,dz) > > What is arange? > > In physics, "height" is a scalar. But later on, you seen to use height as if > it were a collection of values. > > >> outfile=open('nu.dat','w') >> outfile.write('height, nu, nuh') >> >> for z,when in enumerate(height): >> ? for h in range(10): >> ? ? ? for N in range(10): >> ? ? ? ? ? for z in range((N-z)+(N-h)): >> >> ? ? ? ? ? ? ? nuh.append(0.01 * exp(-0.05*(z+200.0))*dz) #turbulence >> diffusivity m**2/s >> ? ? ? ? ? ? ? nu.append(num + nuh[z]) >> >> ----------------------- >> What I like to do with this program is do loop like the fortran >> version of ?as follows: >> >> do i = 2, N >> ?z(i) = z(i-1) +h(i-1) >> >> end do > > > How is z initialised? What is h? > > > I *think* you are trying to add a small increment to each value, based on > the previous value. Am I close? > > > Does this example help? > > > zvalues = [1] ?# starting value > increments = [0.01, 0.01, 0.02, 0.01, 0.01, 0.02, 0.01, 0.01] > for h in increments: > ? ?z = zvalues[-1] + h > ? ?zvalues.append(z) > > print(zvalues) > > > (Note: beware of floating point rounding.) > > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at alchemy.com Fri Nov 25 16:34:16 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 25 Nov 2011 07:34:16 -0800 Subject: [Tutor] Weird Try..Except Error In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D888@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D87C@MX34A.corp.emc.com> <599CEBACD49B4144A61212D837EE3C0F144604D888@MX34A.corp.emc.com> Message-ID: <4ECFB578.7020300@alchemy.com> On 25-Nov-11 04:42, Nikunj.Badjatya at emc.com wrote: > Hi All, > > Thanks for the info. > I had Python27 and Python32 both installed togethar. > In Windows the PATH env variable, I had set Python27 exe and lib path. > > But When I do > C:\> Python [PressEnter] > I get 2.7 > > But when I run > C:\> script.py [PressEnter] > The script is running with Python3.2 , thts weird because I have set my Path variable with Pytho27 exe and lib. > > Which was causing the problem. The problem is likely that when you installed Python 3.2, Windows associated the ".py" extension with the new 3.2 interpreter, PATH notwithstanding. steve -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C From andreas.perstinger at gmx.net Fri Nov 25 17:49:43 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 25 Nov 2011 17:49:43 +0100 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: <4ECF5A85.4040901@pearwood.info> <4ECF79C0.7090104@pearwood.info> Message-ID: <4ECFC727.6030708@gmx.net> On 2011-11-25 13:40, lina wrote: > On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Aprano wrote: >> f = open("some file") >> dehydrons = {} >> occurrence = {} >> pairs = {} >> for line in f.readlines(): >> parts = line.split() >> # convert to ints >> parts = [int(s) for s in parts] >> pair = frozenset(parts[:2]) # order doesn't matter >> if pair in dehydrons: >> occurrence[pair] += 1 >> else: >> dehydrons[pair] = parts[2] >> occurrence[pair] = 1 >> pairs[pair] = pairs.get(pair, 0) + parts[2] >> f.close() >> > for line in f.readlines(): > parts = line.split() > #pair=set((parts[0],parts[1])) > #convert to ints > parts = [int(s) for s in parts] > pair = frozenset(parts[:2]) > print(pair) > if pair in dehydrons: > occurence[pair] += 1 > else: > dehydrons[pair] = parts[2] > pairs[pair] = pairs.get(pair,0) + parts[2] > print(pairs) > > > $ python3 dehydron_data_frozenset_version.py > frozenset({2, 15}) > frozenset({2, 15}) > Traceback (most recent call last): > File "dehydron_data_frozenset_version.py", line 35, in > occurence[pair] += 1 > KeyError: frozenset({2, 15}) You want to add one to "occurence[frozenset({2, 15})]" but there is no such key in "occurence" yet. If you carefully re-read Steven's code snippet you will see that you missed the line occurence[pair] = 1 in the else-branch. Therefore "occurence[frozenset({2, 15})]" wasn't set in the first iteration and you get the error in the second. You can see that you are already in the second iteration by looking at the output of your program before the error message. Bye, Andreas From o0MB0o at hotmail.se Fri Nov 25 18:11:04 2011 From: o0MB0o at hotmail.se (Mic) Date: Fri, 25 Nov 2011 18:11:04 +0100 Subject: [Tutor] Shortening the code. In-Reply-To: References: Message-ID: > >from functools import partial >I use this kind of explicit import for a few names that I use frequently, >namely defaultdict, contextmanager, everything from itertools... >I think of these as my personal extended set of builtins ;) >As to the actual partial() function, you probably don't see it a lot >because >it has been in the standard library for only three years. The older idiom >for making a function that calls another function with a fixed argument is command = lambda button=button: button_clicked(button) Alright! What is a fixed argument? >You can iterate over (row, column) pairs instead of the dummy _ variable: >def create_widgets(self): >for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: >button = tk.Button(self) >command = partial(button_clicked, button) >button["command"] = command >button.grid(row=row, column=column) >command() Very nice! I didn't know that it was possible. This saves me a lot of space. Am I, as a beginner, supposed to know this? Say that when button one is pressed I want a text file to be created. The text in the file should be the same number as the button I pressed. So if I press button one, once, it should create a text file with the name button_1. The text in the file should also be "button_1". If the button is pressed again, it should remove the file. Is this possible to do without any trouble? So if the second button is pressed , it should create a text file with the name button_2 and the text in it should be button_2. If the button is pressed once again, it is supposed to delete that file it created. I don't know if it works with this piece of code you posted earlier: >def create_widgets(self): >for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: >button = tk.Button(self) >command = partial(button_clicked, button) >button["command"] = command >button.grid(row=row, Otherwise it might work with the code below this comment? def button_clicked(button): if button["bg"] == "green": button.configure(bg="red", text="Hi 2") else: button.configure(bg="green", text="Hi 1") class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for _ in range(2): button = tk.Button(self) command = partial(button_clicked, button) button["command"] = command button.grid() command() I also have one last question. How do I make the first button that is created to be named 1, the second to be created 2, the third 3 and so on? >> Also, assume that I have a already have a window with a button in it. If >> you press this button, this window is supposed to open. >> So, if I press the button, will this window open? Because I created the >> previous window using >> from tkinter import* and not import tkinter as tk. >You can make the decision what style you want to use on a per-module basis. >In that module you can then access (for example) a tkinter button with >either tkinter.Button, tk.Button or just Button. >You can even mix styles if you put the respective imports at the beginning >of the module (not recommended). >What approach you take has no consequences on the execution of the program. I didn't know that, thanks. It is strange that this wasn't mentioned in my book. Why is it not recommended to to mix the styles if you put the respective imports at the beginning of the module? Thanks again for your help and insightful suggestions. It is really appreciated :) Mic From __peter__ at web.de Fri Nov 25 19:40:37 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 25 Nov 2011 19:40:37 +0100 Subject: [Tutor] Shortening the code. References: Message-ID: Mic wrote: > >> >from functools import partial > >>I use this kind of explicit import for a few names that I use frequently, >>namely defaultdict, contextmanager, everything from itertools... >>I think of these as my personal extended set of builtins ;) > >>As to the actual partial() function, you probably don't see it a lot >>because >>it has been in the standard library for only three years. The older idiom >>for making a function that calls another function with a fixed argument is > > command = lambda button=button: button_clicked(button) > > Alright! What is a fixed argument? Suppose you have a function add() that calculates the sum of two values >>> def add(a, b): ... return a + b ... >>> add(1, 2) 3 If you want another function that takes one argument and adds 2 to that argument you can either start from scratch >>> def plus_two(b): ... return 2 + b ... >>> plus_two(7) 9 or build on your earlier work >>> from functools import partial >>> plus_two = partial(add, 2) >>> plus_two(3) 5 The effect of wrapping add into partial here is that every time you call plus_two(x) it will in turn call add(2, x). As the first argument is always the same I called it "fixed", but it's not a terminus technicus. >>You can iterate over (row, column) pairs instead of the dummy _ variable: > >>def create_widgets(self): > >for row, column in [(0, 0), (1, 1), (2, 2), (3, 0)]: > >button = tk.Button(self) > >command = partial(button_clicked, button) > >button["command"] = command > >button.grid(row=row, column=column) > >command() > > Very nice! I didn't know that it was possible. This saves me a lot of > space. Am I, as a beginner, supposed to know this? You may read it up somewhere or be shown on a mailinglist ;) > Say that when button one is pressed I want a text file to be created. The > text in the > file should be the same number as the button I pressed. So if I press > button one, once, > it should create a text file with the name button_1. The text in the file > should also be "button_1". > > If the button is pressed again, it should remove the file. Is this > possible to do without > any trouble? > > So if the second button is pressed , it should create a text file with the > name button_2 > and the text in it should be button_2. If the button is pressed once > again, it is supposed to > delete that file it created. > I also have one last question. > How do I make the first button that is created to be named > 1, the second to be created 2, the third 3 and so on? Here's a modified script: import tkinter as tk from functools import partial def button_clicked(button): if button["bg"] == "green": button["bg"] = "red" print("deleting file", button.filename) else: button["bg"] = "green" print("creating file", button.filename) class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = tk.Button(self, text="Button {}".format(index+1), bg="red") button.filename = "button{}.txt".format(index+1) command = partial(button_clicked, button) button["command"] = command row, column = divmod(index, 4) button.grid(row=row, column=column) root = tk.Tk() root.title("Test") app = Window(root) root.mainloop() I hope you can infer answers to your questions from the above... To be honest, we've reached the point where I would switch to a tkinter.Button subclass: import tkinter as tk FREE = "green" OCCUPIED = "red" class SeatButton(tk.Button): def __init__(self, master, index): text = "Button {}".format(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "button{}.txt".format(index+1) self.occupied = False def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED print("creating file", self.filename) else: self["bg"] = FREE print("deleting file", self.filename) class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root = tk.Tk() root.title("Test") app = Window(root) root.mainloop() Too bad that now you've understood what partial() does it's gone... > Why is it not recommended to to mix the styles if you put the respective > imports at the > beginning of the module? Consistency. Either call the button tk.Button or Button. From alan.gauld at btinternet.com Fri Nov 25 22:11:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Nov 2011 21:11:17 +0000 Subject: [Tutor] Weird Try..Except Error In-Reply-To: <599CEBACD49B4144A61212D837EE3C0F144604D888@MX34A.corp.emc.com> References: <599CEBACD49B4144A61212D837EE3C0F144604D87C@MX34A.corp.emc.com> <599CEBACD49B4144A61212D837EE3C0F144604D888@MX34A.corp.emc.com> Message-ID: On 25/11/11 12:42, Nikunj.Badjatya at emc.com wrote: > I had Python27 and Python32 both installed togethar. > In Windows the PATH env variable, I had set Python27 exe and lib path. > > But When I do > C:\> Python [PressEnter] > I get 2.7 > > But when I run > C:\> script.py [PressEnter] > The script is running with Python3.2 , > thts weird because I have set my Path variable with Pytho27 exe This is one of the annoying ambiguities of Windows. The way it finds the executable for executables(exe, bat cmd etc) is different to how it finds the executable for associations. In the former case it uses PATH, in the latter it relies on the file association set in the file properties. When you install a new Python it tends to set itself as the default interpreter for .py files. Annoying, Alan G. From o0MB0o at hotmail.se Fri Nov 25 22:14:46 2011 From: o0MB0o at hotmail.se (Mic) Date: Fri, 25 Nov 2011 22:14:46 +0100 Subject: [Tutor] Shortening the code of a finsihed program. In-Reply-To: References: Message-ID: >Its usually better to paste long programs into a pastebin web site and >give us a link. >This saves cluttering up people mail with long messages, and also the >pastebin rendering will usually be easier to read with syntax coloring etc. Alright. Sorry if I should know this, but what is a pastebin web site and how do I paste my program into a pastebin web site? >While its perfectly legal Python to create a class inside a method its >very unusual in practice and very restricting in the use of the class. >Its nearly always better to declare all your classes at the top level of >the program. Why is it restricting? >Because you post lost all the formatting, I'm not sure where this code >is supposed to sit... This is again where a pastebin would help. Oh, now I understand why I shouldn't post like this. My apologize, won't happen again. >And this is repeating all the bad habits from your original posts. If >you adopt the ChairButton class approach all of this becomes much >clearer and simpler. I got a really good tip earlier on in the thread how I could make my program dramatically shorter. I have tried to implement a couple of things I need into that piece of code, but I cannot get it to work. So I figured I could post it here (short code) and ask you a couple of questions regarding the code: import tkinter as tk from functools import partial def button_clicked(button): if button["bg"] == "green": button.configure(bg="red", text="01") else: button.configure(bg="green", text="01") class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): list_chair=[(0, 0), (0, 1), (0, 3), (0, 4), (1,0)] for row, column in list_chair: button = tk.Button(self) command = partial(button_clicked, button) button["command"] = command button.grid(row=row, column=column) command() root = tk.Tk() root.title("Test") root.geometry("200x200") app = Window(root) root.mainloop() Questions: --I want the first button to be created to have the text "1". The second should have the text "2". The third the text "3" and so on. --When the first button is pressed I want a file to be created with the name Germany_France_1. The text in the file should be Germany_France_1. If/When the button is pressed again it should delete the file. When the second button is pressed I want a file to be created with the name Germany_France_2. The text in the file should be Germany_France_2. If/When the button is pressed again it should delete the file. When the third button is pressed I want a file to be created with the name Germany_France_3. The text in the file should be Germany_France_3. If/When the button is pressed again it should delete the file. Do you have any idea on how I can accomplish this? I reached the conclusion that it should be easy to do so since it was so easy to create so many buttons in so little amount of code. However, to my dismay, I have tried this entire evening without success. It feels like I am so close to shorten my program from 2k+ lines of code to maybe 250 at most, but still so far away. >You should only ever have one Tk() object in a Tkinter program. Why is that? >And again you should only have one mainloop running, otherwise things >would get very confusing with events winding up in the wrong windows >event queue etc. Alright, my teacher never mentioned that when he examined my program. Thanks for your input! Your help is as always appreciated and my apologize for making confusing posts! Mic From alan.gauld at btinternet.com Fri Nov 25 22:24:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Nov 2011 21:24:59 +0000 Subject: [Tutor] Shortening the code. In-Reply-To: References: Message-ID: On 25/11/11 17:11, Mic wrote: >> for making a function that calls another function with a fixed >> argument is > > command = lambda button=button: button_clicked(button) > > Alright! What is a fixed argument? Its onre that is the same every time the function is called. The lambda construct above is equivalent to the following which may make it clearer: def button_clicked(aButton): # do something with aButton here # that uses a lot of code and # we want to reuse for any button Now we want to use that function as an event handler, but the function passed as the command in tkinter is not allowed to take an argument. So we create a very short function that takes no arguments but calls button_clicked with a fixed argument. And we do this for two buttons so that they can both use the button_clicked def button1_clicked(): button_clicked(buttonOne) def button2_clicked(): button_clicked(buttonTwo) and we can use these whehn creating our buttons: buttonOne = Button(parent, command=button1_clicked, ....) buttonTwo = Button(parent, command=button2_clicked, ....) Now a shorter way of doing that, which avoids writing lots of these very small functions is to use lambda, which is an operator that returns a function as a value. Thus def add2(x): return x+2 can be written add2 = lambda x: x+2 And if we don't really care about the name - which is true for the button commands we can put lambda directly into the widget creation: buttonOne = Button(parent, command=lambda b=buttonOne: button_clicked(b), ....) buttonTwo = Button(parent, command=lambda b=buttonTwo: button_clicked(b), ....) Note that this works because the lambda defines a default argument for the command. Thus Tkinter can call the function with no arguments and Python will insert the default value at runtime. HTH, Alan G. From andreas.perstinger at gmx.net Fri Nov 25 22:44:00 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 25 Nov 2011 22:44:00 +0100 Subject: [Tutor] Do loop in Python In-Reply-To: References: <4ECF7DB5.60305@pearwood.info> Message-ID: <4ED00C20.9090509@gmx.net> On 2011-11-25 14:46, stm atoc wrote: > Here is the new version of the program: > > zvalues = [-200] # starting value > hvalues = [10] # starting value > increments = [1, 1, 1, 1, 1, 1, 1, 1] > for N in increments: > h = hvalues[-1] - N > hvalues.append(h) > z = zvalues[-1] + h > zvalues.append(z) > height = arange((z)*dz,0,dz) There is no "arange" in python. Could it be that you use numpy and import it with "from numpy import *"? > for z,when in enumerate(height): I'm pretty sure this line doesn't do what you expect it to do. You have a sequence (a numpy array) named "height" and after calling "enumerate" you get a list of tuples in the form of [(0, height[0]), (1, height[1]), ...]. Now the for-loop iterates over this list and assigns "z" to the first value of the tuple (the index-values) and "when" to the second (the values from "height"). You later never use "when" but just use "z". If you really want that, the "enumerate" is completly unnecessary and you could just use "for z in range(len(height))". But I'm not sure if numpy arrays work with "len()". > nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence > diffusivity m**2/s > nu.append(num + nuh[z]) > > The story is like this: > I should define layers and thickness and see how the diffusion profile > changes over the z. > height (or depth) of the total thickness or 'z'. > I basically, define 'z' in 10 layers and each layer is called ' N' . > Difference between each layer is 'h', which is equal 10 micrometer. > Now, what I like to do is the modification of nu based on each zvalue > In fact, for each 'zvalue' o'z' step, I need to calculate a different > value for 'nu' based on the available equation in the program. > > BUT, I am not sure, exactly, how to add the new do loop of z inside > another loop of nu. For me your explanations are still too confusing. Could it be that you are thinking way too complicated? My guess is you want to have a range of material thicknesses (from 1 to 200 micrometers in 10 micrometer-steps) and then you want from each thickness 10 different layers, right? import math # you should always tell us which modules you import num = 0.05 # some constant nu = [] # list of resulting values h = 10.0 # height of one layer thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, 10, 20, ..., 190, 200) layers = range(1,11) # a list from 1 to 10 for t in thickness: for l in layers: z = t + h * l # I'm not sure if you want to add or subtract the layer thickness nu = num + (0.01 * math.exp(-0.05 * (z + 200.0))) This will result in a big one-dimensional list where you calculate for each thickness the nu-value for 10 layers. Am I close? I'm still not sure about the steps and the height of the layers. I also wonder if it wouldn't be better to use a two-dimensional list. > I have done this way as well (the other way around): > > height = arange((z)*dz,0,dz) > for z,when in enumerate(height): > for N in increments: > h = hvalues[-1] - N > hvalues.append(h) > z = zvalues[-1] + h > zvalues.append(z) > nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence > diffusivity m**2/s > nu.append(num + nuh[z]) > > but still no sign of 'nu changes' over 'z'! As Charles has already mentioned, the values for "nu" are very similar (they start beginning to differ just at the seventh digit after the comma). How do you further process this values? If you plot them what's your scale? Bye, Andreas From alan.gauld at btinternet.com Fri Nov 25 22:50:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 25 Nov 2011 21:50:10 +0000 Subject: [Tutor] Shortening the code of a finsihed program. In-Reply-To: References: Message-ID: On 25/11/11 21:14, Mic wrote: > Alright. Sorry if I should know this, but what is a pastebin web site > and how do I paste my program into a pastebin web site? A web site that you can paste stuff and then provide a link(url) that others can use to view it. You can usually specify the code style and it will apply syntax coloring for you. Try a google search for free pastebin... As an example I've pasted your code from this message at: http://pastebin.com/H3VzaapV Take a look and you will see what I mean. >> While its perfectly legal Python to create a class inside a method its >> very unusual in practice and very restricting in the use of the class. > > Why is it restricting? Because the class is only available inside the function. You cannot create objects of that class anywhere outside the class. > So I figured I could post it here (short code) and ask you a couple of > questions regarding the code: > > > import tkinter as tk > from functools import partial > > def button_clicked(button): > if button["bg"] == "green": > button.configure(bg="red", text="01") > else: > button.configure(bg="green", text="01") Note you are setting text to '01' in every case. Thats probably not what you want? > def create_widgets(self): > list_chair=[(0, 0), (0, 1), (0, 3), (0, 4), (1,0)] > for row, column in list_chair: > button = tk.Button(self) > command = partial(button_clicked, button) > button["command"] = command > button.grid(row=row, column=column) > command() As stated above this will result in every chair being green and having the text '01' It would be better to put the initial colour and text in your data list and configure each button directly: def create_widgets(self): list_chair=[(0, 0, '01'), (0, 1, '02'), (0, 3, '03'), (0, 4, '04'), (1, 0, '05')] for row, column, name in list_chair: command = partial(button_clicked, button) button = tk.Button(self, color='green', command=command, text=name) button.grid(row=row, column=column) Incidentally, This is what I mentioned early on in the discussion about using a data table to create your widgets. > root = tk.Tk() > root.title("Test") > root.geometry("200x200") > app = Window(root) > root.mainloop() > --When the first button is pressed I want a file to be created with the > name Germany_France_1. > The text in the file should be Germany_France_1. > If/When the button is pressed again it should delete the file. Lets get the initial UI set up correctly first. Once we have done that we can worry about adding the functionality. This is one of the good habits in programming. Do it step by step. Get one thing working first before trying to add more features. Its a lot easier to debug code when you know what you changed to stop it working. > Do you have any idea on how I can accomplish this? I reached the > conclusion that it should be easy to do so since it was so easy > to create so many buttons in so little amount of code. Yes, but lets get the UI all done first, then we can add the button features. >> You should only ever have one Tk() object in a Tkinter program. > > Why is that? Because thats how Tkinter expects to work! It builds a tree of all the windows and widgets in your program. If you have two trees in the same program it can get very confused about which widget is doing what to which other widgets, especially if they wind up in different trees!. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Nov 26 01:07:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Nov 2011 11:07:21 +1100 Subject: [Tutor] Shortening the code of a finsihed program. In-Reply-To: References: Message-ID: <4ED02DB9.2020009@pearwood.info> Alan Gauld wrote: > On 24/11/11 16:20, Mic wrote: > >> and then try to put these parts togheter into a large program, I decided >> to post my entire program. > > Its usually better to paste long programs into a pastebin web site and > give us a link. > This saves cluttering up people mail with long messages, and also the > pastebin rendering will usually be easier to read with syntax coloring etc. I'd just like to say that some of us disagree with this advice. Some people (e.g. me) often read their where getting access to a browser is less convenient. More importantly, many pastebin sites are short-term only, after some weeks the bin disappears and the code is lost, which destroys the archival value of the post. If your code snippet is short, say, less than two dozen lines, there's no need to using a pastebin, just include it in your post in-line. More than that, you should attach it to the post as an attachment, as a .txt or .py file. Under no circumstances use your mail client's "rich text", colours or multiple fonts. Even a 200 line program isn't that big, it's only about 6K. If your code is so large that syntax highlighting becomes particularly useful, then chances are it's too long and people won't read it regardless. We're volunteers doing free support, but there are limits to how much code we're going to wade through if it doesn't interest us personally. -- Steven From steve at pearwood.info Sat Nov 26 01:14:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Nov 2011 11:14:02 +1100 Subject: [Tutor] Shortening the code of a finsihed program. In-Reply-To: References: Message-ID: <4ED02F4A.1010806@pearwood.info> Hello Mic, Mic wrote: > >> Its usually better to paste long programs into a pastebin web site and >> give us a link. >> This saves cluttering up people mail with long messages, and also the >> pastebin rendering will usually be easier to read with syntax coloring >> etc. Please keep a attribution line when quoting people directly. Even something simple like "Fred wrote" will do. > Alright. Sorry if I should know this, but what is a pastebin web site > and how do > I paste my program into a pastebin web site? Here's one: http://pastebin.com/ But as I've just written in another post, please don't use it :) >> While its perfectly legal Python to create a class inside a method its >> very unusual in practice and very restricting in the use of the class. >> Its nearly always better to declare all your classes at the top level of >> the program. > > Why is it restricting? Because generally speaking, if you define a class inside a function (or method), you can't use it *except* inside that function or method. class K: def method(self, x): class Q: pass instance = Q() This doesn't work because Q is not visible from the outside of K.method. Sometimes this is what you want; generally it is not. I don't know much about tkinter, so I will avoid commenting about your code. -- Steven From alan.gauld at btinternet.com Sat Nov 26 02:57:34 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Nov 2011 01:57:34 +0000 Subject: [Tutor] Shortening the code of a finsihed program. In-Reply-To: <4ED02DB9.2020009@pearwood.info> References: <4ED02DB9.2020009@pearwood.info> Message-ID: On 26/11/11 00:07, Steven D'Aprano wrote: >> Its usually better to paste long programs into a pastebin web site and >> give us a link. > > I'd just like to say that some of us disagree with this advice. Some > people (e.g. me) often read their where getting access to a browser is > less convenient. Its true there are downsides to every option. > Even a 200 line program isn't that big, it's only about 6K. That adds up if you are reading on a 3G smartphone with a 100M data limit or paying by the byte. And attachments don't help there. Plus many email gateways block all attachments as a security measure. > is so large that syntax highlighting becomes particularly useful, then > chances are it's too long and people won't read it regardless. I find syntax highlighting useful even in very short snippets of code, but I agree it's better to just keep the code sample short and post it inline. And I do take the point that pastebins are short lived and so unless the replies incorporate the defective code snippets its lost to the archive. Nonetheless I personally prefer a pastebin posting to a long mail listing with no highlighting and often defective indenting. as I say there is no perfect solution to long posts other than to shorten them.... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Sat Nov 26 03:49:40 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 26 Nov 2011 10:49:40 +0800 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: <4ECFC727.6030708@gmx.net> References: <4ECF5A85.4040901@pearwood.info> <4ECF79C0.7090104@pearwood.info> <4ECFC727.6030708@gmx.net> Message-ID: On Sat, Nov 26, 2011 at 12:49 AM, Andreas Perstinger wrote: > On 2011-11-25 13:40, lina wrote: >> >> On Fri, Nov 25, 2011 at 7:19 PM, Steven D'Aprano >> ?wrote: >>> >>> ?f = open("some file") >>> ?dehydrons = {} >>> ?occurrence = {} >>> ?pairs = {} >>> ?for line in f.readlines(): >>> ? ? parts = line.split() >>> ? ? # convert to ints >>> ? ? parts = [int(s) for s in parts] >>> ? ? pair = frozenset(parts[:2]) ?# order doesn't matter >>> ? ? if pair in dehydrons: >>> ? ? ? ? occurrence[pair] += 1 >>> ? ? else: >>> ? ? ? ? dehydrons[pair] = parts[2] >>> ? ? ? ? occurrence[pair] = 1 >>> ? ? ? ? pairs[pair] = pairs.get(pair, 0) + parts[2] >>> ?f.close() >>> >> ? ? ? ? for line in f.readlines(): >> ? ? ? ? ? ? parts = line.split() >> ? ? ? ? ? ? #pair=set((parts[0],parts[1])) >> ? ? ? ? ? ? #convert to ints >> ? ? ? ? ? ? parts = [int(s) for s in parts] >> ? ? ? ? ? ? pair = frozenset(parts[:2]) >> ? ? ? ? ? ? print(pair) >> ? ? ? ? ? ? if pair in dehydrons: >> ? ? ? ? ? ? ? ? occurence[pair] += 1 >> ? ? ? ? ? ? else: >> ? ? ? ? ? ? ? ? dehydrons[pair] = parts[2] >> ? ? ? ? ? ? ? ? pairs[pair] = pairs.get(pair,0) + parts[2] >> ? ? ? ? print(pairs) >> >> >> $ python3 dehydron_data_frozenset_version.py >> frozenset({2, 15}) >> frozenset({2, 15}) >> Traceback (most recent call last): >> ? File "dehydron_data_frozenset_version.py", line 35, in >> ? ? occurence[pair] += 1 >> KeyError: frozenset({2, 15}) > > You want to add one to "occurence[frozenset({2, 15})]" but there is no such > key in "occurence" yet. > > If you carefully re-read Steven's code snippet you will see that you missed > the line > > occurence[pair] = 1 > > in the else-branch. Thanks, I was so careless. for k, v in occurence.items(): print(v,k) 292 frozenset({66, 69}) 222 frozenset({24, 27}) How can I let the result like: 292 {66,69} 222 {24,27} don't output the frozenset > > Therefore "occurence[frozenset({2, 15})]" wasn't set in the first iteration > and you get the error in the second. You can see that you are already in the > second iteration by looking at the output of your program before the error > message. > > Bye, Andreas > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From charleshbecker at gmail.com Sat Nov 26 04:36:56 2011 From: charleshbecker at gmail.com (Charles Karl Becker) Date: Fri, 25 Nov 2011 20:36:56 -0700 Subject: [Tutor] Operation Speed Question Message-ID: Dear Pythonistas, http://wiki.python.org/moin/PythonSpeed#Takeadvantageofinterpreteroptimizations%E2%80%8C%E2%80%8Bthis is a link I found concerning optimizing the speed of python code. Is anyone familiar with an article or wiki such as this that may cover the changes that took place in Py3K? And I've heard that the Standard Library will discuss the Big O notation for methods etc. Where do I find the comments on this in the docs? A search for O(1) and O(n) returned nothing on python.org, is http://docs.python.org/py3k/library/timeit.html the best bet or is there somewhere else to look? I realize that my code isn't probably going to enter any area where this is important any time soon, but I'm trying to fill in my gaps in CS theory without doing so through school. Thanks! Charles -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Nov 26 11:05:44 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Nov 2011 11:05:44 +0100 Subject: [Tutor] Operation Speed Question References: Message-ID: Charles Karl Becker wrote: http://wiki.python.org/moin/PythonSpeed#Takeadvantageofinterpreteroptimizations%E2%80%8C%E2%80%8Bthis > is a link I found concerning optimizing the speed of python code. Is > anyone familiar with an article or wiki such as this that may cover the > changes that took place in Py3K? And I've heard that the Standard Library > will discuss the Big O notation for methods etc. Where do I find the > comments on this in the docs? A search for O(1) and O(n) returned nothing > on python.org, Did you follow the link from the page you quote to http://wiki.python.org/moin/TimeComplexity ? > is http://docs.python.org/py3k/library/timeit.html the best > bet or is there somewhere else to look? timeit is meant to give you an idea about the performance of small snippets of code; to find the bottlenecks in an application there is http://docs.python.org/dev/py3k/library/profile.html From kliateni at gmail.com Sat Nov 26 11:16:52 2011 From: kliateni at gmail.com (Karim) Date: Sat, 26 Nov 2011 11:16:52 +0100 Subject: [Tutor] How to raise error without the stack trace Message-ID: <4ED0BC94.1060401@gmail.com> Hello, I want to fire my own exception without having the (useful but ugly in my case) stack trace display. How to modify a Exception type class for that purpose which looks like: classs MyError(Exception): pass Cheers Karim From hugo.yoshi at gmail.com Sat Nov 26 12:14:22 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sat, 26 Nov 2011 12:14:22 +0100 Subject: [Tutor] How to raise error without the stack trace In-Reply-To: <4ED0BC94.1060401@gmail.com> References: <4ED0BC94.1060401@gmail.com> Message-ID: On Sat, Nov 26, 2011 at 11:16 AM, Karim wrote: > > Hello, > > I want to fire my own exception without having the (useful but ugly in my > case) stack trace display. > > How to modify a Exception type class for that purpose which looks like: > > classs MyError(Exception): > ? ? ? pass > > Cheers > Karim > The stack trace is what happens when an exception is uncaught. You don't need to modify it. What you want to do is catch the exception, print it, then, depending on whether you can recover from the error, possibly do a sys.exit(-1). Hugo From __peter__ at web.de Sat Nov 26 12:17:46 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Nov 2011 12:17:46 +0100 Subject: [Tutor] How to raise error without the stack trace References: <4ED0BC94.1060401@gmail.com> Message-ID: Karim wrote: > I want to fire my own exception without having the (useful but ugly in > my case) stack trace display. Printing the stack trace is part of the standard exception handling. For an uncaught exception python will call sys.excepthook which in turn will print the traceback unless you have set it to a custom function. > How to modify a Exception type class for that purpose which looks like: > > classs MyError(Exception): > pass You don't modify the exception, you handle it explicitly. Wrap your code into try ... except: # before main() # may raise MyError # after try: main() except MyError as e: print(e) From o0MB0o at hotmail.se Sat Nov 26 12:36:35 2011 From: o0MB0o at hotmail.se (Mic) Date: Sat, 26 Nov 2011 12:36:35 +0100 Subject: [Tutor] Shortening the code In-Reply-To: References: Message-ID: >> Alright! What is a fixed argument? >Its onre that is the same every time the function is called. >The lambda construct above is equivalent to the following which may >make it clearer: >def button_clicked(aButton): # do something with aButton here # that uses a lot of code and # we want to reuse for any button >Now we want to use that function as an event handler, but the function >passed as the command in tkinter is not allowed to take an argument. >So we create a very short function that takes no arguments but calls >button_clicked with a fixed argument. And we do this for two buttons >so that they can both use the button_clicked >def button1_clicked(): > button_clicked(buttonOne) >def button2_clicked(): > button_clicked(buttonTwo) >and we can use these whehn creating our buttons: >buttonOne = Button(parent, command=button1_clicked, ....) >buttonTwo = Button(parent, command=button2_clicked, ....) >Now a shorter way of doing that, which avoids writing lots of these very >small functions is to use lambda, which is an operator that returns a >function as a value. >Thus >def add2(x): return x+2 >can be written >add2 = lambda x: x+2 >And if we don't really care about the name - which is >true for the button commands we can put lambda directly >into the widget creation: >buttonOne = Button(parent, command=lambda b=buttonOne: button_clicked(b), ....) >buttonTwo = Button(parent, command=lambda b=buttonTwo: button_clicked(b), ....) >Note that this works because the lambda defines a default argument for >the command. Thus Tkinter can call the function with no arguments and >Python will insert the default value at runtime. This was a lot of new information for me so it might take some time for it to sink in. Thanks for the information! >>> While its perfectly legal Python to create a class inside a method its >>> very unusual in practice and very restricting in the use of the class. >> >> Why is it restricting? >Because the class is only available inside the function. You cannot >create objects of that class anywhere outside the class. And that is not good because you want to be able to create objects of a class outside the class mostly? >Note you are setting text to '01' in every case. Thats probably not what >you want? No, that is not what I want. The text should be 1 for button one, 2 for button two and so on. I managed to solve that, but your solution above seems like a better alternative to solving that problem. > def create_widgets(self): > list_chair=[(0, 0), (0, 1), (0, 3), (0, 4), (1,0)] > for row, column in list_chair: > button = tk.Button(self) > command = partial(button_clicked, button) > button["command"] = command > button.grid(row=row, column=column) > command() >As stated above this will result in every chair being green >and having the text '01' It would be better to put the initial colour >and text in your data list and configure each button directly: Is there any difference between a list and a data list? >def create_widgets(self): >list_chair=[(0, 0, '01'), (0, 1, '02'), (0, 3, '03'), (0, 4, '04'), (1, 0, '05')] >for row, column, name in list_chair: >command = partial(button_clicked, button) >button = tk.Button(self, color='green', >command=command, text=name) >button.grid(row=row, column=column) This solution was better than mine since it is possible to place the widgets where you want, which I couldn't do. So, using your suggestions I get this: import tkinter as tk from functools import partial def button_clicked(button): if button["bg"] == "green": button.configure(bg="red") else: button.configure(bg="green") class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): list_chair=[(0, 0, '01'), (0, 1, '02'), (0, 3, '03'), (0, 4, '04'), (1, 0, '05')] for row, column, name in list_chair: command = partial(button_clicked, button) button = tk.Button(self, color='green', command=command, text=name) button.grid(row=row, column=column) root = tk.Tk() root.title("Test") root.geometry("200x200") app = Window(root) root.mainloop() However, nothing happens when I run the program. >This is one of the good habits in programming. Do it step by step. Get >one thing working first before trying to add more features. Its a lot >easier to debug code when you know what you changed to stop it working. Thanks for the suggestions. >Yes, but lets get the UI all done first, then we can add the button >features. UI means user interface, right? >>> You should only ever have one Tk() object in a Tkinter program. >> Why is that? >Because thats how Tkinter expects to work! It builds a tree of all the >windows and widgets in your program. If you have two trees in the same >program it can get very confused about which widget is doing what to >which other widgets, especially if they wind up in different trees!. Alright, I understand. Thanks a lot for the help. Mic From steve at pearwood.info Sat Nov 26 12:41:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 26 Nov 2011 22:41:51 +1100 Subject: [Tutor] How to raise error without the stack trace In-Reply-To: References: <4ED0BC94.1060401@gmail.com> Message-ID: <4ED0D07F.3020607@pearwood.info> Hugo Arts wrote: > On Sat, Nov 26, 2011 at 11:16 AM, Karim wrote: >> Hello, >> >> I want to fire my own exception without having the (useful but ugly in my >> case) stack trace display. >> >> How to modify a Exception type class for that purpose which looks like: >> >> classs MyError(Exception): >> pass >> >> Cheers >> Karim >> > > The stack trace is what happens when an exception is uncaught. You > don't need to modify it. What you want to do is catch the exception, > print it, then, depending on whether you can recover from the error, > possibly do a sys.exit(-1). If you can recover from the error, by all means catch the exception. That's what exceptions are for! But otherwise, please think very, very, VERY carefully before printing an error message and exiting. This is normally the wrong thing to do. Stack traces are useful. They show you exactly what has gone wrong, and where (although sadly not why!). There is very little worse than a "helpful" programmer who turns a sensible, useful stack trace into a useless, stupid message: "An error has occurred" or worse. Perhaps the most sensible example I can think of is this: def main(): # your code goes here... if __name__ == '__main__': try: main() except KeyboardInterupt: # Not an error, so no need for a stack trace. print "operation cancelled by user" sys.exit(1) and that's it. Any other exception is a bug in your code, and so the stack trace should be printed so the user can report it. -- Steven From __peter__ at web.de Sat Nov 26 13:20:41 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Nov 2011 13:20:41 +0100 Subject: [Tutor] Shortening the code References: Message-ID: Mic wrote: [Alan Gauld] > >def create_widgets(self): > >list_chair=[(0, 0, '01'), (0, 1, '02'), > (0, 3, '03'), (0, 4, '04'), > (1, 0, '05')] > >for row, column, name in list_chair: > >command = partial(button_clicked, button) > >button = tk.Button(self, color='green', > >command=command, text=name) > >button.grid(row=row, column=column) [Mic] > This solution was better than mine since it is possible > to place the widgets where you want, which I couldn't do. > > > So, using your suggestions I get this: > > import tkinter as tk > from functools import partial > > def button_clicked(button): > if button["bg"] == "green": > button.configure(bg="red") > else: > button.configure(bg="green") > > class Window(tk.Frame): > def __init__(self, master): > super (Window, self).__init__(master) > self.grid() > self.create_widgets() > > def create_widgets(self): > list_chair=[(0, 0, '01'), (0, 1, '02'), > (0, 3, '03'), (0, 4, '04'), > (1, 0, '05')] > for row, column, name in list_chair: > command = partial(button_clicked, button) > button = tk.Button(self, color='green', > command=command, text=name) > button.grid(row=row, column=column) > > > > > root = tk.Tk() > root.title("Test") > root.geometry("200x200") > app = Window(root) > root.mainloop() > > However, nothing happens when I run the program. Nothing? That's bad. You should see something like $ python3 tmp.py Traceback (most recent call last): File "tmp.py", line 32, in app = Window(root) File "tmp.py", line 14, in __init__ self.create_widgets() File "tmp.py", line 21, in create_widgets command = partial(button_clicked, button) UnboundLocalError: local variable 'button' referenced before assignment Read the last line carefully. At that point in the program flow button is not yet defined. However, if you just swap the lines button = tk.Button(self, color='green', command=command, text=name) command = partial(button_clicked, button) you'll quickly run into another problem: command is not yet defined when you create the button. Try it before you read on! The only way out of the dilemma is to split the task into three steps: - create the button - create the callback - link the callback to the button button = tk.Button(self, color='green', text=name) command = partial(button_clicked, button) button["command"] = command Now you're almost done. There's still one bug left, but it's an easy one and after reading the traceback carefully you should be able to fix it yourself. From alan.gauld at btinternet.com Sat Nov 26 13:34:40 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 26 Nov 2011 12:34:40 +0000 (GMT) Subject: [Tutor] Shortening the code In-Reply-To: References: Message-ID: <1322310880.56180.YahooMailRC@web86707.mail.ird.yahoo.com> > > and text in your data list and configure each button directly: > Is there any difference between a list and a data list? Not really, but a list can handle any kind of data, even functions, objects etc (but they are all types of data too) I was just being specific that I meant the list of data used to configure your widgets. I should probably just have used its name! ################### import tkinter as tk from functools import partial def button_clicked(button): if button["bg"] == "green": button.configure(bg="red") else: button.configure(bg="green") class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): list_chair=[(0, 0, '01'), (0, 1, '02'), (0, 3, '03'), (0, 4, '04'), (1, 0, '05')] for row, column, name in list_chair: command = partial(button_clicked, button) button = tk.Button(self, color='green', command=command, text=name) button.grid(row=row, column=column) root = tk.Tk() root.title("Test") root.geometry("200x200") app = Window(root) root.mainloop() ###################### > However, nothing happens when I run the program. Really? I get an error: Traceback (most recent call last): File "/home/alang/src/Python/chairs.py", line 32, in app = Window(root) File "/home/alang/src/Python/chairs.py", line 14, in __init__ self.create_widgets() File "/home/alang/src/Python/chairs.py", line 21, in create_widgets command = partial(button_clicked, button) UnboundLocalError: local variable 'button' referenced before assignment Which correctly reports that you are using button before it is created. There is also a bug in that the color parameter should, of course, be bg... When I change create_widgets() to: def create_widgets(self): list_chair=[(0, 0, '01'), (0, 1, '02'), (0, 3, '03'), (0, 4, '04'), (1, 0, '05')] for row, column, name in list_chair: button = tk.Button(self, bg='green', text=name) button['command'] = partial(button_clicked, button) button.grid(row=row, column=column) It works as expected Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Sat Nov 26 13:52:01 2011 From: o0MB0o at hotmail.se (Mic) Date: Sat, 26 Nov 2011 13:52:01 +0100 Subject: [Tutor] Shortening the code In-Reply-To: <1322310880.56180.YahooMailRC@web86707.mail.ird.yahoo.com> References: <1322310880.56180.YahooMailRC@web86707.mail.ird.yahoo.com> Message-ID: >Not really, but a list can handle any kind of data, even functions, >objects etc (but they are all types of data too) >I was just being specific that I meant the list of data used to >configure your widgets. I should probably just have used its name! Alright! By the way, it seems like some people favour the use of pastebins, while others don?t, which is the way to go and why? >Really? I get an error: >Traceback (most recent call last): >File "/home/alang/src/Python/chairs.py", line 32, in >app = Window(root) >File "/home/alang/src/Python/chairs.py", line 14, in __init__ >self.create_widgets() >File "/home/alang/src/Python/chairs.py", line 21, in create_widgets >command = partial(button_clicked, button) >UnboundLocalError: local variable 'button' referenced before assignment >Which correctly reports that you are using button before it is created. >There is also a bug in that the color parameter should, of course, >be bg... Strange, I got that error now when I tried to run it just now. But it took like 30 seconds for the error to actually appear. Do you have any idea why this happened? >When I change create_widgets() to: > def create_widgets(self): >list_chair=[(0, 0, '01'), (0, 1, '02'), > (0, 3, '03'), (0, 4, '04'), >(1, 0, '05')] >for row, column, name in list_chair: >button = tk.Button(self, bg='green', text=name) >button['command'] = partial(button_clicked, button) >button.grid(row=row, column=column) >It works as expected Yes it works perfectly fine now. I wonder, in the last section of the code: >button.grid(row=row, column=column) Could I put columnspan in there? Like: Button.grid(row=row, column=column, columnspan=columnspan) That is not necessary to do, I just was curious if that was possible. Also, I have came to the conlcusion that if I should add the textfiles we discussed earlier on, would I somehow put them in the list, list_chair? Assuming you feel that it is time for do this, how do I implement the creation of these text files into the code that we discussed earlier? Thanks for your help and suggestion! Mic -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 26 15:19:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 26 Nov 2011 14:19:19 +0000 Subject: [Tutor] Shortening the code In-Reply-To: References: <1322310880.56180.YahooMailRC@web86707.mail.ird.yahoo.com> Message-ID: On 26/11/11 12:52, Mic wrote: > Alright! By the way, it seems like some people favour the use of pastebins, > while others don?t, which is the way to go and why? I've stated my preference, Steven has stated his, so I guess you need to decide for yourself. However the best bet is not to paste long pieces of code at all, but stick to samples. They are easier to read and therefore more likely to get a reply... > Strange, I got that error now when I tried to run it just now. But it > took like 30 seconds for the error to actually > appear. Do you have any idea why this happened? How are you running the code? From a command prompt or inside an IDE? > Yes it works perfectly fine now. I wonder, in the last section of the code: > >button.grid(row=row, column=column) > Could I put columnspan in there? > Like: > Button.grid(row=row, column=column, columnspan=columnspan) Yes, its an option to grid() use The Python help system(I'm on 2.7) >>> help(Tkinter.Button.grid) yields: Help on method grid_configure in module Tkinter: grid_configure(self, cnf={}, **kw) unbound Tkinter.Button method Position a widget in the parent widget in a grid. Use as options: column=number - use cell identified with given column (starting with 0) columnspan=number - this widget will span several columns in=master - use master to contain this widget in_=master - see 'in' option description ipadx=amount - add internal padding in x direction ipady=amount - add internal padding in y direction padx=amount - add padding in x direction pady=amount - add padding in y direction row=number - use cell identified with given row (starting with 0) rowspan=number - this widget will span several rows sticky=NSEW - if cell is larger on which sides will this widget stick to the cell boundary And then just try it out... > earlier on, would I somehow put them in the list, list_chair? Yes, its just another value. You could use a default like 0 or -1 where you don't want a span. Then in your code test before calling grid: for row, col, span, name in chairs_list: ..... if span == 0: button.grid(row=row,column=col) else: button.grid(row=row,column=col,columnspan=span) > Assuming you feel that it is time for do this, how do I implement the > creation of these text files into the code that we discussed earlier? The easiest way is just to use regular Python data structures in a separate python file. Then you just import that file. So using your chair_list, you would put that in a sepasrate file like: list_chair = [ #row, col, span, name (0, 1, 0, '01'), (0, 2, 0, '02'), (0, 3, 0, '03'), (0, 4, 0, '04'), (1, 1, 2, '05'), (1, 3, 2, '06') ] Assume you call it chair_config.py You can then import the data with from chair_config import list_chair And the rest of your code remains the same. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From roadierich at googlemail.com Sat Nov 26 15:20:39 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 26 Nov 2011 14:20:39 +0000 Subject: [Tutor] How to raise error without the stack trace In-Reply-To: <4ED0D07F.3020607@pearwood.info> References: <4ED0BC94.1060401@gmail.com> <4ED0D07F.3020607@pearwood.info> Message-ID: On 26 November 2011 11:41, Steven D'Aprano wrote: > Hugo Arts wrote: >> >> On Sat, Nov 26, 2011 at 11:16 AM, Karim wrote: >>> >>> Hello, >>> >>> I want to fire my own exception without having the (useful but ugly in my >>> case) stack trace display. >>> >>> How to modify a Exception type class for that purpose which looks like: >>> >>> classs MyError(Exception): >>> ? ? ?pass >>> >>> Cheers >>> Karim >>> >> >> The stack trace is what happens when an exception is uncaught. You >> don't need to modify it. What you want to do is catch the exception, >> print it, then, depending on whether you can recover from the error, >> possibly do a sys.exit(-1). > > If you can recover from the error, by all means catch the exception. That's > what exceptions are for! > > But otherwise, please think very, very, VERY carefully before printing an > error message and exiting. This is normally the wrong thing to do. > > Stack traces are useful. They show you exactly what has gone wrong, and > where (although sadly not why!). There is very little worse than a "helpful" > programmer who turns a sensible, useful stack trace into a useless, stupid > message: > > "An error has occurred" > > or worse. > > Perhaps the most sensible example I can think of is this: > > > def main(): > ? ?# your code goes here... > > > if __name__ == '__main__': > ? ?try: > ? ? ? ?main() > ? ?except KeyboardInterupt: > ? ? ? ?# Not an error, so no need for a stack trace. > ? ? ? ?print "operation cancelled by user" > ? ? ? ?sys.exit(1) > > > and that's it. Any other exception is a bug in your code, and so the stack > trace should be printed so the user can report it. > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Although there's nothing wrong with taking the stack trace and cleaning it up - perhaps dumping it to a logfile, using the Traceback module. Asking your users to send a file (or even automating the process in your except: block is much more user friendly than expecting them to be able to copy and paste from a (potentially hidden, for GUI apps) console. It also ensures you get the entire stack trace, rather than just what they think is useful. -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T.? Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 From o0MB0o at hotmail.se Sat Nov 26 16:08:32 2011 From: o0MB0o at hotmail.se (Mic) Date: Sat, 26 Nov 2011 16:08:32 +0100 Subject: [Tutor] Shortening the code In-Reply-To: References: Message-ID: >> Alright! By the way, it seems like some people favour the use of >> pastebins, >> while others don?t, which is the way to go and why? >I've stated my preference, Steven has stated his, so I guess you need to >decide for yourself. However the best bet is not to paste long pieces of >code at all, but stick to samples. They are easier to read and therefore >more likely to get a reply... Alright, I get it, the safe way would be to just post small pieces of code here. >How are you running the code? >From a command prompt or inside an IDE? I am running it inside an IDLE. Does it matter whether I run it in a command promt or in an IDLE? >> Assuming you feel that it is time for do this, how do I implement the >> creation of these text files into the code that we discussed earlier? >The easiest way is just to use regular Python data structures in a >separate python file. Then you just import that file. So using your >chair_list, you would put that in a sepasrate file like: >list_chair = [ >#row, col, span, name >(0, 1, 0, '01'), >(0, 2, 0, '02'), >(0, 3, 0, '03'), >(0, 4, 0, '04'), >(1, 1, 2, '05'), >(1, 3, 2, '06') >] >Assume you call it chair_config.py >You can then import the data with >from chair_config import list_chair >And the rest of your code remains the same. Yes I understand that :) I think that I was unclear perhaps about what I meant with text files. Therefore I will post an example of my code. While it works fine, I think it would be good if we could implement it into your suggestions! I have marked the part of the code I have been talking about with ########## Here is the code: import tkinter as tk import os FREE="green" OCCUPIED="red" class SeatButton(tk.Button): def __init__(self, master, index): text = "{}".format(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "Germany_France{}.txt".format(index+1) self.occupied = False def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED ################################### text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close ################################### else: self["bg"] = FREE ################################ os.remove(self.filename) ################################# class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root = tk.Tk() root.title("Test") app = Window(root) root.mainloop() As you can see, if button one it pressed it creates a file with the name Germany_France1 and with the contents Germany_France1 . If it is pressed once more, it removes the file. If button two is pressed it creates a file with the name Germany_France2 and with the contents Germany_France2. If it is pressed once more, it removes the file. And so on. I wonder, do you know how I can do this in your piece of code? Is it possible to do without any trouble? While this piece of code is very good, I feel that I have it easier to understand your code. Perhaps it was I who misunderstood you, sorry if that is the case, but otherwise this is what I want the code to do! Thanks! Mic From alan.gauld at btinternet.com Sat Nov 26 17:05:35 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 26 Nov 2011 16:05:35 +0000 (GMT) Subject: [Tutor] Shortening the code In-Reply-To: References: Message-ID: <1322323535.75188.YahooMailRC@web86703.mail.ird.yahoo.com> >> How are you running the code? > I am running it inside an IDLE. Does it matter IDLE sometimes slows things down and can occasionally lock up with Tkinter (probably because it is itself written in Tkinter!). It's usually better and faster to run Tkinter programs from a separate console window. class SeatButton(tk.Button): def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED ################################### text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close ################################### else: self["bg"] = FREE ################################ os.remove(self.filename) ################################# OK, I see. > As you can see, if button one it pressed it creates a file with the name >Germany_France1 > and with the contents Germany_France1 . If it is pressed once more, it removes >the file. > I wonder, do you know how I can do this in your piece of code? What you are doing is fine, I'd leave the button click bit as it is if you really want to create/delete files. As I said originally this is an unusual thing to do but you may have more going on behind the scenes or planned. But normally I would just keep all the data about whether the seats were booked or not in memory and then save it all in one go into a single file at the end of the program. Or, for a long running program, I might store it in a file but I'd use a single file - probably a shelve file. (If you are not familiar with shelves they are special files that act like dictionaries in your code.) HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Sat Nov 26 17:16:28 2011 From: o0MB0o at hotmail.se (Mic) Date: Sat, 26 Nov 2011 17:16:28 +0100 Subject: [Tutor] Shortening the code In-Reply-To: <1322323535.75188.YahooMailRC@web86703.mail.ird.yahoo.com> References: <1322323535.75188.YahooMailRC@web86703.mail.ird.yahoo.com> Message-ID: >IDLE sometimes slows things down and can occasionally lock >up with Tkinter (probably because it is itself written in Tkinter!). >It's usually better and faster to run Tkinter programs from a separate >console window. Okay, as a console window I assume the CMD terminal is OK? >What you are doing is fine, I'd leave the button click bit as it is if you really want to >create/delete files. As I said originally this is an unusual thing to do but you may >have more going on behind the scenes or planned. Yes, I actually have one more thing going on before I feel it is time to wrap the program up. I will first post the entire program here, (not a lot of code) and then ask the question. from tkinter import* import tkinter as tk import os FREE = "green" OCCUPIED = "red" class Mainwindow(Frame): def __init__(self,master): super(Mainwindow,self).__init__(master) self.grid() self.create_mainwidgets() def create_mainwidgets(self): self.klicka=Button(self, text="Press the button", command=self.uppdatera) self.klicka.grid() def uppdatera(self): class SeatButton(tk.Button): def __init__(self, master, index): text = "{}".format(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "Germany_France{}.txt".format(index+1) self.occupied = False def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close else: self["bg"] = FREE os.remove(self.filename) class Window(tk.Frame): def __init__(self, master): super (Window, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root = tk.Tk() root.title("Test") app = Window(root) root.mainloop() root=Tk() root.title("testV2") app=Mainwindow(root) root.mainloop() If you press the button in the first window, a new window open with all the ?seats?. Say that you press one of the buttons so that it turns red. Then you exit this window and are back in the first one. If you press the button in the window, the window with the ?seats? open. However, the buttons that were red when I exited the window is green! How can I make the be the same color they were when I closed the window with the ?seats?? Also, I am aware of the fact that I shouldn?t be using more than one tk() object, I am working on correcting that right now! Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Nov 26 17:40:18 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 26 Nov 2011 17:40:18 +0100 Subject: [Tutor] Shortening the code References: Message-ID: Mic wrote: > text_file.close It has to be text_file.close() to actually do something. > text_file=open(self.filename,"w") > text_file.write(self.filename) > text_file.close() Pro-tip: this can be simplified to with open(self.filename, "w") as text_file: text_file.write(self.filename) From alan.gauld at btinternet.com Sun Nov 27 01:41:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Nov 2011 00:41:52 +0000 Subject: [Tutor] Shortening the code In-Reply-To: References: <1322323535.75188.YahooMailRC@web86703.mail.ird.yahoo.com> Message-ID: On 26/11/11 16:16, Mic wrote: > I will first post the entire program here, (not a lot of code) > and then ask the question. <---snipped ---> > If you press the button in the first window, a new window open with all > the ?seats?. > Say that you press one of the buttons so that it turns red. Then you > exit this window and are back in the first one. > If you press the button in the window, the window with the ?seats? open. > However, the buttons that were red when I exited the window is green! That's right, because your SeatButton init doesn't check to see if a file exists for it, it always colors it green. You need to read the directory and see whether a file for that seat exists. If it does color it red. (Hint: look at os.path.exists() ) > Also, I am aware of the fact that I shouldn?t be using more than one > tk() object, I am working on correcting that right now! This is one case where I think it will be easier to show you than tell you so I've pasted my modified version of your code. Note that I've moved all the clsses to the outer level and made the second window(which I've renamed SeatWindow) inherit from Toplevel rather than Frame so that you can create it as a child of the Mainwindow. That then allows a single mainloop. It will be worth while studying the differences to see if you understand why I've done what I've done. There is still quite a lot could be done to tidy it up but let's get the buttons working right first.... ################################### from tkinter import* import tkinter as tk import os FREE = "green" OCCUPIED = "red" class Mainwindow(Frame): def __init__(self,master): super(Mainwindow,self).__init__(master) self.grid() self.create_mainwidgets() def create_mainwidgets(self): self.klicka=Button(self, text="Press the button", command=self.uppdatera) self.klicka.grid() def uppdatera(self): SeatWindow(root) class SeatButton(tk.Button): def __init__(self, master, index): text = str(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "Germany_France{}.txt".format(index+1) self.occupied = False def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close() else: self["bg"] = FREE os.remove(self.filename) class SeatWindow(tk.Toplevel): def __init__(self, master): super (SeatWindow, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root=Tk() root.title("testV2") app=Mainwindow(root) root.mainloop() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chare at labr.net Sun Nov 27 07:04:27 2011 From: chare at labr.net (Chris Hare) Date: Sun, 27 Nov 2011 00:04:27 -0600 Subject: [Tutor] Tkinter grid manager question Message-ID: <22C78D65-8C58-447A-92C5-F2D72B6B87CD@labr.net> Hi everyone. I am attempting to create a form for the user to complete. I have the basic layout and supporting code working, but I am having a problem with getting things to display in the grid the way I want them. self.label1 = Label(self.frame, text = "Double click on a name from the list in the right. Make your changes in the field below and press the Save button.", fg="Blue", bg=backColor) self.label2 = Label(self.frame, text = "Current Animal Types", fg="Blue", bg=backColor) ?... self.label1.grid(row=1, column=0,columnspan=3, sticky=W) self.label2.grid(row=2, column=0,columnspan=1, sticky=W) self.list.grid(row=2, column=3, columnspan=2, sticky=W) self.label3.grid(row=3, column=0,columnspan=1, sticky=W) My problem is that the cell which contains the text for label2 is the same size as the text in label1. What I am trying to accomplish is to have the text in label1 span the entire window, instead of having a huge cell with all of the label1 text in it. Ideas? Thanks! Chris From __peter__ at web.de Sun Nov 27 10:19:38 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Nov 2011 10:19:38 +0100 Subject: [Tutor] Tkinter grid manager question References: <22C78D65-8C58-447A-92C5-F2D72B6B87CD@labr.net> Message-ID: Chris Hare wrote: > I am attempting to create a form for the user to complete. I have the > basic layout and supporting code working, but I am having a problem with > getting things to display in the grid the way I want them. > > self.label1 = Label(self.frame, text = "Double > click on a name from the list in the right. Make > your changes in the field below and press the Save > button.", fg="Blue", bg=backColor) self.label2 = > Label(self.frame, text = "Current Animal Types", > fg="Blue", bg=backColor) > ?... > self.label1.grid(row=1, column=0,columnspan=3, sticky=W) > self.label2.grid(row=2, column=0,columnspan=1, sticky=W) > self.list.grid(row=2, column=3, columnspan=2, sticky=W) > self.label3.grid(row=3, column=0,columnspan=1, sticky=W) > > My problem is that the cell which contains the text for label2 is the same > size as the text in label1. What I am trying to accomplish is to have the > text in label1 span the entire window, instead of having a huge cell with > all of the label1 text in it. > > Ideas? Columns are indexed from 0 to n-1, the rightmost column in the code above is 3 for the list widget, so you have 4 columns already. Add another column for the list widget's columnspan=2 and you end up with 5 columns in total. Therefore self.label1.grid(row=1, column=0, columnspan=5, sticky=W) should accomplish the desired layout. From ma_development at hotmail.com Sun Nov 27 10:45:01 2011 From: ma_development at hotmail.com (Mario Cavett) Date: Sun, 27 Nov 2011 04:45:01 -0500 Subject: [Tutor] Take a look at this... Message-ID: Hola. finally my aunt gave me a push in the right direction this turned my luck around now im making my way to the top I promise youll love it http://gabfair.com/profile/29DavidScott/ see you later -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Sun Nov 27 12:03:51 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 27 Nov 2011 12:03:51 +0100 Subject: [Tutor] how to delete some quasi-duplicated keys In-Reply-To: References: <4ECF5A85.4040901@pearwood.info> <4ECF79C0.7090104@pearwood.info> <4ECFC727.6030708@gmx.net> Message-ID: <4ED21917.701@gmx.net> On 2011-11-26 03:49, lina wrote: > > for k, v in occurence.items(): > print(v,k) > > 292 frozenset({66, 69}) > 222 frozenset({24, 27}) > > > How can I let the result like: > > 292 {66,69} > 222 {24,27} > > don't output the frozenset If you want to use your own output format you have to provide it. For example, you could use a combination of string formatting and ".join()" to get what you want: for k, v in occurence.items(): print("{0} {{{1}}}".format(v, ",".join([str(x) for x in k]))) Bye, Andreas From kliateni at gmail.com Sun Nov 27 13:11:58 2011 From: kliateni at gmail.com (Karim) Date: Sun, 27 Nov 2011 13:11:58 +0100 Subject: [Tutor] How to raise error without the stack trace In-Reply-To: References: <4ED0BC94.1060401@gmail.com> <4ED0D07F.3020607@pearwood.info> Message-ID: <4ED2290E.2020104@gmail.com> Le 26/11/2011 15:20, Rich Lovely a ?crit : > On 26 November 2011 11:41, Steven D'Aprano wrote: >> Hugo Arts wrote: >>> On Sat, Nov 26, 2011 at 11:16 AM, Karim wrote: >>>> Hello, >>>> >>>> I want to fire my own exception without having the (useful but ugly in my >>>> case) stack trace display. >>>> >>>> How to modify a Exception type class for that purpose which looks like: >>>> >>>> classs MyError(Exception): >>>> pass >>>> >>>> Cheers >>>> Karim >>>> >>> The stack trace is what happens when an exception is uncaught. You >>> don't need to modify it. What you want to do is catch the exception, >>> print it, then, depending on whether you can recover from the error, >>> possibly do a sys.exit(-1). >> If you can recover from the error, by all means catch the exception. That's >> what exceptions are for! >> >> But otherwise, please think very, very, VERY carefully before printing an >> error message and exiting. This is normally the wrong thing to do. >> >> Stack traces are useful. They show you exactly what has gone wrong, and >> where (although sadly not why!). There is very little worse than a "helpful" >> programmer who turns a sensible, useful stack trace into a useless, stupid >> message: >> >> "An error has occurred" >> >> or worse. >> >> Perhaps the most sensible example I can think of is this: >> >> >> def main(): >> # your code goes here... >> >> >> if __name__ == '__main__': >> try: >> main() >> except KeyboardInterupt: >> # Not an error, so no need for a stack trace. >> print "operation cancelled by user" >> sys.exit(1) >> >> >> and that's it. Any other exception is a bug in your code, and so the stack >> trace should be printed so the user can report it. >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > Although there's nothing wrong with taking the stack trace and > cleaning it up - perhaps dumping it to a logfile, using the Traceback > module. Asking your users to send a file (or even automating the > process in your except: block is much more user friendly than > expecting them to be able to copy and paste from a (potentially > hidden, for GUI apps) console. It also ensures you get the entire > stack trace, rather than just what they think is useful. > Sorry, I did not explain myself clearly. I Kow when I fired it because it is in code like: If not value: raise MyError('You did wrong here!') And in that case I did not want the stack trace because I know perfectly where the message is triggered. To avoid stack trace in try/except I use print(e) then sys.exit(1) or return 1. I just wanted to know if it is possible to control the stack trace display when raising my own exception. And sure, Steven I hate message like 'Problem happens exitting...'. My error messages are acute I just wanted to filter the stack trace. Thanks all for you answers. Cheers Karim From o0MB0o at hotmail.se Sun Nov 27 13:17:17 2011 From: o0MB0o at hotmail.se (Mic) Date: Sun, 27 Nov 2011 13:17:17 +0100 Subject: [Tutor] Shorten this code In-Reply-To: References: Message-ID: God morning! >That's right, because your SeatButton init doesn't check to see if a >file exists for it, it always colors it green. You need to read the >directory and see whether a file for that seat exists. If it does >color it red. (Hint: look at os.path.exists() ) Alright, I think I now managed to solve this problem. Here is the code: from tkinter import* import tkinter as tk import os FREE = "green" OCCUPIED = "red" class Mainwindow(Frame): def __init__(self,master): super(Mainwindow,self).__init__(master) self.grid() self.create_mainwidgets() def create_mainwidgets(self): self.klicka=Button(self, text="Press the button", command=self.uppdatera) self.klicka.grid() def uppdatera(self): SeatWindow(root) class SeatButton(tk.Button): def __init__(self, master, index): text = str(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "Germany_France{}.txt".format(index+1) self.occupied = False if os.path.exists(self.filename): self["bg"]=OCCUPIED def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close() else: self["bg"] = FREE os.remove(self.filename) class SeatWindow(tk.Toplevel): def __init__(self, master): super (SeatWindow, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root=Tk() root.title("testV2") app=Mainwindow(root) root.mainloop() >This is one case where I think it will be easier to show you than tell >you so I've pasted my modified version of your code. Note that I've >moved all the clsses to the outer level and made the second window(which >I've renamed SeatWindow) inherit from Toplevel rather than Frame so that >you can create it as a child of the Mainwindow. That then allows a >single mainloop. It will be worth while studying the differences to see >if you understand why I've done what I've done. >>Yeah, well, the main difference I can see is that you only uses one tk >>object while I used more. Hmm, otherwise I can see that you have bound the >>button in the main window to the function def uppdatera(self): SeatWindow(root) which opens the SeatWindow right? I probably missed things, but I noticed that this is much smoother than my alternative! Thanks ! Mic From __peter__ at web.de Sun Nov 27 13:53:09 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 27 Nov 2011 13:53:09 +0100 Subject: [Tutor] Shorten this code References: Message-ID: Mic wrote: > class SeatButton(tk.Button): > def __init__(self, master, index): > text = str(index+1) > super(SeatButton, self).__init__(master, > text=text, bg=FREE, > command=self.clicked) > self.filename = "Germany_France{}.txt".format(index+1) > self.occupied = False > if os.path.exists(self.filename): > self["bg"]=OCCUPIED In the above snippet button color and the occupied-flag can get out of sync. If a seat is occupied the color is correcly updated to red bot the self.occupied remains False. A simple fix: self.occupied = os.path.exists(self.filename) if self.occupied: self["bg"] = OCCUPIED From suryak at live.com Sun Nov 27 14:52:07 2011 From: suryak at live.com (surya k) Date: Sun, 27 Nov 2011 19:22:07 +0530 Subject: [Tutor] Writing Game in python Message-ID: Hi, Actually, I want to develop a multiplayer Bingo game. So, I would like to develop it in python & C. As I am not familiar with game development, could you please tell me what libraries I should use for development?... etc -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sun Nov 27 15:05:46 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 27 Nov 2011 08:05:46 -0600 Subject: [Tutor] Writing Game in python In-Reply-To: References: Message-ID: On Sun, Nov 27, 2011 at 7:52 AM, surya k wrote: > Hi, > > > Actually, I want to develop a multiplayer Bingo game. So, I would like to > develop it in python & C. As I am not familiar with game development, could > you please tell me what libraries I should use for development?... etc > You could easily develop the game entirely in Python. As for libraries... well it depends on what you're trying to do. If you want a GUI you'll want to look at one of the frameworks like Tkinter, PyGTK+, wxPython, or QtPython. Alternatively you could look at the PyGame library which is geared towards game development. If you want to do internet communication, you'll want to investigate the socket module, and possibly the threading module. How familiar are you with Python? Have you written any programs before? What would really help is if you gave us some psuedocode of your algorithm or the steps you think each piece should need to accomplish. We like to see that you've at least tried to do something. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Sun Nov 27 16:14:29 2011 From: suryak at live.com (surya k) Date: Sun, 27 Nov 2011 20:44:29 +0530 Subject: [Tutor] Writing Game in python In-Reply-To: References: , Message-ID: Thanks for your reply. Actually, I am good at writing code in C and still learning python(Familiar with basics). Now, I am much inclined towards python than C and trying to use it more. I love it. Coming back to the game I want to develop.. I didn't put any code yet but I finished with the algorithm part. All I can tell you is.. Its a small board game, Bingo!. Its typical game we seldom use to play in school on a piece of paper. From: waynejwerner at gmail.com Date: Sun, 27 Nov 2011 08:05:46 -0600 Subject: Re: [Tutor] Writing Game in python To: suryak at live.com CC: tutor at python.org On Sun, Nov 27, 2011 at 7:52 AM, surya k wrote: Hi, Actually, I want to develop a multiplayer Bingo game. So, I would like to develop it in python & C. As I am not familiar with game development, could you please tell me what libraries I should use for development?... etc You could easily develop the game entirely in Python. As for libraries... well it depends on what you're trying to do. If you want a GUI you'll want to look at one of the frameworks like Tkinter, PyGTK+, wxPython, or QtPython. Alternatively you could look at the PyGame library which is geared towards game development. If you want to do internet communication, you'll want to investigate the socket module, and possibly the threading module. How familiar are you with Python? Have you written any programs before? What would really help is if you gave us some psuedocode of your algorithm or the steps you think each piece should need to accomplish. We like to see that you've at least tried to do something. HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Sun Nov 27 16:16:17 2011 From: suryak at live.com (surya k) Date: Sun, 27 Nov 2011 20:46:17 +0530 Subject: [Tutor] Writing Game in python In-Reply-To: References: , Message-ID: I think I have got enough tail to catch up and start my project..Thanks to all who have spared some time to help me. From: waynejwerner at gmail.com Date: Sun, 27 Nov 2011 08:05:46 -0600 Subject: Re: [Tutor] Writing Game in python To: suryak at live.com CC: tutor at python.org On Sun, Nov 27, 2011 at 7:52 AM, surya k wrote: Hi, Actually, I want to develop a multiplayer Bingo game. So, I would like to develop it in python & C. As I am not familiar with game development, could you please tell me what libraries I should use for development?... etc You could easily develop the game entirely in Python. As for libraries... well it depends on what you're trying to do. If you want a GUI you'll want to look at one of the frameworks like Tkinter, PyGTK+, wxPython, or QtPython. Alternatively you could look at the PyGame library which is geared towards game development. If you want to do internet communication, you'll want to investigate the socket module, and possibly the threading module. How familiar are you with Python? Have you written any programs before? What would really help is if you gave us some psuedocode of your algorithm or the steps you think each piece should need to accomplish. We like to see that you've at least tried to do something. HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mylesbroomes at hotmail.co.uk Sun Nov 27 17:28:42 2011 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sun, 27 Nov 2011 16:28:42 +0000 Subject: [Tutor] Random order program Message-ID: Im trying to make a program where the user enters 5 words and then the list of words a is returned in a random order. Heres the code I have come up with so far: #random word order program #the user gives the program a list of words #the program then returns them in a random order import random #explain the purpose of the program to the user print("At the prompt, type in a list of words and they will be returned in a random order.") #get the users input for the list of words, one by one first_word = input("Please enter your first word: ") second_word = input("Please enter your second word: ") third_word = input("Please enter your third word: ") fourth_word = input("Please enter your fourth word: ") fifth_word = input("Please enter your fifth word: ") #create a tuple containing the users words of the words word_list = (first_word,second_word,third_word,fourth_word,fifth_word) #create an empty list that the words will go into to be returned in a random order random_word_list = [] print("Now your list will be displayed in a random order.") #random order list while random_word_list != len(word_list): word = random.choice(word_list) if word not in random_word_list: random_word_list += word #display the random word list print(random_word_list) input("Press enter to exit...") When I run the program, this is what is displayed: At the prompt, type in a list of words and they will be returned in a random order. Please enter your first word: one Please enter your second word: two Please enter your third word: three Please enter your fourth word: four Please enter your fifth word: five Now your list will be displayed in a random order. ...And then nothing happens after that - no error, no nothing. Any help would be much appreciated. Thanks in advance. From alan.gauld at btinternet.com Sun Nov 27 17:32:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Nov 2011 16:32:16 +0000 Subject: [Tutor] Writing Game in python In-Reply-To: References: Message-ID: On 27/11/11 13:52, surya k wrote: > Actually, I want to develop a multiplayer Bingo game. When you say multiplayer do you mean many client desktops or a web game? The solutions will be very different. > to develop it in python & C. Since Bingo is not a high speed game Python should be perfectly capable of doing all you need. > could you please tell me what libraries I should > use for development?... etc If its desktop based look at pyGame for the game bits(obviously!) and Twisted for the networking bits. Twisted is quite a complex framework but very powerful and once you get your head around it perfect for your needs. If it's a web game then Django or some of the other Python web frameworks will do all you need. Take a look at the various web pages and FAQs on the Python web site before choosing a framework. Consider whether you need database support, security features, etc etc. Some are better in those areas than others. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Nov 27 17:36:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 27 Nov 2011 16:36:54 +0000 Subject: [Tutor] How to raise error without the stack trace In-Reply-To: <4ED2290E.2020104@gmail.com> References: <4ED0BC94.1060401@gmail.com> <4ED0D07F.3020607@pearwood.info> <4ED2290E.2020104@gmail.com> Message-ID: On 27/11/11 12:11, Karim wrote: > I just wanted to know if it is possible to control the stack trace > display when raising my own exception. No, and you should not try. You can control the stacktrace display where you catch it, but not where you raise it. And that's the point, you are raising it because you don't want to handle it there. You are expecting the user to deal with the error, including how it is displayed. Peter has already showed you how to do that by overridding the standard exception hook sys.excepthook.. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From o0MB0o at hotmail.se Sun Nov 27 17:58:11 2011 From: o0MB0o at hotmail.se (Mic) Date: Sun, 27 Nov 2011 17:58:11 +0100 Subject: [Tutor] How to use try and except in this case? In-Reply-To: References: Message-ID: Mic wrote: >> class SeatButton(tk.Button): >> def __init__(self, master, index): >> text = str(index+1) >> super(SeatButton, self).__init__(master, >> text=text, bg=FREE, >> command=self.clicked) >> self.filename = "Germany_France{}.txt".format(index+1) >> self.occupied = False >> if os.path.exists(self.filename): >> self["bg"]=OCCUPIED >In the above snippet button color and the occupied-flag can get out of >sync. >If a seat is occupied the color is correcly updated to red bot the >self.occupied remains False. >A simple fix: >self.occupied = os.path.exists(self.filename) >if self.occupied: >self["bg"] = OCCUPIED Thanks! Say that I want to try and open 10 files. If none of these exists, I want an error message to appear. But only if NONE of these files exists. I know how to handle this with one file. But I don't know how to do that with more than one. So the program should try and open all 10 files and if, and only if, none of the files exists I want en error message to appear. Thanks for your help guys! From bgailer at gmail.com Sun Nov 27 18:59:24 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 27 Nov 2011 12:59:24 -0500 Subject: [Tutor] Random order program In-Reply-To: References: Message-ID: <4ED27A7C.2020607@gmail.com> On 11/27/2011 11:28 AM, myles broomes wrote: > Im trying to make a program where the user enters 5 words and then the list of words a is returned in a random order. Heres the code I have come up with so far: > > #random word order program > #the user gives the program a list of words > #the program then returns them in a random order > > import random > > #explain the purpose of the program to the user > print("At the prompt, type in a list of words and they will be returned in a random order.") > > #get the users input for the list of words, one by one > first_word = input("Please enter your first word: ") > second_word = input("Please enter your second word: ") > third_word = input("Please enter your third word: ") > fourth_word = input("Please enter your fourth word: ") > fifth_word = input("Please enter your fifth word: ") > > #create a tuple containing the users words of the words > word_list = (first_word,second_word,third_word,fourth_word,fifth_word) > > #create an empty list that the words will go into to be returned in a random order > random_word_list = [] > > print("Now your list will be displayed in a random order.") > > #random order list > while random_word_list != len(word_list): > word = random.choice(word_list) > if word not in random_word_list: > random_word_list += word > > #display the random word list > print(random_word_list) > > input("Press enter to exit...") > > When I run the program, this is what is displayed: > > At the prompt, type in a list of words and they will be returned in a random order. > Please enter your first word: one > Please enter your second word: two > Please enter your third word: three > Please enter your fourth word: four > Please enter your fifth word: five > Now your list will be displayed in a random order. > > > ...And then nothing happens after that - no error, no nothing. random_word_list != len(word_list) will always be true. Therefore the loop will never end. What should that expression be? See if you can figure out why it is always true and what to change to get the desired result. In theory the loop could run for a long time, as you could get an arbitrarily long run of words that are already in the random_word_list. How could you fix that? There are any number of ways to simplify and improve the program. Are you interested in hearing about them? For one study the functions in the random module. -- Bob Gailer 919-636-4239 Chapel Hill NC From suryak at live.com Sun Nov 27 19:52:00 2011 From: suryak at live.com (surya k) Date: Mon, 28 Nov 2011 00:22:00 +0530 Subject: [Tutor] How to handle conjunction operators Message-ID: Hi, Could you please tell me why this isn't working and how can I make it possible... Consider this code..name = raw_input("Enter your first name: ") if name[0] == ("m" or "f" or "b") : rhyme = name[1:]What I want here is.. If the name starts with 'm' or 'f' or 'b', The first letter should be removed.But this isn't happening here. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Nov 27 20:02:58 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 27 Nov 2011 20:02:58 +0100 Subject: [Tutor] How to handle conjunction operators In-Reply-To: References: Message-ID: On Sun, Nov 27, 2011 at 7:52 PM, surya k wrote: > Hi, > Could you please tell me why this isn't working and how can I make it > possible... > Consider this code.. > > name = raw_input("Enter your first name: ") > if name[0] == ("m" or "f" or "b") : > rhyme = name[1:] > > What I want here is.. If the name starts with 'm' or 'f' or 'b', The first > letter should be removed. > But this isn't happening here. This is a very common error. Fact is, the or operator just isn't distributive with respect to the == operator like that, and for good reason. What you want is either this: if name[0] == "m" or name[0] == "f" or name[0] == "b": or, more idiomatically, you can use the in operator like this: if name[0] in ("m", "f", "b"): HTH, Hugo From andreas.perstinger at gmx.net Sun Nov 27 21:38:15 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 27 Nov 2011 21:38:15 +0100 Subject: [Tutor] How to use try and except in this case? In-Reply-To: References: Message-ID: <4ED29FB7.80108@gmx.net> On 2011-11-27 17:58, Mic wrote: > Say that I want to try and open 10 files. If none of these exists, I want an > error > message to appear. But only if NONE of these files exists. > > I know how to handle this with one file. But I don't know how to do that > with more than one. > So the program should try and open all 10 files and if, and only if, none > of the files exists I want en error message to appear. Use a counter which increments with every existing file. After opening all files check if the counter is bigger than 0. Or, if you need to know which files exist, use a list, append existing files to it and check at the end if it's not empty. Do you need more help? Bye, Andreas From denawilson33 at gmail.com Sun Nov 27 21:45:30 2011 From: denawilson33 at gmail.com (Deanna Wilson) Date: Sun, 27 Nov 2011 12:45:30 -0800 Subject: [Tutor] Parsing Message-ID: Project 4: Parsing rhinoceros sightings In this project, I?m working for a wildlife conservation group that is tracking rhinos in the African savannah. My field workers' software resources and GIS expertise are limited, but you have managed to obtain an Excel spreadsheetshowing the positions of several rhinos over time. Each record in the spreadsheet shows the latitude/longitude coordinate of a rhino along with the rhino's name (these rhinos are well known to your field workers). I want to write a script that will turn the readings in the spreadsheet into a vector dataset that I can place on a map. This will be a polyline dataset showing the tracks the rhinos followed over the time the data was collected. I will deliver: A Python script that reads the data from the spreadsheet and creates, from scratch, a polyline shapefile with *n* polylines, *n* being the number of rhinos in the spreadsheet. Each polyline should represent a rhino's track chronologically from the beginning of the spreadsheet to the end of the spreadsheet. Each polyline should also have a text attribute containing the rhino's name. The shapefile should use the WGS 1984 geographic coordinate system. *Challenges* The data is in a format (XLSX) that you cannot easily parse. The first step I must do is manually open the file in Excel and save it as a comma-delimited format that I can easily read with a script. Choose the option *CSV (comma-delimited) (*.csv)*. I did this - The rhinos in the spreadsheet appear in no guaranteed order, and not all the rhinos appear at the beginning of the spreadsheet. As I parse each line, I must determine which rhino the reading belongs to and update that rhino's polyline track accordingly. *I am not allowed to sort the Rhino column in Excel before I export to the CSV file. My script must be "smart" enough to work with an unsorted spreadsheet in the order that the records appear.* - I do not immediately know how many rhinos are in the file or even what their names are. Although I could visually comb the spreadsheet for this information and hard-code each rhino's name, your script is required to handle all the rhino names programmatically. The idea is that I should be able to run this script on a different file, possibly containing more rhinos, without having to make many manual adjustments. sample of my code: import arcpy shapefile = "C:\\...shp" pointFilePath = "C:\\...csv" pointFile = open(pointFilePath, "r") lineOfText = pointFile.readline() dataPairList = lineOfText.split(",") def addVertex(lat, lon, array): vertex = arcpy.CreateObject("Point") vertex.X = lon vertex.Y = lat array.add(vertex) def addPolyline(cursor, array): feature = cursor.newRow() feature.shape = array cursor.insertRow(feature) array.removeAll() def rhinoName(Rhino, dictionary): if rhinoName in rhinoDictionary: dictionary[rhinoName].append([latValue, lonValueIndex]) if rhinoName not in dictionary: dictionary[rhinoName] = [] else: dictionary[rhinoName]= ([latValue, lonValue]) latValueIndex = dataPairList.index("X") lonValueIndex = dataPairList.index("Y") vertexArray = arcpy.CreateObject("Array") for line in pointFile.readlines(): segmentedLine = line.split(",") latValue = segmentedLine[latValueIndex] lonValue = segmentedLine[lonValueIndex] vertex = arcpy.CreateObject("Point") vertex.X = lonValue vertex.Y = latValue vertexArray.add(vertex) polylineArray.add(currentPoint) cursor = arcpy.InsertCursor(shapefile) row = cursor.newRow() row.Shape = vertexArray cursor.insertRow(row) del cursor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Nov 27 22:04:21 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 27 Nov 2011 16:04:21 -0500 Subject: [Tutor] How to handle conjunction operators In-Reply-To: References: Message-ID: <4ED2A5D5.3030809@gmail.com> On 11/27/2011 1:52 PM, surya k wrote: > Hi, > > Could you please tell me why this isn't working and how can I make it > possible... > > Consider this code.. name = raw_input("Enter your first name: ") if name[0] == ("m" or "f" or "b") : rhyme = name[1:] > What I want here is.. If the name starts with 'm' or 'f' or 'b', The > first letter should be removed. > But this isn't happening here. Hugh answered your question. PLEASE in future post in plain text rather than HTML. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Nov 27 22:09:59 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 27 Nov 2011 16:09:59 -0500 Subject: [Tutor] How to handle conjunction operators In-Reply-To: References: Message-ID: <4ED2A727.2020106@gmail.com> On 11/27/2011 1:52 PM, surya k wrote: > Hi, > > Could you please tell me why this isn't working and how can I make it > possible... > > Consider this code.. name = raw_input("Enter your first name: ") if name[0] == ("m" or "f" or "b") : rhyme = name[1:] > What I want here is.. If the name starts with 'm' or 'f' or 'b', The > first letter should be removed. > But this isn't happening here. Hugh answered your question. I add - let's analyze name[0] == ("m" or "f" or "b") "m" or "f" or "b" gets evaluated first. The result is "m" (the first non-false value) then name[0] == "m" gets evaluated, which may be true or false. the shortest way is name[0] in "mfb" -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Nov 27 22:46:22 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 27 Nov 2011 16:46:22 -0500 Subject: [Tutor] Parsing In-Reply-To: References: Message-ID: <4ED2AFAE.1030403@gmail.com> Welcome to the Tutor List. We are a few volunteers who enjoy tutoring folk on specific Python learning issues. We like posts that are in plain text rather than HTML. Please post plain text in future. Also your code has a blank line between every LOC, Please remove these in future posts I failed to see any specific request in your post so all I can say is welcome and how can we help you. Did you run the code? Did you get errors or unexpected results? Please report these. Errors usually appear as a traceback. Include the entire traceback (after putting in some effort to figure out the error on your own). unexpected results? Tell us what you expected and how the results differ. Good luck! On 11/27/2011 3:45 PM, Deanna Wilson wrote: > Project 4: Parsing rhinoceros sightings > > In this project, I'm working for a wildlife conservation group that > is tracking rhinos in the African savannah. My field workers' > software resources and GIS expertise are limited, but you have managed > to obtain an Excel spreadsheet > > showing the positions of several rhinos over time. Each record in the > spreadsheet shows the latitude/longitude coordinate of a rhino along > with the rhino's name (these rhinos are well known to your field workers). > > I want to write a script that will turn the readings in the > spreadsheet into a vector dataset that I can place on a map. This will > be a polyline dataset showing the tracks the rhinos followed over the > time the data was collected. > > I will deliver: > > A Python script that reads the data from the spreadsheet and creates, > from scratch, a polyline shapefile with n polylines, n being the > number of rhinos in the spreadsheet. Each polyline should represent a > rhino's track chronologically from the beginning of the spreadsheet to > the end of the spreadsheet. Each polyline should also have a text > attribute containing the rhino's name. The shapefile should use the > WGS 1984 geographic coordinate system. > > Challenges > > The data is in a format (XLSX) that you cannot easily parse. The first > step I must do is manually open the file in Excel and save it as a > comma-delimited format that I can easily read with a script. Choose > the option CSV (comma-delimited) (*.csv). I did this > > * The rhinos in the spreadsheet appear in no guaranteed order, and > not all the rhinos appear at the beginning of the spreadsheet. As > I parse each line, I must determine which rhino the reading > belongs to and update that rhino's polyline track accordingly. I > am not allowed to sort the Rhino column in Excel before I export > to the CSV file. My script must be "smart" enough to work with an > unsorted spreadsheet in the order that the records appear. > * I do not immediately know how many rhinos are in the file or even > what their names are. Although I could visually comb the > spreadsheet for this information and hard-code each rhino's name, > your script is required to handle all the rhino names > programmatically. The idea is that I should be able to run this > script on a different file, possibly containing more rhinos, > without having to make many manual adjustments. > > sample of my code: > > import arcpy > > shapefile = "C:\\...shp" > > pointFilePath = "C:\\...csv" > > pointFile = open(pointFilePath, "r") > > lineOfText = pointFile.readline() > > dataPairList = lineOfText.split(",") > > def addVertex(lat, lon, array): > > vertex = arcpy.CreateObject("Point") > > vertex.X = lon > > vertex.Y = lat > > array.add(vertex) > > def addPolyline(cursor, array): > > feature = cursor.newRow() > > feature.shape = array > > cursor.insertRow(feature) > > array.removeAll() > > def rhinoName(Rhino, dictionary): > > if rhinoName in rhinoDictionary: > > dictionary[rhinoName].append([latValue, lonValueIndex]) > > if rhinoName not in dictionary: > > dictionary[rhinoName] = [] > > else: > > dictionary[rhinoName]= ([latValue, lonValue]) > > latValueIndex = dataPairList.index("X") > > lonValueIndex = dataPairList.index("Y") > > vertexArray = arcpy.CreateObject("Array") > > for line in pointFile.readlines(): > > segmentedLine = line.split(",") > > latValue = segmentedLine[latValueIndex] > > lonValue = segmentedLine[lonValueIndex] > > vertex = arcpy.CreateObject("Point") > > vertex.X = lonValue > > vertex.Y = latValue > > vertexArray.add(vertex) > > polylineArray.add(currentPoint) > > cursor = arcpy.InsertCursor(shapefile) > > row = cursor.newRow() > > row.Shape = vertexArray > > cursor.insertRow(row) > > del cursor > > > > > > _______________________________________________ > 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 andreas.perstinger at gmx.net Sun Nov 27 22:58:49 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sun, 27 Nov 2011 22:58:49 +0100 Subject: [Tutor] Parsing In-Reply-To: References: Message-ID: <4ED2B299.2050206@gmx.net> On 2011-11-27 21:45, Deanna Wilson wrote: > Project 4: Parsing rhinoceros sightings Please confirm that this is homework. At least I've found this site: https://www.e-education.psu.edu/geog485/node/144 [snip] > sample of my code: What are your problems? I've skimmed your sample and found a number of errors. Since your task looks like homework, you should be more specific about your problems. Bye, Andreas From mylesbroomes at hotmail.co.uk Sun Nov 27 23:17:28 2011 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Sun, 27 Nov 2011 22:17:28 +0000 Subject: [Tutor] Random order program Message-ID: I requested help for this code earlier and I thought it had been corrected but apparently, there is still a problem with it... #random word order program #the user gives the program a list of words #the program then returns them in a random order import random #explain the purpose of the program to the user print("At the prompt, type in a list of words and they will be returned in a random order.") #get the users input for the list of words, one by one first_word = input("Please enter your first word: ") second_word = input("Please enter your second word: ") third_word = input("Please enter your third word: ") fourth_word = input("Please enter your fourth word: ") fifth_word = input("Please enter your fifth word: ") #create a tuple containing the users words of the words word_list = (first_word,second_word,third_word,fourth_word,fifth_word) #create an empty list that the words will go into to be returned in a random order random_word_list = [] print("Now your list will be displayed in a random order.") #random order list while len(random_word_list) != len(word_list): word = random.choice(word_list) if word not in random_word_list: random_word_list += word #display the random word list print(random_word_list) input("Press enter to exit...") And once again, the following is displayed.... At the prompt, type in a list of words and they will be returned in a random order. Please enter your first word: one Please enter your second word: two Please enter your third word: three Please enter your fourth word: four Please enter your fifth word: five Now your list will be displayed in a random order. Then the program just stops for some reason. Again, any help is much appreciated. From rhettnaxel at gmail.com Sun Nov 27 23:26:08 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Sun, 27 Nov 2011 17:26:08 -0500 Subject: [Tutor] Blacklist? In-Reply-To: References: Message-ID: <424E8CB2-3B61-42CD-92C5-E186FBF48AF9@gmail.com> I'm top posting because the link below is spam. Does the email address who sent the message get blacklisted or punished? Alexander On Nov 27, 2011, at 4:45, Mario Cavett wrote: > Hola. > finally my aunt gave me a push in the right direction this turned my luck around now im making my way to the top I promise youll love it > http://gabfair.com/profile/29DavidScott/ > see you later > _______________________________________________ > 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 Sun Nov 27 23:55:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Nov 2011 09:55:04 +1100 Subject: [Tutor] Blacklist? In-Reply-To: <424E8CB2-3B61-42CD-92C5-E186FBF48AF9@gmail.com> References: <424E8CB2-3B61-42CD-92C5-E186FBF48AF9@gmail.com> Message-ID: <4ED2BFC8.9000608@pearwood.info> Alexander Etter wrote: > I'm top posting because the link below is spam. Why on earth do you think that it is acceptable to repeat spam on the list just because you top post? If you have to reply to spam, does your backspace key not work? ESPECIALLY the spammer's URL. -- Steven From rhettnaxel at gmail.com Mon Nov 28 00:09:28 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Sun, 27 Nov 2011 18:09:28 -0500 Subject: [Tutor] Blacklist? In-Reply-To: <4ED2BFC8.9000608@pearwood.info> References: <424E8CB2-3B61-42CD-92C5-E186FBF48AF9@gmail.com> <4ED2BFC8.9000608@pearwood.info> Message-ID: <199EE105-0970-4160-AD7F-AC7FB6C1CE86@gmail.com> On Nov 27, 2011, at 17:55, Steven D'Aprano wrote: > Alexander Etter wrote: >> I'm top posting because the link below is spam. > > > Why on earth do you think that it is acceptable to repeat spam on the list just because you top post? > > If you have to reply to spam, does your backspace key not work? ESPECIALLY the spammer's URL. > > -- > Steven > Sorry Steven! I've learned my lesson. Alexander. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From andreas.perstinger at gmx.net Mon Nov 28 00:24:47 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Mon, 28 Nov 2011 00:24:47 +0100 Subject: [Tutor] Random order program In-Reply-To: References: Message-ID: <4ED2C6BF.4000603@gmx.net> On 2011-11-27 23:17, myles broomes wrote: > #get the users input for the list of words, one by one > first_word = input("Please enter your first word: ") > second_word = input("Please enter your second word: ") > third_word = input("Please enter your third word: ") > fourth_word = input("Please enter your fourth word: ") > fifth_word = input("Please enter your fifth word: ") > > #create a tuple containing the users words of the words > word_list = (first_word,second_word,third_word,fourth_word,fifth_word) You could shorten the input procedure by using a for-loop and appending every word to a list instead using five different "word"-variables and building a tuple with them. > #create an empty list that the words will go into to be returned in a random order > random_word_list = [] > > print("Now your list will be displayed in a random order.") > > #random order list > while len(random_word_list) != len(word_list): > word = random.choice(word_list) > if word not in random_word_list: > random_word_list += word Bob told you already that you are creating an infinite-loop. Try this: Python 3.2 (r32:88445, Mar 25 2011, 19:28:28) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l = [] >>> s = "test" >>> l += s >>> l ['t', 'e', 's', 't'] Do you see your problem? You want to "add" a string to a list but with the inplace operator "+=" "word" is interpreted as a sequence (a list of letters). You can't "add" a string to a list: >>> l = l + s Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate list (not "str") to list If you want to add an element to a list you should use the ".append"-method of lists: http://docs.python.org/py3k/tutorial/datastructures.html#more-on-lists Bob mentioned also the problem with your algorithm. Everytime you get a word from "random.choice" which is already in "random_word_list" you have to loop again: >>> counter = 0 >>> random_word_list = [] >>> word_list = ["a", "b", "c", "d", "e"] >>> while len(random_word_list) != len(word_list): ... counter += 1 ... word = random.choice(word_list) ... if word not in random_word_list: ... random_word_list.append(word) ... >>> print(counter) If you are lucky, "counter" is close to the minimum 5. But in one of my test runs it was 25. This is unnecessary because you don't need more iterations than the length of "word_list" (5 in your case) Anyways, there is already a shuffle-method in the "random"-module: docs.python.org/py3k/library/random.html Bye, Andreas From d at davea.name Mon Nov 28 00:25:27 2011 From: d at davea.name (Dave Angel) Date: Sun, 27 Nov 2011 18:25:27 -0500 Subject: [Tutor] Random order program In-Reply-To: References: Message-ID: <4ED2C6E7.6060600@davea.name> On 11/27/2011 05:17 PM, myles broomes wrote: > I requested help for this code earlier and I thought it had been corrected but apparently, there is still a problem with it... > To start with, tell us what version of Python, and what operating system platform you're using. I'm assuming Python 3.x and Linux. In this case the first matters, the second probably does not. > #random word order program > #the user gives the program a list of words > #the program then returns them in a random order > > import random > > #explain the purpose of the program to the user > print("At the prompt, type in a list of words and they will be returned in a random order.") > > #get the users input for the list of words, one by one > first_word = input("Please enter your first word: ") > second_word = input("Please enter your second word: ") > third_word = input("Please enter your third word: ") > fourth_word = input("Please enter your fourth word: ") > fifth_word = input("Please enter your fifth word: ") > > #create a tuple containing the users words of the words > word_list = (first_word,second_word,third_word,fourth_word,fifth_word) > > #create an empty list that the words will go into to be returned in a random order > random_word_list = [] > > print("Now your list will be displayed in a random order.") > > #random order list > while len(random_word_list) != len(word_list): > word = random.choice(word_list) > if word not in random_word_list: > random_word_list += word > If you use += operator with list on the left side, it assumes something compatible with list on the right. So either use random_word_list += [word] Or else use random_word_list.append(word) As it's currently coded, it take each character of the word and adds them to the list, so the list doesn't match the original at all. Next problem you might encounter is if the user doesn't give unique words. If they repeat one of them, the loop will never terminate. You figure out why. > #display the random word list > print(random_word_list) > > input("Press enter to exit...") > > And once again, the following is displayed.... > > At the prompt, type in a list of words and they will be returned in a random order. > Please enter your first word: one > Please enter your second word: two > Please enter your third word: three > Please enter your fourth word: four > Please enter your fifth word: five > Now your list will be displayed in a random order. > > Then the program just stops for some reason. Again, any help is much appreciated. > As others have pointed out, there is at least one function in random that's a better match to your problem. You could collapse the loop to one line, and duplicates wouldn't be an issue. Another approach would be to make a set out of the original input. Duplicates will be thrown out (you might want to tell the user, though). Then you take the set as an argument to the function I just hinted at, and out comes your answer. -- DaveA From andreas.perstinger at gmx.net Mon Nov 28 00:50:10 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Mon, 28 Nov 2011 00:50:10 +0100 Subject: [Tutor] Parsing In-Reply-To: References: <4ED2B299.2050206@gmx.net> Message-ID: <4ED2CCB2.6070900@gmx.net> [Please reply to the list. Your indentation also got lost during the mail delivery.] On 2011-11-27 23:21, Deanna Wilson wrote: > Yes it is homework, but not from Penn state. It is a Geog690 class. I'm > having difficulties with determining where the rhino is referenced in the > split line, determining if the dictionary has a key for the rhino and if no > key exists, creating a new array object. So pretty much writing the > dictionary. I think I got the rest of the script just not understanding the > dictionary portion. I would appreciate any help/advice. > > Here is part of my script where I tried to create a dictionary > > rhinoLocalDictionary = {} > > def rhinoName(Rhino, Lat, Lon, dictionary): > if rhinoName in dictionary: > dictionary[rhinoName].append([Lat, Lon]) > else: > dictionary[rhinoName]= ([Lat, Lon]) You define the function "rhinoName" with the parameter "Rhino" but inside the function you use "rhinoName" which is the function's name. You want to build a list of lists for each dictionary-value. But then you need to start the list with a nested-list in the else-branch. Otherwise your list will start with two elements followed by two-elements lists: >>> d = {} >>> d[1] = [1, 2] >>> d[1].append([3, 4]) >>> d[1] [1, 2, [3, 4]] # That's not what you want >>> d[2] = [[1, 2]] >>> d[2].append([3, 4]) >>> d[2] [[1, 2], [3, 4]] # Better But assuming that your lat/lon-values don't change I would suggest using tuples. HTH, Andreas From alan.gauld at btinternet.com Mon Nov 28 01:35:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Nov 2011 00:35:45 +0000 Subject: [Tutor] How to handle conjunction operators In-Reply-To: References: Message-ID: On 27/11/11 19:02, Hugo Arts wrote: > if name[0] == "m" or name[0] == "f" or name[0] == "b": > > or, more idiomatically, you can use the in operator like this: > > if name[0] in ("m", "f", "b"): And you might want to force it to lower case too: if name[0].lower() in ("m", "f", "b"): OTOH you might want it to be case sensitive... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wtfwhoami at gmail.com Mon Nov 28 01:43:37 2011 From: wtfwhoami at gmail.com (Guess?!?) Date: Sun, 27 Nov 2011 16:43:37 -0800 Subject: [Tutor] Coin game Message-ID: Hello All, I am learning python and hence was writing code for school assignments I could find online. I wrote my solution for this problem below. Please find it attached. I would like someone to review and give me comments on it. Basically improvements/ comments to make it more efficient problem.py has print statements in them. problem_clean is cleaner version of the same. Thanks, G Two players take turns flipping a fair coin. The game ends when the same outcome occurs on three flips in a row. Whichever player flipped the coin last, wins. For example: Player 1 flips H Player 2 flips T Player 1 flips T Player 2 flips H Player 1 flips H Player 2 flips H <<< player 2 wins or Player 1 flips T Player 2 flips T Player 1 flips T <<< player 1 wins or Player 1 flips H Player 2 flips H Player 1 flips T Player 2 flips H Player 1 flips T Player 2 flips H Player 1 flips T Player 2 flips T Player 1 flips H Player 2 flips H Player 1 flips H <<< player 1 wins -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: problem_clean.py Type: application/octet-stream Size: 1656 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: problem.py Type: application/octet-stream Size: 1655 bytes Desc: not available URL: From alan.gauld at btinternet.com Mon Nov 28 01:51:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Nov 2011 00:51:27 +0000 Subject: [Tutor] Parsing In-Reply-To: References: Message-ID: On 27/11/11 20:45, Deanna Wilson wrote: > > Project 4: Parsing rhinoceros sightings OK, You've told us this is homework, and you appear to have made some start but we need some more information. Can you program in any other language other than Python? Which version of Python are you using? Obviously 2.X but which X? Which OS are you running? What is arcpy? It is not one of the standard Python libraries. What is the arrray that you are trying to use? Its not a builtin type in Python and you don;t seem to import it from anywhere? You are obviously allowed to use arcopy, so do we assume you could also use the csv module to process the csv file? Your rhinoName function is badly broken... And addVertex is not used vbut duplicated in the code. Inserting a few print statements at strategic places should help you see what is happening in your code. Now where would you like us to start? > sample of my code: > > import arcpy > > shapefile = "C:\\...shp" > pointFilePath = "C:\\...csv" > pointFile = open(pointFilePath, "r") > lineOfText = pointFile.readline() > dataPairList = lineOfText.split(",") > > def addVertex(lat, lon, array): > vertex = arcpy.CreateObject("Point") > vertex.X = lon > vertex.Y = lat > array.add(vertex) > > def addPolyline(cursor, array): > feature = cursor.newRow() > feature.shape = array > cursor.insertRow(feature) > array.removeAll() > > def rhinoName(Rhino, dictionary): > if rhinoName in rhinoDictionary: > dictionary[rhinoName].append([latValue, lonValueIndex]) > if rhinoName not in dictionary: > dictionary[rhinoName] = [] > else: > dictionary[rhinoName]= ([latValue, lonValue]) > > latValueIndex = dataPairList.index("X") > lonValueIndex = dataPairList.index("Y") > vertexArray = arcpy.CreateObject("Array") > for line in pointFile.readlines(): > segmentedLine = line.split(",") > latValue = segmentedLine[latValueIndex] > lonValue = segmentedLine[lonValueIndex] > vertex = arcpy.CreateObject("Point") > vertex.X = lonValue > vertex.Y = latValue > vertexArray.add(vertex) > polylineArray.add(currentPoint) > > cursor = arcpy.InsertCursor(shapefile) > row = cursor.newRow() > row.Shape = vertexArray > cursor.insertRow(row) > del cursor -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Mon Nov 28 02:27:38 2011 From: d at davea.name (Dave Angel) Date: Sun, 27 Nov 2011 20:27:38 -0500 Subject: [Tutor] Coin game In-Reply-To: References: Message-ID: <4ED2E38A.5040300@davea.name> On 11/27/2011 07:43 PM, Guess?!? wrote: > Hello All, > > I am learning python and hence was writing code for school assignments I > could find online. I wrote my solution for this problem below. Please find > it attached. > > I would like someone to review and give me comments on it. Basically > improvements/ comments to make it more efficient > > problem.py has print statements in them. problem_clean is cleaner version > of the same. > > Thanks, > > G > This program is far too complex for the problem. It doesn't document what the various variables are really supposed to mean, but there are far more of 'em than there really needs to be. Your for-loop doesn't need two separate conditions. You don't care how many iterations it takes, but if you really want to limit to 10, then do a loop: for counter in range(10): then when you want to exit the loop early, use the 'break' statement. And the modulo test can be a simple assignment. If you make player an integer (0 or 1), you can just do: player = counter %2 The next roll can be something like random.choice("H", "T") You also don't care about the history, only the last three values. So seed the list with illegal values, like tracklist = ["*", "*", "*"] then you just add the new roll as: tracklist.pop(0) tracklist.append(random.choice("H","T") Now the if statement only has two choice. Either all 3 are identical, or they're not. If they are, print your "win" message and break. After the loop you could use an else clause to detect the case that the loop finished without a win. Any time you have to print out the player name, you could use something like ["player 1", "player 2"] [player] But of course if you have a list of real names, you'd use that instead of the two literals I gave. If you make it a set of functions, it gets quite small and easier to read. -- DaveA From pritesh.ugrankar at gmail.com Mon Nov 28 08:56:06 2011 From: pritesh.ugrankar at gmail.com (Pritesh Ugrankar) Date: Mon, 28 Nov 2011 13:26:06 +0530 Subject: [Tutor] Text Proccessing/Command Line Redirection/XML Parsing etc in Python. Message-ID: First of all, my apologies for writing this very long post. I have been through some related questions about this in Stack Overflow as well as googled it and found that Perl and Python are the two languages that offer most what I need. As a SAN Administrator, I have a very limited time to learn a scripting language so I can concentrate on only one. Most of my questions below may make you think that I prefer Perl, but its nothing like...Just that I tried learning Perl before for doing stuff I want to try, but am thinking now what advantages will I have if I try out Python? All my SAN Management Servers are Windows only. Following is what I am specifically looking at: 1) Consider the following output: symdev -sid 1234 list devs 0D62 Not Visible ???:? 07C:D13 RAID-5 N/A (DT) RW 187843 0D63 Not Visible ???:? 08C:C11 RAID-5 N/A (DT) RW 187843 0D64 Not Visible ???:? 07C:C12 RAID-5 N/A (DT) RW 62614 0D65 Not Visible ???:? 08C:D14 RAID-5 N/A (DT) RW 62614 0D66 Not Visible ???:? 07C:D15 RAID-5 N/A (DT) RW 31307 0D67 Not Visible ???:? 08C:C13 RAID-5 N/A (DT) RW 31307 0D68 Not Visible ???:? 07C:C14 RAID-5 N/A (DT) RW 31307 Whats given above is only a small part of the output. There are many other fields that appear but I have left those out for brevity. The symdev commands generates a list of devices that can be used for SAN Allocation. What I want to do is, on the Windows Machines, do something like a grep or awk so that the 10th field, which contains the size of the devices will be filtered and I can generate an output like. Devices of 187 GB = 3 Devices of 62 GB = 2 Devices of 31 GB = 3 Thing is, this output will differ on each storage box. Some may have 10 devices, some may have 100.... I can use grep or awk for Windows, but looking at a bigger picture here. what I want to do is do some kind of filtering of the command line output so that it will count the type of devices and seggregate them according to their size. Tried Perl, but I found that the syntax was a little difficult to remember. This is again my own shortcoming as I am not a trained programmer. I only got to work on the script after a gap of many weeks and by that time, I forgot what the script was supposed to do so had to start from the scratch....May be commenting will help :) I could only get to a point where I was able to store the out put of the whole line in an array but nothing beyond that because workload kept me really busy. When I did that, each element of the array seem to have one line of the output, like: The following was one element. 0D62 Not Visible ???:? 07C:D13 RAID-5 N/A (DT) RW 187843 The following was the next element. 0D63 Not Visible ???:? 08C:C11 RAID-5 N/A (DT) RW 187843 and so on..... What I wanted instead was a way to printout and count the last field.....I guess I will have to use hashes in Perl. Most examples of Hashes I have seen are pre created....But is there a way to create a Hash on the fly? Because I dont know how many devices will be a part of that hash....it will differ on each storage box....Is there something like this available in Python that will let me filter/add/printout the last field in a way that it will refer to it as a row and column kind of stuff? Is there a Hash equivalent in Python? Note I am giving Perl examples because I started with Perl first....though personally, I find Python syntax easier to understand...(Again, my bad....my limitation...not of the language).. 2) Automate storage allocation. Whats given below is only a small part of what I want to do.... Given is a brief output and explanation. All storage devices of my storage boxes have hexamdecimal LUN IDs..... Lets say I have a free available LUN IDs between say 5* to A .....meaning, the command output looks something like this: symcfg list -sid 1234 -sa 04B -p 0 -addresses -available Symmetrix ID: 000184501234 Director Device Name Attr Address ---------------------- ----------------------------- ---- -------------- Ident Symbolic Port Sym Physical VBUS TID LUN ------ -------- ---- ---- ----------------------- ---- --- --- FA-4B 04B 0 - AVAILABLE 0 0 000 * 0029 /dev/rdsk/c1t0d1s2 0 0 001 0033 /dev/rdsk/c1t0d2s2 0 0 002 003D /dev/rdsk/c1t0d3s2 0 0 003 0046 Not Visible 0 0 004 - AVAILABLE 0 0 005 * 0075 Not Visible 0 0 00A - AVAILABLE 0 0 00B * When there is a "*", from there on, till the next hex number, th LUN IDs are available. Meaning, from 000* to 1, nothing is available, but from 005* to 00A I have 006 through 009 available. I want to redirect this output to an array or a hash or something like that, then filter the last field, and then on the fly generate the LUN IDs between the 005 to 009 as well..Then using some commands, automate the process of allocating the LUN IDs to some free avaiable LUNs which I found in the first command output.... Is Perl better at manipulating hex or python? I know its possible to redirect the above output to a text file as well as a CSV file or an XML File and do I/Os on those files and then .but is Perl better for that or Python? 3) I want to generate reports on Performance, like which LUN has more IOs....What will be helpful here is a language that can help me create these graphs in excel....run the script and the output should generate a graph in Excel.... Which language is better suited for my needs? I found Perl syntax a little cryptic, but if Perl will be faster and better suited than Python, then I am ready to invest more time with Perl.... Which language will be faster for text processing/automation? Which language will generate Binary executable that is smaller in size and faster? I played a little with Python too...today is my third day....Found the syntax much easier to learn....Also came across cxfreeze which creates independent binary executables...is something such available in Perl? 4) I also want to try out playing with XML output....The storage commands I use allow me the output to be directed to an XML Format....Is Python better suited at this ? Few more questions pop up like, Which will give me more freedom and ease to maintain ? Which scripting language is better from the employability point of view? I dont want to start with one language and six months or a year down think "Heck, this was better in the other one".....because I really can concentrate on only one langauge. My apologies in advance if any questions above seem to be dumb or naive. -------------- next part -------------- An HTML attachment was scrubbed... URL: From charleshbecker at gmail.com Mon Nov 28 08:57:10 2011 From: charleshbecker at gmail.com (Charles Becker) Date: Mon, 28 Nov 2011 00:57:10 -0700 Subject: [Tutor] Random order program In-Reply-To: <4ED2C6E7.6060600@davea.name> References: <4ED2C6E7.6060600@davea.name> Message-ID: Dave, Myles, et al, On Nov 27, 2011, at 4:25 PM, Dave Angel wrote: > On 11/27/2011 05:17 PM, myles broomes wrote: >> >> >> >> >> >> >> >> #random order list >> while len(random_word_list) != len(word_list): >> word = random.choice(word_list) >> if word not in random_word_list: >> random_word_list += word >> > If you use += operator with list on the left side, it assumes something compatible with list on the right. So either use > random_word_list += [word] > Or else use random_word_list.append(word) >> >> >> >> >> Everyone has offered some good feedback, I just wanted to throw in this, and hopefully everyone can say if I'm correct or not: A way to make the code more 'pythonic' and easier to read might be to replace the conditional while len(random_word_list) != len(word_list) With the following : For x in range(len(word_list)) This will prevent infinite loops, easier to read, and allows for a lot of other uses (even if x is never used). Any thoughts people? And would this method (on a small or large scale) be 'cheaper' than the original conditional? Or more 'pythonic'? Charles Sent from my iPhone -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Nov 28 09:42:36 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 28 Nov 2011 08:42:36 +0000 Subject: [Tutor] Text Proccessing/Command Line Redirection/XML Parsing etc in Python. In-Reply-To: References: Message-ID: Pritesh Ugrankar, 28.11.2011 07:56: > First of all, my apologies for writing this very long post. Welcome to the list. :) > I have been through some related questions about this in Stack Overflow as > well as googled it and found that Perl and Python are the two languages > that offer most what I need. As a SAN Administrator, I have a very limited > time to learn a scripting language so I can concentrate on only one. Most > of my questions below may make you think that I prefer Perl, but its > nothing like...Just that I tried learning Perl before for doing stuff I > want to try, but am thinking now what advantages will I have if I try out > Python? There are two anecdotes that people from both camps frequently report. With Perl, people write their script, and then, several months later, they come back, look at it, don't understand it anymore, and rewrite it. With Python, people write their script, forget about it over time, write it again when they need it, and when they happen to find the old one and compare it to the new one, they find that both look almost identical. It's all in the syntax. > All my SAN Management Servers are Windows only. > > Following is what I am specifically looking at: > > 1) Consider the following output: > symdev -sid 1234 list devs > 0D62 Not Visible ???:? 07C:D13 RAID-5 N/A (DT) RW 187843 > 0D63 Not Visible ???:? 08C:C11 RAID-5 N/A (DT) RW 187843 > 0D64 Not Visible ???:? 07C:C12 RAID-5 N/A (DT) RW 62614 > 0D65 Not Visible ???:? 08C:D14 RAID-5 N/A (DT) RW 62614 > 0D66 Not Visible ???:? 07C:D15 RAID-5 N/A (DT) RW 31307 > 0D67 Not Visible ???:? 08C:C13 RAID-5 N/A (DT) RW 31307 > 0D68 Not Visible ???:? 07C:C14 RAID-5 N/A (DT) RW 31307 > > Whats given above is only a small part of the output. There are many other > fields that appear but I have left those out for brevity. > > The symdev commands generates a list of devices that can be used for SAN > Allocation. > > What I want to do is, on the Windows Machines, do something like a grep or > awk so that the 10th field, which contains the size of the devices will be > filtered and I can generate an output like. > > Devices of 187 GB = 3 > > Devices of 62 GB = 2 > > Devices of 31 GB = 3 > > Thing is, this output will differ on each storage box. Some may have 10 > devices, some may have 100.... > > I can use grep or awk for Windows, but looking at a bigger picture here. > > what I want to do is do some kind of filtering of the command line output > so that it will count the type of devices and seggregate them according to > their size. That's really easy. You open the file (see the open() function) and it returns a file object. You can iterate over it with a for-loop, and it will return each line as a string. Use the split() method on the string object to split the string by whitespace. That returns a list of separate fields. Then, pick the fields you want. In code: with open('thefile.txt') as f: for line in f: fields = line.split() print(fields[9]) # the 10th field, for example If you are not reading the output from a file but from a process you started, take a look at the subprocess module in the standard library. http://docs.python.org/library/subprocess.html Also take a look at string formatting for output. http://docs.python.org/tutorial/inputoutput.html http://docs.python.org/library/stdtypes.html#string-formatting-operations > Tried Perl, but I found that the syntax was a little difficult to remember. > This is again my own shortcoming as I am not a trained programmer. I only > got to work on the script after a gap of many weeks and by that time, I > forgot what the script was supposed to do so had to start from the > scratch....May be commenting will help :) Yep, that's Perl at it's best. > Which language will generate Binary executable that is smaller in size and > faster? You usually don't do that. Instead, you'd install Python on all machines where you need it and then just run your code there. If you really want to go through the hassle to build a self-contained executable from each program you write, you will have to bundle the runtime for either language with it, so it won't be small. > 4) I also want to try out playing with XML output....The storage commands I > use allow me the output to be directed to an XML Format....Is Python better > suited at this ? Absolutely. Python has ElementTree. You'll just love working with it. http://docs.python.org/library/xml.etree.elementtree.html A quick tutorial is here: http://effbot.org/zone/element-index.htm > Few more questions pop up like, Which will give me more freedom and ease to > maintain ? Which scripting language is better from the employability point > of view? > > I dont want to start with one language and six months or a year down think > "Heck, this was better in the other one".....because I really can > concentrate on only one langauge. There are always certain types of problems that can be solved very beautifully in a particular language. That's why there's more than one language. You won't miss anything by choosing Python, though. Stefan From alan.gauld at btinternet.com Mon Nov 28 09:45:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Nov 2011 08:45:54 +0000 Subject: [Tutor] Random order program In-Reply-To: References: <4ED2C6E7.6060600@davea.name> Message-ID: On 28/11/11 07:57, Charles Becker wrote: > A way to make the code more 'pythonic' and easier to read might be to > replace the conditional > while len(random_word_list) != len(word_list) > With the following : > for x in range(len(word_list)) Unfortunately that won't work with the OPs algorithm. It involves randomly extracting an item from word_list until all items have been chosen, this is likely to require many more iterations than the number of items in the list because the random choice will pick some items more than once. This is why we are suggesting that a different algorithm be used instead! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cwitts at compuscan.co.za Mon Nov 28 09:57:28 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 28 Nov 2011 10:57:28 +0200 Subject: [Tutor] Random order program In-Reply-To: References: Message-ID: <4ED34CF8.3000603@compuscan.co.za> On 2011/11/28 12:17 AM, myles broomes wrote: > I requested help for this code earlier and I thought it had been corrected but apparently, there is still a problem with it... > > #random word order program > #the user gives the program a list of words > #the program then returns them in a random order > > import random > > #explain the purpose of the program to the user > print("At the prompt, type in a list of words and they will be returned in a random order.") > > #get the users input for the list of words, one by one > first_word = input("Please enter your first word: ") > second_word = input("Please enter your second word: ") > third_word = input("Please enter your third word: ") > fourth_word = input("Please enter your fourth word: ") > fifth_word = input("Please enter your fifth word: ") > > #create a tuple containing the users words of the words > word_list = (first_word,second_word,third_word,fourth_word,fifth_word) > > #create an empty list that the words will go into to be returned in a random order > random_word_list = [] > > print("Now your list will be displayed in a random order.") > > #random order list > while len(random_word_list) != len(word_list): > word = random.choice(word_list) > if word not in random_word_list: > random_word_list += word > > #display the random word list > print(random_word_list) > > input("Press enter to exit...") > > And once again, the following is displayed.... > > At the prompt, type in a list of words and they will be returned in a random order. > Please enter your first word: one > Please enter your second word: two > Please enter your third word: three > Please enter your fourth word: four > Please enter your fifth word: five > Now your list will be displayed in a random order. > > Then the program just stops for some reason. Again, any help is much appreciated. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Is there anything wrong with just doing the following ? from random import shuffle # just type words with space separating the items # ie. one two three four five words = input('Please enter a list of words: ') word_list = words.split() print word_list shuffle(word_list) print word_list -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From pritesh.ugrankar at gmail.com Mon Nov 28 10:08:42 2011 From: pritesh.ugrankar at gmail.com (Pritesh Ugrankar) Date: Mon, 28 Nov 2011 14:38:42 +0530 Subject: [Tutor] Tutor Digest, Vol 93, Issue 158 In-Reply-To: References: Message-ID: Hi, Thank you very much Stefan Behnel for your reply. I never thought you guys would go through my whole mail. Heck, no one bashed me about asking so many questions here (untill now)....no direct/indirect "Go away/dont ask such stupid questions etc etc" You people are amazingly patient and helpful. I am sure that there will be something in Python that will let me generate the hex stuff that I was talking about. I will spend more time learning this language. From what I understand, if something can be done in one scripting language, same can be done in any other, and definitely in Python. Thank you sir once again. On Mon, Nov 28, 2011 at 2:12 PM, wrote: > 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. Text Proccessing/Command Line Redirection/XML Parsing etc in > Python. (Pritesh Ugrankar) > 2. Re: Random order program (Charles Becker) > 3. Re: Text Proccessing/Command Line Redirection/XML Parsing etc > in Python. (Stefan Behnel) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 28 Nov 2011 13:26:06 +0530 > From: Pritesh Ugrankar > To: tutor at python.org > Subject: [Tutor] Text Proccessing/Command Line Redirection/XML Parsing > etc in Python. > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > First of all, my apologies for writing this very long post. > > I have been through some related questions about this in Stack Overflow as > well as googled it and found that Perl and Python are the two languages > that offer most what I need. As a SAN Administrator, I have a very limited > time to learn a scripting language so I can concentrate on only one. Most > of my questions below may make you think that I prefer Perl, but its > nothing like...Just that I tried learning Perl before for doing stuff I > want to try, but am thinking now what advantages will I have if I try out > Python? > > All my SAN Management Servers are Windows only. > > Following is what I am specifically looking at: > > 1) Consider the following output: > symdev -sid 1234 list devs > 0D62 Not Visible ???:? 07C:D13 RAID-5 N/A (DT) RW 187843 > 0D63 Not Visible ???:? 08C:C11 RAID-5 N/A (DT) RW 187843 > 0D64 Not Visible ???:? 07C:C12 RAID-5 N/A (DT) RW 62614 > 0D65 Not Visible ???:? 08C:D14 RAID-5 N/A (DT) RW 62614 > 0D66 Not Visible ???:? 07C:D15 RAID-5 N/A (DT) RW 31307 > 0D67 Not Visible ???:? 08C:C13 RAID-5 N/A (DT) RW 31307 > 0D68 Not Visible ???:? 07C:C14 RAID-5 N/A (DT) RW 31307 > > Whats given above is only a small part of the output. There are many other > fields that appear but I have left those out for brevity. > > The symdev commands generates a list of devices that can be used for SAN > Allocation. > > What I want to do is, on the Windows Machines, do something like a grep or > awk so that the 10th field, which contains the size of the devices will be > filtered and I can generate an output like. > > Devices of 187 GB = 3 > > Devices of 62 GB = 2 > > Devices of 31 GB = 3 > > Thing is, this output will differ on each storage box. Some may have 10 > devices, some may have 100.... > > I can use grep or awk for Windows, but looking at a bigger picture here. > > what I want to do is do some kind of filtering of the command line output > so that it will count the type of devices and seggregate them according to > their size. > > Tried Perl, but I found that the syntax was a little difficult to remember. > This is again my own shortcoming as I am not a trained programmer. I only > got to work on the script after a gap of many weeks and by that time, I > forgot what the script was supposed to do so had to start from the > scratch....May be commenting will help :) > > I could only get to a point where I was able to store the out put of the > whole line in an array but nothing beyond that because workload kept me > really busy. > > When I did that, each element of the array seem to have one line of the > output, like: The following was one element. > 0D62 Not Visible ???:? 07C:D13 RAID-5 N/A (DT) RW 187843 > > The following was the next element. > 0D63 Not Visible ???:? 08C:C11 RAID-5 N/A (DT) RW 187843 > > and so on..... > > What I wanted instead was a way to printout and count the last field.....I > guess I will have to use hashes in Perl. Most examples of Hashes I have > seen are pre created....But is there a way to create a Hash on the fly? > Because I dont know how many devices will be a part of that hash....it will > differ on each storage box....Is there something like this available in > Python that will let me filter/add/printout the last field in a way that it > will refer to it as a row and column kind of stuff? Is there a Hash > equivalent in Python? > > Note I am giving Perl examples because I started with Perl first....though > personally, I find Python syntax easier to understand...(Again, my > bad....my limitation...not of the language).. > > 2) Automate storage allocation. Whats given below is only a small part of > what I want to do.... Given is a brief output and explanation. > > All storage devices of my storage boxes have hexamdecimal LUN IDs..... > > Lets say I have a free available LUN IDs between say 5* to A .....meaning, > the command output looks something like this: > symcfg list -sid 1234 -sa 04B -p 0 -addresses -available > Symmetrix ID: 000184501234 > Director Device Name Attr Address > ---------------------- ----------------------------- ---- -------------- > Ident Symbolic Port Sym Physical VBUS TID LUN > ------ -------- ---- ---- ----------------------- ---- --- --- > FA-4B 04B 0 - AVAILABLE 0 0 000 * > 0029 /dev/rdsk/c1t0d1s2 0 0 001 > 0033 /dev/rdsk/c1t0d2s2 0 0 002 > 003D /dev/rdsk/c1t0d3s2 0 0 003 > 0046 Not Visible 0 0 004 > - AVAILABLE 0 0 005 * > 0075 Not Visible 0 0 00A > - AVAILABLE 0 0 00B * > > When there is a "*", from there on, till the next hex number, th LUN IDs > are available. Meaning, from 000* to 1, nothing is available, but from 005* > to 00A I have 006 through 009 available. I want to redirect this output to > an array or a hash or something like that, then filter the last field, and > then on the fly generate the LUN IDs between the 005 to 009 as well..Then > using some commands, automate the process of allocating the LUN IDs to some > free avaiable LUNs which I found in the first command output.... > > Is Perl better at manipulating hex or python? > > I know its possible to redirect the above output to a text file as well as > a CSV file or an XML File and do I/Os on those files and then .but is Perl > better for that or Python? > > 3) I want to generate reports on Performance, like which LUN has more > IOs....What will be helpful here is a language that can help me create > these graphs in excel....run the script and the output should generate a > graph in Excel.... > > Which language is better suited for my needs? I found Perl syntax a little > cryptic, but if Perl will be faster and better suited than Python, then I > am ready to invest more time with Perl.... > > Which language will be faster for text processing/automation? > > Which language will generate Binary executable that is smaller in size and > faster? > I played a little with Python too...today is my third day....Found the > syntax much easier to learn....Also came across cxfreeze which creates > independent binary executables...is something such available in Perl? > > 4) I also want to try out playing with XML output....The storage commands I > use allow me the output to be directed to an XML Format....Is Python better > suited at this ? > > Few more questions pop up like, Which will give me more freedom and ease to > maintain ? Which scripting language is better from the employability point > of view? > > I dont want to start with one language and six months or a year down think > "Heck, this was better in the other one".....because I really can > concentrate on only one langauge. > > My apologies in advance if any questions above seem to be dumb or naive. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111128/ded43c3c/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Mon, 28 Nov 2011 00:57:10 -0700 > From: Charles Becker > To: "d at davea.name" > Cc: "tutor at python.org" , myles broomes > > Subject: Re: [Tutor] Random order program > Message-ID: > Content-Type: text/plain; charset="us-ascii" > > Dave, Myles, et al, > > On Nov 27, 2011, at 4:25 PM, Dave Angel wrote: > > > On 11/27/2011 05:17 PM, myles broomes wrote: > >> > >> > >> > >> > >> > >> > >> > >> #random order list > >> while len(random_word_list) != len(word_list): > >> word = random.choice(word_list) > >> if word not in random_word_list: > >> random_word_list += word > >> > > If you use += operator with list on the left side, it assumes something > compatible with list on the right. So either use > > random_word_list += [word] > > Or else use random_word_list.append(word) > >> > >> > >> > >> > >> > > Everyone has offered some good feedback, I just wanted to throw in this, > and hopefully everyone can say if I'm correct or not: > > A way to make the code more 'pythonic' and easier to read might be to > replace the conditional > while len(random_word_list) != len(word_list) > With the following : > For x in range(len(word_list)) > This will prevent infinite loops, easier to read, and allows for a lot of > other uses (even if x is never used). Any thoughts people? And would this > method (on a small or large scale) be 'cheaper' than the original > conditional? Or more 'pythonic'? > > Charles > > Sent from my iPhone > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111128/a1076e0e/attachment-0001.html > > > > ------------------------------ > > Message: 3 > Date: Mon, 28 Nov 2011 08:42:36 +0000 > From: Stefan Behnel > To: tutor at python.org > Subject: Re: [Tutor] Text Proccessing/Command Line Redirection/XML > Parsing etc in Python. > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > Pritesh Ugrankar, 28.11.2011 07:56: > > First of all, my apologies for writing this very long post. > > Welcome to the list. :) > > > > I have been through some related questions about this in Stack Overflow > as > > well as googled it and found that Perl and Python are the two languages > > that offer most what I need. As a SAN Administrator, I have a very > limited > > time to learn a scripting language so I can concentrate on only one. Most > > of my questions below may make you think that I prefer Perl, but its > > nothing like...Just that I tried learning Perl before for doing stuff I > > want to try, but am thinking now what advantages will I have if I try out > > Python? > > There are two anecdotes that people from both camps frequently report. With > Perl, people write their script, and then, several months later, they come > back, look at it, don't understand it anymore, and rewrite it. With Python, > people write their script, forget about it over time, write it again when > they need it, and when they happen to find the old one and compare it to > the new one, they find that both look almost identical. > > It's all in the syntax. > > > > All my SAN Management Servers are Windows only. > > > > Following is what I am specifically looking at: > > > > 1) Consider the following output: > > symdev -sid 1234 list devs > > 0D62 Not Visible ???:? 07C:D13 RAID-5 N/A (DT) RW 187843 > > 0D63 Not Visible ???:? 08C:C11 RAID-5 N/A (DT) RW 187843 > > 0D64 Not Visible ???:? 07C:C12 RAID-5 N/A (DT) RW 62614 > > 0D65 Not Visible ???:? 08C:D14 RAID-5 N/A (DT) RW 62614 > > 0D66 Not Visible ???:? 07C:D15 RAID-5 N/A (DT) RW 31307 > > 0D67 Not Visible ???:? 08C:C13 RAID-5 N/A (DT) RW 31307 > > 0D68 Not Visible ???:? 07C:C14 RAID-5 N/A (DT) RW 31307 > > > > Whats given above is only a small part of the output. There are many > other > > fields that appear but I have left those out for brevity. > > > > The symdev commands generates a list of devices that can be used for SAN > > Allocation. > > > > What I want to do is, on the Windows Machines, do something like a grep > or > > awk so that the 10th field, which contains the size of the devices will > be > > filtered and I can generate an output like. > > > > Devices of 187 GB = 3 > > > > Devices of 62 GB = 2 > > > > Devices of 31 GB = 3 > > > > Thing is, this output will differ on each storage box. Some may have 10 > > devices, some may have 100.... > > > > I can use grep or awk for Windows, but looking at a bigger picture here. > > > > what I want to do is do some kind of filtering of the command line output > > so that it will count the type of devices and seggregate them according > to > > their size. > > That's really easy. You open the file (see the open() function) and it > returns a file object. You can iterate over it with a for-loop, and it will > return each line as a string. Use the split() method on the string object > to split the string by whitespace. That returns a list of separate fields. > Then, pick the fields you want. In code: > > with open('thefile.txt') as f: > for line in f: > fields = line.split() > print(fields[9]) # the 10th field, for example > > If you are not reading the output from a file but from a process you > started, take a look at the subprocess module in the standard library. > > http://docs.python.org/library/subprocess.html > > Also take a look at string formatting for output. > > http://docs.python.org/tutorial/inputoutput.html > > http://docs.python.org/library/stdtypes.html#string-formatting-operations > > > > Tried Perl, but I found that the syntax was a little difficult to > remember. > > This is again my own shortcoming as I am not a trained programmer. I only > > got to work on the script after a gap of many weeks and by that time, I > > forgot what the script was supposed to do so had to start from the > > scratch....May be commenting will help :) > > Yep, that's Perl at it's best. > > > > Which language will generate Binary executable that is smaller in size > and > > faster? > > You usually don't do that. Instead, you'd install Python on all machines > where you need it and then just run your code there. > > If you really want to go through the hassle to build a self-contained > executable from each program you write, you will have to bundle the runtime > for either language with it, so it won't be small. > > > > 4) I also want to try out playing with XML output....The storage > commands I > > use allow me the output to be directed to an XML Format....Is Python > better > > suited at this ? > > Absolutely. Python has ElementTree. You'll just love working with it. > > http://docs.python.org/library/xml.etree.elementtree.html > > A quick tutorial is here: > > http://effbot.org/zone/element-index.htm > > > > Few more questions pop up like, Which will give me more freedom and ease > to > > maintain ? Which scripting language is better from the employability > point > > of view? > > > > I dont want to start with one language and six months or a year down > think > > "Heck, this was better in the other one".....because I really can > > concentrate on only one langauge. > > There are always certain types of problems that can be solved very > beautifully in a particular language. That's why there's more than one > language. You won't miss anything by choosing Python, though. > > Stefan > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 93, Issue 158 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 28 10:20:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Nov 2011 09:20:21 +0000 Subject: [Tutor] Tutor Digest, Vol 93, Issue 158 In-Reply-To: References: Message-ID: On 28/11/11 09:08, Pritesh Ugrankar wrote: > I am sure that there will be something in Python that will let me > generate the hex stuff that I was talking about. Python does hex as well as most languages, I'm not sure exactly what you want to do in hex however, it wasn't clear from your original post. One last thing, we prefer if you cut out redundant materialm from the posts, it cuts down bandwidth... So no need to include the full original message at the bottom. > learning this language. From what I understand, if something can be done > in one scripting language, same can be done in any other, and definitely > in Python. Python can do most things, some other scripting languages are more specialised and therefore less flexible. But Perl, Python, Ruby, Tcl etc are all similar in capabilities. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Nov 28 10:22:12 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Nov 2011 09:22:12 +0000 Subject: [Tutor] Random order program In-Reply-To: <4ED34CF8.3000603@compuscan.co.za> References: <4ED34CF8.3000603@compuscan.co.za> Message-ID: On 28/11/11 08:57, Christian Witts wrote: > Is there anything wrong with just doing the following ? No, it's what we were trying to get the OP to discover for himself :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mlybrand at gmail.com Mon Nov 28 10:28:06 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Mon, 28 Nov 2011 01:28:06 -0800 Subject: [Tutor] Critique and Question Message-ID: Okay, so I just started to learn Python. I have been working through Dive Into Python 3 and the Google stuff (great exercises IMHO, totally fun). However, with Dive, I had an issue with him referencing the files in the example directory, which from the website seem very unhandy. Although I have since stumbled upon his GitHub, I made a Python script to grab those files for me and it works great, with the exception of doubling the line spacing. So here is my code. I hope you critique the heck out of my and that you point out what I did wrong to introduce double line-spacing. Thanks a bunch: import os import urllib.request import re url_root = 'http://diveintopython3.ep.io/examples/' file_root = os.path.join(os.path.expanduser("~"), "diveintopython3", "examples") main_page = urllib.request.urlopen(url_root).read() main_page = main_page.decode("utf-8") pattern = 'href="([^"].*?.)(py|xml)"' matches = re.findall(pattern, main_page) for my_tuple in matches: this_file = my_tuple[0] + my_tuple[1] data = urllib.request.urlopen(url_root + this_file).read() data = data.decode("utf-8") with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8') as a_file: a_file.write(data) -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Nov 28 10:37:17 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Nov 2011 10:37:17 +0100 Subject: [Tutor] Random order program References: <4ED34CF8.3000603@compuscan.co.za> Message-ID: Christian Witts wrote: > Is there anything wrong with just doing the following ? > > from random import shuffle > # just type words with space separating the items > # ie. one two three four five > words = input('Please enter a list of words: ') > word_list = words.split() > print word_list > shuffle(word_list) > print word_list You're mixing 3.x input and 2.x print ;) From cwitts at compuscan.co.za Mon Nov 28 10:41:11 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 28 Nov 2011 11:41:11 +0200 Subject: [Tutor] Random order program In-Reply-To: References: <4ED34CF8.3000603@compuscan.co.za> Message-ID: <4ED35737.8000802@compuscan.co.za> On 2011/11/28 11:37 AM, Peter Otten wrote: > Christian Witts wrote: > >> Is there anything wrong with just doing the following ? >> >> from random import shuffle >> # just type words with space separating the items >> # ie. one two three four five >> words = input('Please enter a list of words: ') >> word_list = words.split() >> print word_list >> shuffle(word_list) >> print word_list > You're mixing 3.x input and 2.x print ;) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Doh, that's what you get when you retype your code instead of copy/pasta it, it was originally raw_input. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Mon Nov 28 10:53:41 2011 From: suryak at live.com (surya k) Date: Mon, 28 Nov 2011 15:23:41 +0530 Subject: [Tutor] why doesn't python show error Message-ID: 1. Why doesn't python show error(description given below) at the?beginning?when we use functions which aren't present in the standard modules... Example:? TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look closely, I used a wrong function to find length of the string. [ strlen( ) belongs to C ].When I run the program, it didn't show any error but when entered input, it then showed up!.Why python doesn't show error at the beginning just like C does?2. Why doesn't python create executable file (.exe ) when we run the code.. If this doesn't do, how can I share my program.. does everyone need to have python to check others code and know what it does?? From tvssarma.omega9 at gmail.com Mon Nov 28 11:16:59 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Mon, 28 Nov 2011 15:46:59 +0530 Subject: [Tutor] why doesn't python show error In-Reply-To: References: Message-ID: On 28 November 2011 15:23, surya k wrote: > > 1. Why doesn't python show error(description given below) at > the beginning when we use functions which aren't present in the standard > modules... > > Example: > > TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look > closely, I used a wrong function to find length of the string. [ strlen( ) > belongs to C ].When I run the program, it didn't show any error but when > entered input, it then showed up!.Why python doesn't show error at the > beginning just like C does?2. Why doesn't python create executable file > (.exe ) when we run the code.. If this doesn't do, how can I share my > program.. does everyone need to have python to check others code and know > what it does? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The thing is, python does not compile code like C does. It interprets each line. So as you say, "it runs". Errors turn up only when they are encountered. http://en.wikipedia.org/wiki/Interpreted_language But python does have a compile version, I believe jython does this. There are a couple of programs that generate executable, py2exe on Win for example. http://stackoverflow.com/questions/2933/an-executable-python-app -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Mon Nov 28 11:31:39 2011 From: suryak at live.com (surya k) Date: Mon, 28 Nov 2011 16:01:39 +0530 Subject: [Tutor] why doesn't python show error In-Reply-To: References: Message-ID: Thanks for that information. I understood what you are saying but in general when python doesn't give us executable files (whether its in Mac/ Linux/ Windows).. how could people develop programs ?. At some point of time people need to provide a file that runs without the help of a python interpreter.. From: Sarma Tangirala Sent: Monday, November 28, 2011 3:46 PM To: surya k Cc: Python Tutor Subject: Re: [Tutor] why doesn't python show error On 28 November 2011 15:23, surya k wrote: 1. Why doesn't python show error(description given below) at the beginning when we use functions which aren't present in the standard modules... Example: TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look closely, I used a wrong function to find length of the string. [ strlen( ) belongs to C ].When I run the program, it didn't show any error but when entered input, it then showed up!.Why python doesn't show error at the beginning just like C does?2. Why doesn't python create executable file (.exe ) when we run the code.. If this doesn't do, how can I share my program.. does everyone need to have python to check others code and know what it does? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The thing is, python does not compile code like C does. It interprets each line. So as you say, "it runs". Errors turn up only when they are encountered. http://en.wikipedia.org/wiki/Interpreted_language But python does have a compile version, I believe jython does this. There are a couple of programs that generate executable, py2exe on Win for example. http://stackoverflow.com/questions/2933/an-executable-python-app -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Nov 28 11:54:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Nov 2011 21:54:14 +1100 Subject: [Tutor] why doesn't python show error In-Reply-To: References: Message-ID: <4ED36856.1040403@pearwood.info> surya k wrote: > Thanks for that information. I understood what you are saying but in general when python doesn't give us executable files (whether its in Mac/ Linux/ Windows).. how could people develop programs ?. > At some point of time people need to provide a file that runs without the help of a python interpreter.. Why? Perl, Javascript, PHP, Flash, Java, shell scripts, .Net, VisualBasic, and hundreds of other languages have been successful for decades, and they all require either an interpreter or a runtime environment, or both, to work. Why should Python be treated any differently? If you want to include a Python runtime environment with your code, either include a version of Python, or use py2exe to wrap the Python runtime environment and your code into a single executable. Unless you are writing device drivers for hardware, or operating system kernels, or a few other applications, compiling to machine code is of limited value. And even where compiling to machine code is useful, it is often better to use a Just In Time compiler that compiles the code when it is run, so it can take advantage of runtime information about the data. A good JIT compiler can often beat a static compiler for speed. -- Steven From timomlists at gmail.com Mon Nov 28 12:18:49 2011 From: timomlists at gmail.com (Timo) Date: Mon, 28 Nov 2011 12:18:49 +0100 Subject: [Tutor] How to handle conjunction operators In-Reply-To: References: Message-ID: <4ED36E19.9060205@gmail.com> Op 27-11-11 20:02, Hugo Arts schreef: > On Sun, Nov 27, 2011 at 7:52 PM, surya k wrote: >> Hi, >> Could you please tell me why this isn't working and how can I make it >> possible... >> Consider this code.. >> >> name = raw_input("Enter your first name: ") >> if name[0] == ("m" or "f" or "b") : >> rhyme = name[1:] >> >> What I want here is.. If the name starts with 'm' or 'f' or 'b', The first >> letter should be removed. >> But this isn't happening here. > This is a very common error. Fact is, the or operator just isn't > distributive with respect to the == operator like that, and for good > reason. What you want is either this: > > if name[0] == "m" or name[0] == "f" or name[0] == "b": > > or, more idiomatically, you can use the in operator like this: > > if name[0] in ("m", "f", "b"): Or even shorter: if name[0] in "mfb": Cheers, Timo > > HTH, > Hugo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Mon Nov 28 12:43:18 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Nov 2011 12:43:18 +0100 Subject: [Tutor] How to handle conjunction operators References: Message-ID: surya k wrote: > Could you please tell me why this isn't working and how can I make it > possible... Consider this code.. > name = raw_input("Enter your first name:") > if name[0] == ("m" or "f" or "b") : > rhyme = name[1:] > What I want here is.. If the name starts with 'm' or > 'f' or 'b', The first letter should be removed.But this isn't happening > here. - If you want to make your code bullet-proof you should also consider the case where the user enters an empty string. - You can check if a string starts with a particular string with the startswith() method: >>> "frank".startswith("f") True It's not widely known, but the method accepts a tuple since Python 2.5: >>> "sue".startswith(("m", "f", "b")) False >>> "frank".startswith(("m", "f", "b")) True The beauty of this approach is that you are not limited to single-char prefixes: >>> "stephen".startswith(("m", "f", "st")) True From steve at pearwood.info Mon Nov 28 12:30:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 28 Nov 2011 22:30:06 +1100 Subject: [Tutor] How to handle conjunction operators In-Reply-To: <4ED36E19.9060205@gmail.com> References: <4ED36E19.9060205@gmail.com> Message-ID: <4ED370BE.10409@pearwood.info> Timo wrote: >> if name[0] in ("m", "f", "b"): > Or even shorter: > if name[0] in "mfb": Shorter, but wrong. name = ['fb', 'ph', 'xy'] # oops, bad data if name[0] in 'mfb': ... Bad data should lead to an error as close as possible to the source of the bad data, and do the wrong thing for a while before blowing up in some unexpected part of the code. Code defensively: if you want to be sure name[0] is a single character, make sure the test will only pass when given a single character. -- Steven From Michael at shamirlens.co.uk Mon Nov 28 12:35:34 2011 From: Michael at shamirlens.co.uk (Michael M Mason) Date: Mon, 28 Nov 2011 11:35:34 +0000 Subject: [Tutor] Weird Try..Except Error In-Reply-To: References: <599CEBACD49B4144A61212D837EE3C0F144604D87C@MX34A.corp.emc.com> <599CEBACD49B4144A61212D837EE3C0F144604D888@MX34A.corp.emc.com> Message-ID: <5378B081D0A21C45A6135E92E182BD7F4DCDFAD4@Mail1-Shamir.shamir.org.il> Alan Gauld wrote on 25 November 2011 at 21:11:- > This is one of the annoying ambiguities of Windows. > The way it finds the executable for executables(exe, bat cmd etc) is > different to how it finds the executable for associations. > > In the former case it uses PATH, in the latter it relies on the file > association set in the file properties. > > When you install a new Python it tends to set itself as > the default interpreter for .py files. You can use the DOS commands to manipulate file associations on Windows so that you can run two or more versions of Python on the same computer. The DOS commands are ASSOC and FTYPE. First you need to use ASSOC to discover the file type for .py, .pyw and .pyc files. To use ASSOC type ASSOC followed by the extension you are interested in. For example, find the file type for .py files, type:- assoc .py Typical results from ASSOC will be:- .py = Python.File .pyw = Python.NoConFile .pyc = Python.CompiledFile Next, use FTYPE to discover the 'open' commands associated with each of these file types. To use FTYPE type FTYPE followed by the file type as given by the ASSOC command. For example:- ftype Python.File Typical results from FTYPE will be something like this:- Python.File="C:\Python27\python.exe" "%1" %* Python.NoConFile="C:\Python27\pythonw.exe" "%1" %* Python.CompiledFile="C:\Python27\python.exe" "%1" %* What we can do now is create our own set of file types, one for Python 2.7 and one for Python 3.2. This is done using the FTYPE command (of course, your paths may be different to the ones shown):- ftype Python32.File="C:\Python3\python.exe" "%1" %* ftype Python32.NoConFile="C:\Python3\pythonw.exe" "%1" %* ftype Python32.CompiledFile="C:\Python3\python.exe" "%1" %* ftype Python27.File="C:\Python27\python.exe" "%1" %* ftype Python27.NoConFile="C:\Python27\pythonw.exe" "%1" %* ftype Python27.CompiledFile="C:\Python27\python.exe" "%1" %* That's the preparatory work completed. We can now choose which version of Python will run when a *.py file is executed using the ASSOC command. To select Python 3 we'd use these commands:- assoc .py = Python32.File assoc .pyw = Python32.NoConFile assoc .pyc = Python32.CompiledFile ...and to use Python 2.7 we'd use these commands:- assoc .py = Python27.File assoc .pyw = Python27.NoConFile assoc .pyc = Python27.CompiledFile -- Michael This mail was sent via Mail-SeCure System. ************************************************************************************ This footnote confirms that this email message has been scanned by PineApp Mail-SeCure for the presence of malicious code, vandals & computer viruses. ************************************************************************************ From suryak at live.com Mon Nov 28 13:22:58 2011 From: suryak at live.com (surya k) Date: Mon, 28 Nov 2011 17:52:58 +0530 Subject: [Tutor] Multiplater gaming Message-ID: I am building a multiplayer game (Game:Bingo) where friends(players) connect over internet. In this particular game, users sends a "character/ number" to all other players.. Can you please shed some light on it. I've been looking into 'Core Python Programming' book by Chun but I couldn't understand clearly. So, If possible, please provide links to related free e-books / tutorials. my another question is.. do I need to setup any external hardware infrastructure to get this done ?? Thanks for sparing your valuable time on this! -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Nov 28 13:26:36 2011 From: d at davea.name (Dave Angel) Date: Mon, 28 Nov 2011 07:26:36 -0500 Subject: [Tutor] Critique and Question In-Reply-To: References: Message-ID: <4ED37DFC.7010808@davea.name> On 11/28/2011 04:28 AM, Mark Lybrand wrote: > Okay, so I just started to learn Python. I have been working through Dive > Into Python 3 and the Google stuff (great exercises IMHO, totally fun). > However, with Dive, I had an issue with him referencing the files in the > example directory, which from the website seem very unhandy. Although I > have since stumbled upon his GitHub, I made a Python script to grab those > files for me and it works great, with the exception of doubling the line > spacing. So here is my code. I hope you critique the heck out of my and > that you point out what I did wrong to introduce double line-spacing. > Thanks a bunch: > > import os > import urllib.request > import re > > url_root = 'http://diveintopython3.ep.io/examples/' > file_root = os.path.join(os.path.expanduser("~"), "diveintopython3", > "examples") > > main_page = urllib.request.urlopen(url_root).read() > main_page = main_page.decode("utf-8") > > pattern = 'href="([^"].*?.)(py|xml)"' > matches = re.findall(pattern, main_page) > for my_tuple in matches: > this_file = my_tuple[0] + my_tuple[1] > data = urllib.request.urlopen(url_root + this_file).read() > data = data.decode("utf-8") > with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8') > as a_file: > a_file.write(data) > You don't tell what your environment is, nor how you decide that the file is double-spaced. You also don't mention whether you're using Python 2.x or 3.x My guess is that you are using a Unix/Linux environment, and that the Dive author(s) used Windows. And that your text editor is interpreting the cr/lf pair (hex 0d 0a) as two line-endings. I believe emacs would have ignored the redundant cr. Python likewise probably won't care, though I'm not positive about things like lines that continue across newline boundaries. You can figure out what is actually in the file by using repr() on bytes read from the file in binary mode. Exactly how you do that will differ between Python 2.x and 3.x As for fixing it, you could either just use one of the dos2unix utilities kicking around (one's available on my Ubuntu from the Synaptic package manager), or you could make your utility manage it. On a regular file open, there's a mode paramter that you can use "u", or better "ru" to say Universal. It's intended to handle any of the three common line endings, and use a simple newline for all 3 cases. I don't know whether urlopen() also has that option, but if not, you can always copy the file after you have it locally. -- DaveA From andreas.perstinger at gmx.net Mon Nov 28 15:59:45 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Mon, 28 Nov 2011 15:59:45 +0100 Subject: [Tutor] Multiplater gaming In-Reply-To: References: Message-ID: <4ED3A1E1.5060603@gmx.net> On 2011-11-28 13:22, surya k wrote: > I am building a multiplayer game (Game:Bingo) where friends(players) > connect over internet. In this particular game, users sends a > "character/ number" to all other players.. > > Can you please shed some light on it. I've been looking into 'Core > Python Programming' book by Chun but I couldn't understand clearly. What are your specific problems? We can't help you if you don't give us more information about your program. Show us the problematic parts of your code. > So, If possible, please provide links to related free e-books / > tutorials. Some tutorials (IIRC you have already programming experiences, haven't you?): http://wiki.python.org/moin/BeginnersGuide/Programmers > my another question is.. do I need to setup any external hardware > infrastructure to get this done ?? I'm not a hardware expert, but if you want to create an online game you'll need at least some kind of server which probably has to be online 24/7 and is able to handle the traffic. Bye, Andreas From mlybrand at gmail.com Mon Nov 28 18:31:31 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Mon, 28 Nov 2011 09:31:31 -0800 Subject: [Tutor] Critique and Question In-Reply-To: <4ED37DFC.7010808@davea.name> References: <4ED37DFC.7010808@davea.name> Message-ID: Sorry for not providing all the required info. I am running python 3.2 on windows vista. I determined the files are double spaced by viewong them (random sampling) in notepad++. Not double spaced on server by downloading one in the browser. Can I use the 'Wu' flag when writing. I might just be 'w'-ing. I will look when I get home. Thanks Mark Also a little bummed that subprocess module doesn't appear to work on windows. I probably (hopefully) won't need it, but it still bums me. On Nov 28, 2011 4:27 AM, "Dave Angel" wrote: > On 11/28/2011 04:28 AM, Mark Lybrand wrote: > >> Okay, so I just started to learn Python. I have been working through Dive >> Into Python 3 and the Google stuff (great exercises IMHO, totally fun). >> However, with Dive, I had an issue with him referencing the files in the >> example directory, which from the website seem very unhandy. Although I >> have since stumbled upon his GitHub, I made a Python script to grab those >> files for me and it works great, with the exception of doubling the line >> spacing. So here is my code. I hope you critique the heck out of my and >> that you point out what I did wrong to introduce double line-spacing. >> Thanks a bunch: >> >> import os >> import urllib.request >> import re >> >> url_root = 'http://diveintopython3.ep.io/**examples/ >> ' >> file_root = os.path.join(os.path.**expanduser("~"), "diveintopython3", >> "examples") >> >> main_page = urllib.request.urlopen(url_**root).read() >> main_page = main_page.decode("utf-8") >> >> pattern = 'href="([^"].*?.)(py|xml)"' >> matches = re.findall(pattern, main_page) >> for my_tuple in matches: >> this_file = my_tuple[0] + my_tuple[1] >> data = urllib.request.urlopen(url_**root + this_file).read() >> data = data.decode("utf-8") >> with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8') >> as a_file: >> a_file.write(data) >> >> You don't tell what your environment is, nor how you decide that the > file is double-spaced. You also don't mention whether you're using Python > 2.x or 3.x > > My guess is that you are using a Unix/Linux environment, and that the Dive > author(s) used Windows. And that your text editor is interpreting the > cr/lf pair (hex 0d 0a) as two line-endings. I believe emacs would have > ignored the redundant cr. Python likewise probably won't care, though I'm > not positive about things like lines that continue across newline > boundaries. > > You can figure out what is actually in the file by using repr() on bytes > read from the file in binary mode. Exactly how you do that will differ > between Python 2.x and 3.x > > As for fixing it, you could either just use one of the dos2unix utilities > kicking around (one's available on my Ubuntu from the Synaptic package > manager), or you could make your utility manage it. On a regular file > open, there's a mode paramter that you can use "u", or better "ru" to say > Universal. It's intended to handle any of the three common line endings, > and use a simple newline for all 3 cases. I don't know whether urlopen() > also has that option, but if not, you can always copy the file after you > have it locally. > > > -- > > DaveA > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mayoadams at gmail.com Mon Nov 28 18:32:45 2011 From: mayoadams at gmail.com (Mayo Adams) Date: Mon, 28 Nov 2011 12:32:45 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) Message-ID: I am trying to pass a set of tuple strings from a file to a function I have defined.? Each tuple is on a separate line, and looks something like this: ('note',2048) The function has two parameters , and is defined thus: def findindex(dval,ticks): Apparently, I need to cast the second value as an integer in the body of the function in order to work with it as such, but when I attempt int(ticks) I get ValueError: invalid literal for int() with base 10: '2048)' Upon searching for elucidation of this on the internet I find nothing but esoterica, at least as far as I am concerned. Any pointers would make me happy. -- Mayo Adams mayoadams at gmail.com From eire1130 at gmail.com Mon Nov 28 18:47:00 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 28 Nov 2011 12:47:00 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: Message-ID: On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams wrote: > I am trying to pass a set of tuple strings from a file to a function I > have defined. Each tuple is on a separate line, and looks something > like this: > ('note',2048) > The function has two parameters , and is defined thus: def > findindex(dval,ticks): > Apparently, I need to cast the second value as an integer in the body > of the function in order to work with it as such, but when I attempt > int(ticks) I get > ValueError: invalid literal for int() with base 10: '2048)' > > Upon searching for elucidation of this on the internet I find nothing > but esoterica, at least as far as I am concerned. > Any pointers would make me happy. > > -- > Mayo Adams > > > > mayoadams at gmail.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Your problem is in the error message: ValueError: invalid literal for int() with base 10: '2048)' observer, Python tells you this isn't a number: '2048)' Indeed, this is correct, because you '2048)' is not a number. What you really want to pass to '2048', which int('2048') can understand just fine. So, trim off the parenthesis, or something. Alternatively, since you aren't actually passing a "tuple" but something that looks like a python tuple as a string, you could eval it: a = "('note',2048)" b = eval(a) print a, type(a), b, type(b) >> ('note',2048) ('note', 2048) In working with the second, you do normal tuple operations, like b[1] to access that index When passing to a function, you do this: findindex(*b) -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Mon Nov 28 18:46:40 2011 From: d at davea.name (Dave Angel) Date: Mon, 28 Nov 2011 12:46:40 -0500 Subject: [Tutor] Critique and Question In-Reply-To: References: <4ED37DFC.7010808@davea.name> Message-ID: <4ED3C900.1040205@davea.name> On 11/28/2011 12:31 PM, Mark Lybrand wrote: > Sorry for not providing all the required info. I am running python 3.2 on > windows vista. I determined the files are double spaced by viewong them > (random sampling) in notepad++. Not double spaced on server by downloading > one in the browser. Can I use the 'Wu' flag when writing. I might just be > 'w'-ing. I will look when I get home. > > Thanks > > Mark > > Also a little bummed that subprocess module doesn't appear to work on > windows. I probably (hopefully) won't need it, but it still bums me. > On Nov 28, 2011 4:27 AM, "Dave Angel" wrote: > >> On 11/28/2011 04:28 AM, Mark Lybrand wrote: >> >>> Okay, so I just started to learn Python. I have been working through Dive >>> Into Python 3 and the Google stuff (great exercises IMHO, totally fun). >>> However, with Dive, I had an issue with him referencing the files in the >>> example directory, which from the website seem very unhandy. Although I >>> have since stumbled upon his GitHub, I made a Python script to grab those >>> files for me and it works great, with the exception of doubling the line >>> spacing. So here is my code. I hope you critique the heck out of my and >>> that you point out what I did wrong to introduce double line-spacing. >>> Thanks a bunch: >>> >>> import os >>> import urllib.request >>> import re >>> >>> url_root = 'http://diveintopython3.ep.io/**examples/ >>> ' >>> file_root = os.path.join(os.path.**expanduser("~"), "diveintopython3", >>> "examples") >>> >>> main_page = urllib.request.urlopen(url_**root).read() >>> main_page = main_page.decode("utf-8") >>> >>> pattern = 'href="([^"].*?.)(py|xml)"' >>> matches = re.findall(pattern, main_page) >>> for my_tuple in matches: >>> this_file = my_tuple[0] + my_tuple[1] >>> data = urllib.request.urlopen(url_**root + this_file).read() >>> data = data.decode("utf-8") >>> with open(os.path.join(file_root, this_file), mode='w', encoding='utf-8') >>> as a_file: >>> a_file.write(data) >>> >>> You don't tell what your environment is, nor how you decide that the >> file is double-spaced. You also don't mention whether you're using Python >> 2.x or 3.x >> >> My guess is that you are using a Unix/Linux environment, and that the Dive >> author(s) used Windows. And that your text editor is interpreting the > >> You can figure out what is actually in the file by using repr() on bytes >> read from the file in binary mode. Exactly how you do that will differ >> between Python 2.x and 3.x >> You put your comments BEFORE the quoted text (top-posted), so they appear out of order. In a forum like this one, the convention is to add your remarks after the part you're quoting. Use a hex viewer to see what the file actually looks like. My guess doesn't apply, since if you had the reverse problem (reading text file in a Windows program that was generated in Linux) MIGHT have a symptom of showing all the lines concatenated. That's not what you describe. if you don't have a hex viewer, you could write one, or you could just write a function that uses repr() on the first 200 bytes of the file. As for subprocess, why would you guess that it doesn't work on Windows? Perhaps if there's something specific that you've tried, you could start a new thread showing what you tried and how it misbehaved. Don't forget to supply your environment information as well as the source code you tried, and any stack trace from the crash. -- DaveA From memilanuk at gmail.com Mon Nov 28 18:49:53 2011 From: memilanuk at gmail.com (Monte Milanuk) Date: Mon, 28 Nov 2011 17:49:53 +0000 (UTC) Subject: [Tutor] Functional tutorial covering SQL database + GUI interface Message-ID: Hello all, Thought I might ask here just to make sure my Google-fu isn't on the fritz and I'm not missing something already existing... Is there / do you know of any tutorial that covers actually using an SQL database with a GUI interface (say, sqlite and tkinter since they come packaged with python by default) to build something moderately useful like a small address book i.e. CRUD application? Seems like most of the tutorials cover isolated 'proof of concept' db access or small windows with a button and label, not a lot more. I'm kind of at that point where I think I'm ready to move beyond that to making something a little more functional and thought I might see if there were any prior works that covered this sort of thing. TIA, Monte From cranky.frankie at gmail.com Mon Nov 28 19:06:45 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 28 Nov 2011 13:06:45 -0500 Subject: [Tutor] tkinter message & button questions Message-ID: I have a program I'm testing in Python 3.1 in Windows XP using tkinker to dispay random quotes. It works except for two things. 1) The program displays a random quote of the day when it's invoked, but I want to have a "Next quote" button so that additional random quotes can be displayed. Here are the parts of the program were I get the first quote: ################################ def get_random_quote(): # create a function to get a random quote from quote_dict rq = (random.randrange(len(quote_dict))+1) # pick a random entry from the quote dictionary return rq def output_quote(): rand_quote = get_random_quote() # get a random quote quote = quote_dict[rand_quote][1] # put the quote in a string varible author = quote_dict[rand_quote][0] # put the author in a string variable om = (quote+"\n\n"+author) # format the output string variable return om out_message = output_quote() msg_widget = Message(win, anchor = NW, justify = LEFT, width = 1000, bd= 2, bg = "white", relief = SOLID, text=out_message) ################################ Here is my button the get the next quote: ################################ next_button = Button(win, text="Next Quote", command=output_quote()) # create button widget next_button.pack(side=LEFT) ################################ Even though I'm calling the same function, output_quote(), the screen is not getting refreshed. There is no error, just the new quote is not showing up in the message box. How do I refresh the message box? 2) The message widget seems to be sizing based on the size of the text you present to it. For a small quote it's small, for a longer quote it streches out wide and then adds more lines. I'd like to present a consistent sized message box when the program is run, no matter if the text is small or large, but I can't figure out how to do that. In other words, I'd like the message widget in question 1 above to display as a box capable of storing, say, 1,000 characters, even if I only give it 100, so the program looks the same every time it's invoked. Is there a way to make a default sized message widget? -- Frank L. "Cranky Frankie" Palmeri From d at davea.name Mon Nov 28 19:08:20 2011 From: d at davea.name (Dave Angel) Date: Mon, 28 Nov 2011 13:08:20 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: Message-ID: <4ED3CE14.401@davea.name> On 11/28/2011 12:47 PM, James Reynolds wrote: > On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams wrote: > >> I am trying to pass a set of tuple strings from a file to a function I That's an undefined term. Python doesn't have a type called 'tuple strings'. >> have defined. Each tuple is on a separate line, and looks something >> like this: >> ('note',2048) >> The function has two parameters , and is defined thus: def >> findindex(dval,ticks): >> Apparently, I need to cast the second value as an integer in the body >> of the function in order to work with it as such, but when I attempt >> int(ticks) I get >> ValueError: invalid literal for int() with base 10: '2048)' >> >> Upon searching for elucidation of this on the internet I find nothing >> but esoterica, at least as far as I am concerned. >> Any pointers would make me happy. >> >> -- >> Mayo Adams >> >> >> >> mayoadams at gmail.com >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > Your problem is in the error message: > > ValueError: invalid literal for int() with base 10: '2048)' > > observer, Python tells you this isn't a number: '2048)' > > Indeed, this is correct, because you '2048)' is not a number. > > What you really want to pass to '2048', which int('2048') > > can understand just fine. > > So, trim off the parenthesis, or something. > > Alternatively, since you aren't actually passing a "tuple" but something > that looks like a python tuple as a string, you could eval it: > > a = "('note',2048)" > b = eval(a) > > print a, type(a), b, type(b) > >>> ('note',2048) ('note', 2048) > In working with the second, you do normal tuple operations, like b[1] to > access that index > > When passing to a function, you do this: findindex(*b) > My two-cents: Avoid eval like the plague. It's not a tool for the beginner, it's an escape hatch when all else fails. So let's look at the first approach. First comment is that the stuff in a text file is not treated in any way the same as the stuff in the source code. Parentheses, quotes, and commas do not have any special meaning. Whenever writing data to a file, if you expect to be able to read the same data back (as opposed to giving it to a human), you need to be careful about how you format it. In effect, the writing and the reading have to be considered at the same time, and you have to decide just what constraints on the data, and what you'll do if the data doesn't meet those constraints. Nothing magic about the parentheses, and I wouldn't have written them in the first place. So what were the constraints on the original data? If you're sure neither field can have any commas in it, then you could use line.split() with a comma as a delimiter. And once you've split, you strip off the leading parenthesis on the zeroth item, and the trailing parens on the 1th item. At that point a simple int() function on the 1th item will convert the digit characters to an integer. -- DaveA From __peter__ at web.de Mon Nov 28 19:52:04 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 28 Nov 2011 19:52:04 +0100 Subject: [Tutor] tkinter message & button questions References: Message-ID: Cranky Frankie wrote: > I have a program I'm testing in Python 3.1 in Windows XP using tkinker > to dispay random quotes. It works except for two things. > > 1) The program displays a random quote of the day when it's invoked, > but I want to have a "Next quote" button so that additional random > quotes can be displayed. Here are the parts of the program were I get > the first quote: > > ################################ > def get_random_quote(): # create a function > to get a random quote from quote_dict Crankie, your comments carry very little information, but entirely mess up the formatting of the scripts you post. Please avoid all comments but those that really help understanding your program. Keep the line length under 80 chars and start a new line if that doesn't suffice. > > rq = (random.randrange(len(quote_dict))+1) # pick a > random entry from the quote dictionary > return rq > > > def output_quote(): > rand_quote = get_random_quote() # get a random quote > quote = quote_dict[rand_quote][1] # put the quote in a > string varible > author = quote_dict[rand_quote][0] # put the author in a > string variable > om = (quote+"\n\n"+author) # format the output > string variable > return om > > > out_message = output_quote() > > msg_widget = Message(win, anchor = NW, justify = LEFT, width = 1000, > bd= 2, bg = "white", > relief = SOLID, text=out_message) > > ################################ > > > Here is my button the get the next quote: > > ################################ > > next_button = Button(win, text="Next Quote", command=output_quote()) # Here you are assigning the result of an output_quote() call (i. e. one of your quotes) to the command parameter. To get a new quote you need command be a function that somehow displays a new quote def update_quote(): # your code to make a new quote appear # on the screen next_button = Button(..., command=update_quote) Note the missing (), you are really passing the function > create button widget > next_button.pack(side=LEFT) > > ################################ > > Even though I'm calling the same function, output_quote(), the screen > is not getting refreshed. There is no error, just the new quote is not > showing up in the message box. How do I refresh the message box? > > 2) The message widget seems to be sizing based on the size of the text > you present to it. For a small quote it's small, for a longer quote it > streches out wide and then adds more lines. I'd like to present a > consistent sized message box when the program is run, no matter if the > text is small or large, but I can't figure out how to do that. In > other words, I'd like the message widget in question 1 above to > display as a box capable of storing, say, 1,000 characters, even if I > only give it 100, so the program looks the same every time it's > invoked. Is there a way to make a default sized message widget? You may need another layout manager (.place()). From alan.gauld at btinternet.com Mon Nov 28 23:20:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 28 Nov 2011 22:20:23 +0000 Subject: [Tutor] Functional tutorial covering SQL database + GUI interface In-Reply-To: References: Message-ID: On 28/11/11 17:49, Monte Milanuk wrote: > Is there / do you know of any tutorial that covers actually using an SQL > database with a GUI interface (say, sqlite and tkinter since they come > packaged with python by default) to build something moderately useful like a > small address book i.e. CRUD application? My tutorial shows how to build an address book in SqlLite. But it doesn't add the GUI layer. But the GUI is pretty much independant of the SQL Layer (or should be!) The Case Study app shows a more representative GUI with some radio buttons and a Text widget(where you could dump the result of a SQL qwuery for example...) > Seems like most of the tutorials cover isolated 'proof of concept' db access > or small windows with a button and label, not a lot more. Thats all most tutorials will cover, its an exercise for the reader to join all the bits together :-) But seriously, if I ever get round to finishing the missing topics I do intend to take the address book right through to a web application on top of a SQL database.... Just finding the time is the problem. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Chare at labr.net Mon Nov 28 23:05:45 2011 From: Chare at labr.net (Chris Hare) Date: Mon, 28 Nov 2011 16:05:45 -0600 Subject: [Tutor] advice Message-ID: I have been searching around a bit, but not really finding anything which is meaningful. I want to embed a set of help files in my application, and display them from within the application. I could use plain text files, which would be easy to suck into a Text field, but it would be nice to include rich text features and maybe even graphics. Is there some way of displaying rich text files, such as RTF or HTML from within a python Tkinter widget? Thanks Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 29 00:14:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Nov 2011 10:14:48 +1100 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: Message-ID: <4ED415E8.20406@pearwood.info> James Reynolds wrote: > Alternatively, since you aren't actually passing a "tuple" but something > that looks like a python tuple as a string, you could eval it: Please don't give beginners terrible advice like this. There are already too many programs vulnerable to code injection attacks without us encouraging newbies to write more. If anyone here doesn't know what a code injection attack is, and what it has to do with eval and exec, then please do not write another line of code until you have have learned. > a = "('note',2048)" > b = eval(a) And then one day somebody finds a way of passing input like this to your web server using that code: "__import__('os').system('echo i got you now rm-rf')" Say goodnight Gracie. I hope you have good backups. -- Steven From alan.gauld at btinternet.com Tue Nov 29 01:45:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 29 Nov 2011 00:45:36 +0000 Subject: [Tutor] advice In-Reply-To: References: Message-ID: On 28/11/11 22:05, Chris Hare wrote: > Is there some way of displaying rich text files, such as RTF or HTML > from within a python Tkinter widget? Not so much RTF but you can set different fonts and colours etc within the standard text widget. You could either use HTML or a subset to save your styles and interpret that when loading the widget. But its much more common these days to just use HTML and launch a browser. The browser module may help there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Tue Nov 29 03:59:40 2011 From: d at davea.name (Dave Angel) Date: Mon, 28 Nov 2011 21:59:40 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: <4ED3CE14.401@davea.name> Message-ID: <4ED44A9C.3090500@davea.name> 1. Please post messages to the list, a private response is not appropriate unless it's just a thanks, or other private msg. Easiest way is probably to use Reply-All. 2. Don't top-post. Put your responses AFTER whatever you're quoting. It's a forum policy, for most usenet groups. On 11/28/2011 01:45 PM, Mayo Adams wrote: > Thanks for your reply. I didn't say Python had a type called "tuple > strings", just that the lines in the file were tuples, and that the > elements of each tuple were strings. I suppose that is what I should > have said. Still wrong on both counts. A tuple does not and cannot exist in such a file. And the original tuple must have consisted of a string and a number. > If I knew how to avoid the parenthesis, I would have, and it is > helpful to know that there is nothing meaningful about the > parentheses, as you say. Ill try to find a way to write the data to > the file without the parentheses. The parentheses is only part of the problem. You still haven't defined what constraints you had on the data in those tuples. If you do, we can suggest various ways to store the data so that it's easy, efficient, and/or possible to retrieve it again. Now since your message was out of order, I had to delete all the rest of the history. -- DaveA From mlybrand at gmail.com Tue Nov 29 04:36:18 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Mon, 28 Nov 2011 19:36:18 -0800 Subject: [Tutor] Critique and Question In-Reply-To: <4ED3C900.1040205@davea.name> References: <4ED37DFC.7010808@davea.name> <4ED3C900.1040205@davea.name> Message-ID: Just so y'all know, I replaced all the urlopen, read, write, nonsense with the following: urllib.request.urlretrieve(url_root + this_file, os.path.join(file_root, this_file)) and it's all good :) Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Nov 29 05:25:42 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 28 Nov 2011 23:25:42 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: Message-ID: <4ED45EC6.3030101@gmail.com> On 11/28/2011 12:47 PM, James Reynolds wrote: > > > On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams > wrote: > > I am trying to pass a set of tuple strings from a file to a function I > have defined. Each tuple is on a separate line, and looks something > like this: > ('note',2048) > As already pointed out - this is a string (a representation of a tuple), not a tuple. Your code must parse the string to extract the string representations of the values, then convert as needed to the desired Python values. Tasks like this are not trivial. Using eval as already noted is the easiest but not the best solution. Perhaps we should back up and ask the overall objective of the program. Where did this file come from? Could we store the data in some other (easier to parse) manner? If each line will always contain a string literal and an integer literal then the simplest encoding is: note 2048 the program then is: for line in file(path): val1, val2 = line.split) findindex(val1, int(val2)) Also see http://docs.python.org/library/json.html > The function has two parameters , and is defined thus: def > findindex(dval,ticks): > Apparently, I need to cast the second value as an integer in the body > of the function in order to work with it as such, but when I attempt > int(ticks) I get > ValueError: invalid literal for int() with base 10: '2048)' > > Upon searching for elucidation of this on the internet I find nothing > but esoterica, at least as far as I am concerned. > Any pointers would make me happy. > > -- > Mayo Adams > > > > mayoadams at gmail.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > Your problem is in the error message: > > ValueError: invalid literal for int() with base 10: '2048)' > > observer, Python tells you this isn't a number: '2048)' > > Indeed, this is correct, because you '2048)' is not a number. > > What you really want to pass to '2048', which int('2048') > > can understand just fine. > > So, trim off the parenthesis, or something. > > Alternatively, since you aren't actually passing a "tuple" but > something that looks like a python tuple as a string, you could eval it: > > a = "('note',2048)" > b = eval(a) > > print a, type(a), b, type(b) > > >> ('note',2048) ('note', 2048) > > In working with the second, you do normal tuple operations, like b[1] > to access that index > > When passing to a function, you do this: findindex(*b) > > > _______________________________________________ > 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 bgailer at gmail.com Tue Nov 29 05:31:07 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 28 Nov 2011 23:31:07 -0500 Subject: [Tutor] Coin game In-Reply-To: References: Message-ID: <4ED4600B.2020806@gmail.com> On 11/27/2011 7:43 PM, Guess?!? wrote: > > Two players take turns flipping a fair coin. The game ends when the > same outcome occurs on three flips in a row. Whichever player flipped > the coin last, wins. For example: > > Here's my version of a simple compact program. import random N = 10 tosses = ''.join(random.choice("HT") for i in range (N)) w = min(tosses.find("TTT") % N + 1,tosses.find("HHH") % N + 1) if w == N: print 'no winner' else: print tosses[:w+2], 'player %s wins.' %((w % 2) + 1,) -- Bob Gailer 919-636-4239 Chapel Hill NC From mlybrand at gmail.com Tue Nov 29 05:30:13 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Mon, 28 Nov 2011 20:30:13 -0800 Subject: [Tutor] useful function or reinventing the wheel?? Message-ID: I am a habitual wheel re-inventor, so it would not surprise me, but I made this little function that I was kinda proud of (seeing that I have only been learning python like a week now): It just takes a directory and checks to see if all the directories, sub-directories exist and creates them if they don't: def insure_exists_dir(dir): grow_path = [dir] while not os.path.ismount(grow_path[0]): part_tuple = os.path.split(grow_path[0]) grow_path.insert(0, part_tuple[0]) del(grow_path[0]) while grow_path: if not os.path.exists(grow_path[0]): os.mkdir(grow_path[0]) del(grow_path[0]) return(dir) Opinions? What should I really be using? -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Nov 29 06:07:16 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 00:07:16 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: <4ED45EC6.3030101@gmail.com> References: <4ED45EC6.3030101@gmail.com> Message-ID: <4ED46884.4070600@davea.name> On 11/28/2011 11:25 PM, bob gailer wrote: > On 11/28/2011 12:47 PM, James Reynolds wrote: >> >> >> On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams > > wrote: >> >> I am trying to pass a set of tuple strings from a file to a >> function I >> have defined. Each tuple is on a separate line, and looks something >> like this: >> ('note',2048) >> > > As already pointed out - this is a string (a representation of a > tuple), not a tuple. > > Your code must parse the string to extract the string representations > of the values, then convert as needed to the desired Python values. > > Tasks like this are not trivial. > > Using eval as already noted is the easiest but not the best solution. > > Perhaps we should back up and ask the overall objective of the > program. Where did this file come from? Could we store the data in > some other (easier to parse) manner? > This file came from the OP's other thread, "Re: [Tutor] write list of tuples to file (beginner)" At that point, he didn't say what the file was for. > If each line will always contain a string literal and an integer > literal then the simplest encoding is: > note 2048 > > the program then is: > > for line in file(path): > val1, val2 = line.split) > findindex(val1, int(val2)) > Well, this also assumes the string has no whitespace in its internals. As i said in my last response, the first thing that's needed is a complete spec on what these arguments might be. We have an example of 1, that happens not to have any quotes, commas, spaces or anything else interesting in the string. And the number happens to be an integer. can we assume much? Not really. -- DaveA From d at davea.name Tue Nov 29 06:12:21 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 00:12:21 -0500 Subject: [Tutor] useful function or reinventing the wheel?? In-Reply-To: References: Message-ID: <4ED469B5.1040105@davea.name> On 11/28/2011 11:30 PM, Mark Lybrand wrote: > I am a habitual wheel re-inventor, so it would not surprise me, but I made > this little function that I was kinda proud of (seeing that I have only > been learning python like a week now): > > It just takes a directory and checks to see if all the directories, > sub-directories exist and creates them if they don't: > > def insure_exists_dir(dir): > grow_path = [dir] > while not os.path.ismount(grow_path[0]): > part_tuple = os.path.split(grow_path[0]) > grow_path.insert(0, part_tuple[0]) > > del(grow_path[0]) > while grow_path: > if not os.path.exists(grow_path[0]): > os.mkdir(grow_path[0]) > del(grow_path[0]) > return(dir) > > > Opinions? What should I really be using? > I couldn't follow your code, but finally concluded that it's trying to create a directory, creating the directories parents also if they don't exist either. It would be much simpler if written recursively, but there's no need. Check out os.makedirs(), and see if it meets your needs. (that's makedirs() function, in the os module) -- DaveA From mlybrand at gmail.com Tue Nov 29 06:19:39 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Mon, 28 Nov 2011 21:19:39 -0800 Subject: [Tutor] useful function or reinventing the wheel?? In-Reply-To: <4ED469B5.1040105@davea.name> References: <4ED469B5.1040105@davea.name> Message-ID: > > >> I couldn't follow your code, but finally concluded that it's trying to > create a directory, creating the directories parents also if they don't > exist either. It would be much simpler if written recursively, but there's > no need. > > Check out os.makedirs(), and see if it meets your needs. (that's > makedirs() function, in the os module) > > Okay, so I guess commenting is in order :) "It was hard for me to write it, so it should be hard for you to read it." comes to mind. And I will probably try to write it recursively based on your suggestion, even though long term, I will just make use of os.makedirs, since that was what I was re-inventing. thanks > > > -- > > DaveA > > -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Nov 29 07:22:53 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 01:22:53 -0500 Subject: [Tutor] useful function or reinventing the wheel?? In-Reply-To: References: <4ED469B5.1040105@davea.name> Message-ID: <4ED47A3D.4020100@davea.name> On 11/29/2011 12:19 AM, Mark Lybrand wrote: >> >> >>> I couldn't follow your code, but finally concluded that it's trying to >> create a directory, creating the directories parents also if they don't >> exist either. It would be much simpler if written recursively, but there's >> no need. >> >> Check out os.makedirs(), and see if it meets your needs. (that's >> makedirs() function, in the os module) >> >> > Okay, so I guess commenting is in order :) "It was hard for me to write > it, so it should be hard for you to read it." comes to mind. > > And I will probably try to write it recursively based on your suggestion, > even though long term, I will just make use of os.makedirs, since that was > what I was re-inventing. > You're welcome. I'd look forward to seeing your rewrite, and whether it's really shorter and more straightforward. Another advantage is doing less disk I/O if you start by trying the requested directory directly, and only recursing to parents if you can't make the requested directory. I took a quick stab at it (ask me later for mark.py) and it wasn't as straightforward as I expected. The main problem comes down to how to define the base case. I think you might have the same problem also. You assume that you can safely go back to the mount point. But if the path given is relative, you have to allow for that as well. Perhaps a call to os.path.abspath is in order. I also think that ismount() might not be legal on Windows, if you care about that. Also, we have to worry about what happens when one of the directories cannot be made for reasons unrelated to the syntax of the string. For example, the user might not have write permissions for one or more of the directories. In fact, the user might not have read permissions either. -- DaveA From o0MB0o at hotmail.se Tue Nov 29 09:37:28 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 09:37:28 +0100 Subject: [Tutor] How to handle try and except in this case In-Reply-To: References: Message-ID: On 2011-11-27 17:58, Mic wrote: >> Say that I want to try and open 10 files. If none of these exists, I want >> an >> error >> message to appear. But only if NONE of these files exists. >> I know how to handle this with one file. But I don't know how to do that >> with more than one. >> So the program should try and open all 10 files and if, and only if, none >> of the files exists I want en error message to appear. [Andreas wrote]: >Use a counter which increments with every existing file. After opening >all files check if the counter is bigger than 0. >Or, if you need to know which files exist, use a list, append existing >files to it and check at the end if it's not empty. >Do you need more help? Andreas, Thanks for your answer. I am afraid I don't understand this: "Use a counter which increments with every existing file. After opening all files check if the counter is bigger than 0." I thought I could co along those lines earlier try: text_file=open("Hey","r") and text_file1=open("Hey","r") except: print("hi") So that hi is printed only and only if both files aren't existing. Thank you! From mlybrand at gmail.com Tue Nov 29 09:37:40 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Tue, 29 Nov 2011 00:37:40 -0800 Subject: [Tutor] useful function or reinventing the wheel?? In-Reply-To: <4ED47A3D.4020100@davea.name> References: <4ED469B5.1040105@davea.name> <4ED47A3D.4020100@davea.name> Message-ID: > > > You're welcome. I'd look forward to seeing your rewrite, and whether it's > really shorter and more straightforward. > > Another advantage is doing less disk I/O if you start by trying the > requested directory directly, and only recursing to parents if you can't > make the requested directory. > > I took a quick stab at it (ask me later for mark.py) and it wasn't as > straightforward as I expected. The main problem comes down to how to > define the base case. I think you might have the same problem also. You > assume that you can safely go back to the mount point. But if the path > given is relative, you have to allow for that as well. Perhaps a call to > os.path.abspath is in order. I also think that ismount() might not be > legal on Windows, if you care about that. > > Also, we have to worry about what happens when one of the directories > cannot be made for reasons unrelated to the syntax of the string. For > example, the user might not have write permissions for one or more of the > directories. In fact, the user might not have read permissions either. > > I am actually passing in the path already os.path.abspath-ed. So, I should probably move that into the function for better encapsulation. I am on Windows, so ismount is behaving correctly (I tested it in Idle before going with that as my base case). Since this will end up being a throw-away, I will probably not worry too much about permissions and failures, but I can appreciate the need for such checks, should I decide to keep this for more widespread use. Thanks again. I will send my solution when I get a chance to get back to it (gotta get myself ahead in machine learning before the weekend gets too close :) Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlybrand at gmail.com Tue Nov 29 09:42:01 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Tue, 29 Nov 2011 00:42:01 -0800 Subject: [Tutor] Programming Collective Intelligence Study Group Message-ID: Over on the Machine Learning Class, I mentioned the idea of setting up some online resources to go through the Programming Collective Intelligence book as a group. This would include a group or discussion board of some type, maybe a Google+ or Facebook page, and a wiki. Then we would set a pace and work through the book. Since it is in Python, I thought this group would be interested. Am I wrong? If it works out pretty good, we will probably continue with Natural Language Processing (also Python) after we finish. So, what is the interest like here? Let me know and I will give you guys a heads up when I get everything all set up. -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From stm.at.oc at googlemail.com Tue Nov 29 09:51:45 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Tue, 29 Nov 2011 09:51:45 +0100 Subject: [Tutor] Do loop in Python In-Reply-To: <4ED00C20.9090509@gmx.net> References: <4ECF7DB5.60305@pearwood.info> <4ED00C20.9090509@gmx.net> Message-ID: Thank you so much. This script and all information was totally helpful and actually helped me for the next step of my work as well. Have a great time..... Sue On Fri, Nov 25, 2011 at 10:44 PM, Andreas Perstinger wrote: > On 2011-11-25 14:46, stm atoc wrote: >> >> Here is the new version of the program: >> >> zvalues = [-200] ?# starting value >> hvalues = [10] ?# starting value >> increments = [1, 1, 1, 1, 1, 1, 1, 1] >> for N in increments: >> ? ? ? ?h = hvalues[-1] - N >> ? ? ? ?hvalues.append(h) >> ? ? ? ?z = zvalues[-1] + h >> ? ? ? ?zvalues.append(z) >> ? ? ? ?height = arange((z)*dz,0,dz) > > > There is no "arange" in python. Could it be that you use numpy and import it > with "from numpy import *"? > >> ? ? ? ?for z,when in enumerate(height): > > > I'm pretty sure this line doesn't do what you expect it to do. You have a > sequence (a numpy array) named "height" and after calling "enumerate" you > get a list of tuples in the form of [(0, height[0]), (1, height[1]), ...]. > Now the for-loop iterates over this list and assigns "z" to the first value > of the tuple (the index-values) and "when" to the second (the values from > "height"). You later never use "when" but just use "z". If you really want > that, the "enumerate" is completly unnecessary and you could just use "for z > in range(len(height))". But I'm not sure if numpy arrays work with "len()". > > >> ? ? ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence >> diffusivity m**2/s >> ? ? ? ? ? ?nu.append(num + nuh[z]) >> >> The story is like this: >> I should define layers and thickness and see how the diffusion profile >> changes over the z. >> height (or depth) of the total thickness or 'z'. >> I basically, define 'z' in 10 layers and each layer is called ?' N' . >> Difference between each layer is 'h', which is equal 10 micrometer. >> Now, what I like to do is the modification of nu based on each zvalue >> In fact, for each 'zvalue' o'z' step, I need to calculate a different >> value for 'nu' based on the available equation in the program. >> >> BUT, I am not sure, exactly, how to add the new do loop of z inside >> another loop of nu. > > > For me your explanations are still too confusing. Could it be that you are > thinking way too complicated? > > My guess is you want to have a range of material thicknesses (from 1 to 200 > micrometers in 10 micrometer-steps) and then you want from each thickness 10 > different layers, right? > > import math # you should always tell us which modules you import > num = 0.05 # some constant > nu = [] # list of resulting values > h = 10.0 # height of one layer > thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, 10, > 20, ..., 190, 200) > layers = range(1,11) # a list from 1 to 10 > for t in thickness: > ?for l in layers: > ? ?z = t + h * l # I'm not sure if you want to add or subtract the layer > thickness > ? ?nu = num + (0.01 * math.exp(-0.05 * (z + 200.0))) > > This will result in a big one-dimensional list where you calculate for each > thickness the nu-value for 10 layers. Am I close? > I'm still not sure about the steps and the height of the layers. I also > wonder if it wouldn't be better to use a two-dimensional list. > > >> I have done this way as well (the other way around): >> >> height = arange((z)*dz,0,dz) >> for z,when in enumerate(height): >> ? ? for N in increments: >> ? ? ? ?h = hvalues[-1] - N >> ? ? ? ?hvalues.append(h) >> ? ? ? ?z = zvalues[-1] + h >> ? ? ? ?zvalues.append(z) >> ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence >> diffusivity m**2/s >> ? ? ? ?nu.append(num + nuh[z]) >> >> but still no sign of 'nu changes' over 'z'! > > > As Charles has already mentioned, the values for "nu" are very similar (they > start beginning to differ just at the seventh digit after the comma). How do > you further process this values? If you plot them what's your scale? > > Bye, Andreas > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Tue Nov 29 10:17:55 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 04:17:55 -0500 Subject: [Tutor] How to handle try and except in this case In-Reply-To: References: Message-ID: <4ED4A343.1020406@davea.name> On 11/29/2011 03:37 AM, Mic wrote: > > On 2011-11-27 17:58, Mic wrote: >>> Say that I want to try and open 10 files. If none of these exists, I >>> want an >>> error >>> message to appear. But only if NONE of these files exists. > >>> I know how to handle this with one file. But I don't know how to do >>> that >>> with more than one. >>> So the program should try and open all 10 files and if, and only if, >>> none >>> of the files exists I want en error message to appear. > > > [Andreas wrote]: >> Use a counter which increments with every existing file. After opening >> all files check if the counter is bigger than 0. > >> Or, if you need to know which files exist, use a list, append existing >> files to it and check at the end if it's not empty. > >> Do you need more help? > > Andreas, > > > Thanks for your answer. I am afraid I don't understand this: > "Use a counter which increments with every existing file. After opening > all files check if the counter is bigger than 0." > Could you explain what's unclear about it? Andreas couldn't get more specific, since you didn't say how these 10 names are provided. If they're in a list called filenames, you could do something like: fileobjects = [] for fname in filenames: try: fileobj = open(fname, "r") fileobjects.append(fileobj) catch SomeExceptionType as e: pass and when you're done, use something like: if len(fileobjects) == 0: print "no files could be opened" > > I thought I could co along those lines earlier > > try: > text_file=open("Hey","r") and text_file1=open("Hey","r") Unfortunately this isn't valid Python syntax. The equal sign has a specific statement syntax, and the only time you can have more than one of them in one statement, is the chained assignments, where they all get bound to the same object. You wouldn't want to do this anyway, since it would leave all those open files in an unspecified state. To go one step further, if it could work, it would give an exception if any ONE of the files couldn't be open, and you want the message to appear if none of the files could be opened. > except: > print("hi") > > > So that hi is printed only and only if both files aren't existing. If you didn't need to open them, but just to make sure they exist, you could use if os.exist(filename) much more easily. -- DaveA From __peter__ at web.de Tue Nov 29 10:30:30 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Nov 2011 10:30:30 +0100 Subject: [Tutor] How to handle try and except in this case References: Message-ID: Mic wrote: > > On 2011-11-27 17:58, Mic wrote: >>> Say that I want to try and open 10 files. If none of these exists, I >>> want an >>> error >>> message to appear. But only if NONE of these files exists. > >>> I know how to handle this with one file. But I don't know how to do that >>> with more than one. >>> So the program should try and open all 10 files and if, and only if, >>> none of the files exists I want en error message to appear. > > > [Andreas wrote]: >>Use a counter which increments with every existing file. After opening >>all files check if the counter is bigger than 0. > >>Or, if you need to know which files exist, use a list, append existing >>files to it and check at the end if it's not empty. > >>Do you need more help? > > Andreas, > > > Thanks for your answer. I am afraid I don't understand this: > "Use a counter which increments with every existing file. After opening > all files check if the counter is bigger than 0." > > > I thought I could co along those lines earlier > > try: > text_file=open("Hey","r") and text_file1=open("Hey","r") > except: > print("hi") > > > So that hi is printed only and only if both files aren't existing. filenames = ["file1.txt", "file2.txt"] files = [] for name in filenames: try: files.append(open(name)) except IOError: pass if not files: print("couldn't open any files") If you don't need the file objects: filenames = ["file1.txt", "file2.txt"] if not any(os.path.exists(name) for name in filenames): print("didn't find any existing files") From tommy at enkelthed.dk Tue Nov 29 10:44:11 2011 From: tommy at enkelthed.dk (tommy at enkelthed.dk) Date: Tue, 29 Nov 2011 10:44:11 +0100 Subject: [Tutor] Programming Collective Intelligence Study Group (Mark Lybrand) In-Reply-To: References: Message-ID: <69e2ce06b4b1d51210fedda6bb319097@mail01> Hey Mark Id be very much interested in this. While I mostly lurk on the python mailing list and have only dabbled in a few quick scripts. Then I wouldnt mind getting deeper into via a collective group. This is the first I've heard of this, Im not sure if you've posted before but which book are you using? /Regards Tommy On Tue, 29 Nov 2011 10:18:25 +0100, tutor-request at python.org wrote: > 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: How to handle try and except in this case (Mic) > 2. Re: useful function or reinventing the wheel?? (Mark Lybrand) > 3. Programming Collective Intelligence Study Group (Mark Lybrand) > 4. Re: Do loop in Python (stm atoc) > 5. Re: How to handle try and except in this case (Dave Angel) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 29 Nov 2011 09:37:28 +0100 > From: "Mic" > To: > Subject: Re: [Tutor] How to handle try and except in this case > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > On 2011-11-27 17:58, Mic wrote: >>> Say that I want to try and open 10 files. If none of these exists, I >>> want >>> an >>> error >>> message to appear. But only if NONE of these files exists. > >>> I know how to handle this with one file. But I don't know how to do that >>> with more than one. >>> So the program should try and open all 10 files and if, and only if, >>> none >>> of the files exists I want en error message to appear. > > > [Andreas wrote]: >>Use a counter which increments with every existing file. After opening >>all files check if the counter is bigger than 0. > >>Or, if you need to know which files exist, use a list, append existing >>files to it and check at the end if it's not empty. > >>Do you need more help? > > Andreas, > > > Thanks for your answer. I am afraid I don't understand this: > "Use a counter which increments with every existing file. After opening > all files check if the counter is bigger than 0." > > > I thought I could co along those lines earlier > > try: > text_file=open("Hey","r") and text_file1=open("Hey","r") > except: > print("hi") > > > So that hi is printed only and only if both files aren't existing. > > > Thank you! > > > > > > > > ------------------------------ > > Message: 2 > Date: Tue, 29 Nov 2011 00:37:40 -0800 > From: Mark Lybrand > To: d at davea.name > Cc: tutor at python.org > Subject: Re: [Tutor] useful function or reinventing the wheel?? > Message-ID: > > Content-Type: text/plain; charset="utf-8" > >> >> >> You're welcome. I'd look forward to seeing your rewrite, and whether >> it's >> really shorter and more straightforward. >> >> Another advantage is doing less disk I/O if you start by trying the >> requested directory directly, and only recursing to parents if you can't >> make the requested directory. >> >> I took a quick stab at it (ask me later for mark.py) and it wasn't as >> straightforward as I expected. The main problem comes down to how to >> define the base case. I think you might have the same problem also. You >> assume that you can safely go back to the mount point. But if the path >> given is relative, you have to allow for that as well. Perhaps a call to >> os.path.abspath is in order. I also think that ismount() might not be >> legal on Windows, if you care about that. >> >> Also, we have to worry about what happens when one of the directories >> cannot be made for reasons unrelated to the syntax of the string. For >> example, the user might not have write permissions for one or more of the >> directories. In fact, the user might not have read permissions either. >> >> > I am actually passing in the path already os.path.abspath-ed. So, I should > probably move that into the function for better encapsulation. I am on > Windows, so ismount is behaving correctly (I tested it in Idle before going > with that as my base case). Since this will end up being a throw-away, I > will probably not worry too much about permissions and failures, but I can > appreciate the need for such checks, should I decide to keep this for more > widespread use. > > Thanks again. I will send my solution when I get a chance to get back to > it (gotta get myself ahead in machine learning before the weekend gets too > close :) > > Mark > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 3 > Date: Tue, 29 Nov 2011 00:42:01 -0800 > From: Mark Lybrand > To: tutor at python.org > Subject: [Tutor] Programming Collective Intelligence Study Group > Message-ID: > > Content-Type: text/plain; charset="utf-8" > > Over on the Machine Learning Class, I mentioned the idea of setting up some > online resources to go through the Programming Collective Intelligence book > as a group. This would include a group or discussion board of some type, > maybe a Google+ or Facebook page, and a wiki. Then we would set a pace and > work through the book. Since it is in Python, I thought this group would > be interested. Am I wrong? If it works out pretty good, we will probably > continue with Natural Language Processing (also Python) after we finish. > > So, what is the interest like here? Let me know and I will give you guys a > heads up when I get everything all set up. > > -- > Mark :) > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 4 > Date: Tue, 29 Nov 2011 09:51:45 +0100 > From: stm atoc > To: Andreas Perstinger > Cc: tutor at python.org > Subject: Re: [Tutor] Do loop in Python > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > Thank you so much. This script and all information was totally helpful > and actually helped me for the next step of my work as well. > > Have a great time..... > Sue > > On Fri, Nov 25, 2011 at 10:44 PM, Andreas Perstinger > wrote: >> On 2011-11-25 14:46, stm atoc wrote: >>> >>> Here is the new version of the program: >>> >>> zvalues = [-200] ?# starting value >>> hvalues = [10] ?# starting value >>> increments = [1, 1, 1, 1, 1, 1, 1, 1] >>> for N in increments: >>> ? ? ? ?h = hvalues[-1] - N >>> ? ? ? ?hvalues.append(h) >>> ? ? ? ?z = zvalues[-1] + h >>> ? ? ? ?zvalues.append(z) >>> ? ? ? ?height = arange((z)*dz,0,dz) >> >> >> There is no "arange" in python. Could it be that you use numpy and >> import it >> with "from numpy import *"? >> >>> ? ? ? ?for z,when in enumerate(height): >> >> >> I'm pretty sure this line doesn't do what you expect it to do. You have a >> sequence (a numpy array) named "height" and after calling "enumerate" you >> get a list of tuples in the form of [(0, height[0]), (1, height[1]), >> ...]. >> Now the for-loop iterates over this list and assigns "z" to the first >> value >> of the tuple (the index-values) and "when" to the second (the values from >> "height"). You later never use "when" but just use "z". If you really >> want >> that, the "enumerate" is completly unnecessary and you could just use >> "for z >> in range(len(height))". But I'm not sure if numpy arrays work with >> "len()". >> >> >>> ? ? ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence >>> diffusivity m**2/s >>> ? ? ? ? ? ?nu.append(num + nuh[z]) >>> >>> The story is like this: >>> I should define layers and thickness and see how the diffusion profile >>> changes over the z. >>> height (or depth) of the total thickness or 'z'. >>> I basically, define 'z' in 10 layers and each layer is called ?' N' . >>> Difference between each layer is 'h', which is equal 10 micrometer. >>> Now, what I like to do is the modification of nu based on each zvalue >>> In fact, for each 'zvalue' o'z' step, I need to calculate a different >>> value for 'nu' based on the available equation in the program. >>> >>> BUT, I am not sure, exactly, how to add the new do loop of z inside >>> another loop of nu. >> >> >> For me your explanations are still too confusing. Could it be that you >> are >> thinking way too complicated? >> >> My guess is you want to have a range of material thicknesses (from 1 to >> 200 >> micrometers in 10 micrometer-steps) and then you want from each >> thickness 10 >> different layers, right? >> >> import math # you should always tell us which modules you import >> num = 0.05 # some constant >> nu = [] # list of resulting values >> h = 10.0 # height of one layer >> thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, 10, >> 20, ..., 190, 200) >> layers = range(1,11) # a list from 1 to 10 >> for t in thickness: >> ?for l in layers: >> ? ?z = t + h * l # I'm not sure if you want to add or subtract the layer >> thickness >> ? ?nu = num + (0.01 * math.exp(-0.05 * (z + 200.0))) >> >> This will result in a big one-dimensional list where you calculate for >> each >> thickness the nu-value for 10 layers. Am I close? >> I'm still not sure about the steps and the height of the layers. I also >> wonder if it wouldn't be better to use a two-dimensional list. >> >> >>> I have done this way as well (the other way around): >>> >>> height = arange((z)*dz,0,dz) >>> for z,when in enumerate(height): >>> ? ? for N in increments: >>> ? ? ? ?h = hvalues[-1] - N >>> ? ? ? ?hvalues.append(h) >>> ? ? ? ?z = zvalues[-1] + h >>> ? ? ? ?zvalues.append(z) >>> ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence >>> diffusivity m**2/s >>> ? ? ? ?nu.append(num + nuh[z]) >>> >>> but still no sign of 'nu changes' over 'z'! >> >> >> As Charles has already mentioned, the values for "nu" are very similar >> (they >> start beginning to differ just at the seventh digit after the comma). >> How do >> you further process this values? If you plot them what's your scale? >> >> Bye, Andreas >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > Message: 5 > Date: Tue, 29 Nov 2011 04:17:55 -0500 > From: Dave Angel > To: Mic > Cc: tutor at python.org > Subject: Re: [Tutor] How to handle try and except in this case > Message-ID: <4ED4A343.1020406 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 11/29/2011 03:37 AM, Mic wrote: >> >> On 2011-11-27 17:58, Mic wrote: >>>> Say that I want to try and open 10 files. If none of these exists, I >>>> want an >>>> error >>>> message to appear. But only if NONE of these files exists. >> >>>> I know how to handle this with one file. But I don't know how to do >>>> that >>>> with more than one. >>>> So the program should try and open all 10 files and if, and only if, >>>> none >>>> of the files exists I want en error message to appear. >> >> >> [Andreas wrote]: >>> Use a counter which increments with every existing file. After opening >>> all files check if the counter is bigger than 0. >> >>> Or, if you need to know which files exist, use a list, append existing >>> files to it and check at the end if it's not empty. >> >>> Do you need more help? >> >> Andreas, >> >> >> Thanks for your answer. I am afraid I don't understand this: >> "Use a counter which increments with every existing file. After opening >> all files check if the counter is bigger than 0." >> > Could you explain what's unclear about it? Andreas couldn't get more > specific, since you didn't say how these 10 names are provided. If > they're in a list called filenames, you could do something like: > > fileobjects = [] > for fname in filenames: > try: > fileobj = open(fname, "r") > fileobjects.append(fileobj) > catch SomeExceptionType as e: > pass > > and when you're done, use something like: > > if len(fileobjects) == 0: > print "no files could be opened" > >> >> I thought I could co along those lines earlier >> >> try: >> text_file=open("Hey","r") and text_file1=open("Hey","r") > > Unfortunately this isn't valid Python syntax. The equal sign has a > specific statement syntax, and the only time you can have more than one > of them in one statement, is the chained assignments, where they all get > bound to the same object. You wouldn't want to do this anyway, since it > would leave all those open files in an unspecified state. > > To go one step further, if it could work, it would give an exception if > any ONE of the files couldn't be open, and you want the message to > appear if none of the files could be opened. > >> except: >> print("hi") >> >> >> So that hi is printed only and only if both files aren't existing. > If you didn't need to open them, but just to make sure they exist, you > could use if os.exist(filename) much more easily. From steve at pearwood.info Tue Nov 29 10:53:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Nov 2011 20:53:27 +1100 Subject: [Tutor] Programming Collective Intelligence Study Group In-Reply-To: References: Message-ID: <4ED4AB97.9030300@pearwood.info> Mark Lybrand wrote: > Over on the Machine Learning Class, I mentioned the idea of setting up some > online resources to go through the Programming Collective Intelligence book What are the Machine Learning Class and the Programming Collective Intelligence book? Should I have heard of them before? > as a group. This would include a group or discussion board of some type, > maybe a Google+ or Facebook page, and a wiki. Then we would set a pace and If it's Google+ or Facebook, count me out. > work through the book. Since it is in Python, I thought this group would > be interested. Am I wrong? If I had any idea what you were talking about, other than "something to do with Python", then I might be. -- Steven From mlybrand at gmail.com Tue Nov 29 11:04:04 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Tue, 29 Nov 2011 02:04:04 -0800 Subject: [Tutor] Programming Collective Intelligence Study Group (Mark Lybrand) In-Reply-To: <69e2ce06b4b1d51210fedda6bb319097@mail01> References: <69e2ce06b4b1d51210fedda6bb319097@mail01> Message-ID: Sorry about that. The book is called Programming Collective Intelligence. It is from O'Reilly Press. It is written by Toby Segaran. ISBN-13: 978-0596529321. There is a PDF on the web, if you google around, but it doesn't seem that kosher to me, so you are on your own if you decide to go that route. The other book that we are considering afterwards is Natural Language Processing with Python. Also from O'Reilly. Written by Steven Bird, et al. The book is legally freely available on the web. See here: http://www.nltk.org/book I hope that helps. I will try to make my postings specific enough to be able to participate without the book. And will try to point people to information that might help. But I am also a noob (to all of it, Python, NLP, ML). Man I miss my curly braces (although not as much as I thought I would, since Python is making it real easy to love it) On Tue, Nov 29, 2011 at 1:44 AM, wrote: > Hey Mark > > Id be very much interested in this. While I mostly lurk on the python > mailing list and have only dabbled in a few quick scripts. Then I wouldnt > mind getting deeper into via a collective group. > > This is the first I've heard of this, Im not sure if you've posted before > but which book are you using? > > /Regards > Tommy > On Tue, 29 Nov 2011 10:18:25 +0100, tutor-request at python.org wrote: > > 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: How to handle try and except in this case (Mic) > > 2. Re: useful function or reinventing the wheel?? (Mark Lybrand) > > 3. Programming Collective Intelligence Study Group (Mark Lybrand) > > 4. Re: Do loop in Python (stm atoc) > > 5. Re: How to handle try and except in this case (Dave Angel) > > > > > > ---------------------------------------------------------------------- > > > > Message: 1 > > Date: Tue, 29 Nov 2011 09:37:28 +0100 > > From: "Mic" > > To: > > Subject: Re: [Tutor] How to handle try and except in this case > > Message-ID: > > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > > reply-type=original > > > > > > On 2011-11-27 17:58, Mic wrote: > >>> Say that I want to try and open 10 files. If none of these exists, I > >>> want > >>> an > >>> error > >>> message to appear. But only if NONE of these files exists. > > > >>> I know how to handle this with one file. But I don't know how to do > that > >>> with more than one. > >>> So the program should try and open all 10 files and if, and only if, > >>> none > >>> of the files exists I want en error message to appear. > > > > > > [Andreas wrote]: > >>Use a counter which increments with every existing file. After opening > >>all files check if the counter is bigger than 0. > > > >>Or, if you need to know which files exist, use a list, append existing > >>files to it and check at the end if it's not empty. > > > >>Do you need more help? > > > > Andreas, > > > > > > Thanks for your answer. I am afraid I don't understand this: > > "Use a counter which increments with every existing file. After opening > > all files check if the counter is bigger than 0." > > > > > > I thought I could co along those lines earlier > > > > try: > > text_file=open("Hey","r") and text_file1=open("Hey","r") > > except: > > print("hi") > > > > > > So that hi is printed only and only if both files aren't existing. > > > > > > Thank you! > > > > > > > > > > > > > > > > ------------------------------ > > > > Message: 2 > > Date: Tue, 29 Nov 2011 00:37:40 -0800 > > From: Mark Lybrand > > To: d at davea.name > > Cc: tutor at python.org > > Subject: Re: [Tutor] useful function or reinventing the wheel?? > > Message-ID: > > BW5H3W3pcUr0DCtpRBg--2saA at mail.gmail.com> > > Content-Type: text/plain; charset="utf-8" > > > >> > >> > >> You're welcome. I'd look forward to seeing your rewrite, and whether > >> it's > >> really shorter and more straightforward. > >> > >> Another advantage is doing less disk I/O if you start by trying the > >> requested directory directly, and only recursing to parents if you > can't > >> make the requested directory. > >> > >> I took a quick stab at it (ask me later for mark.py) and it wasn't as > >> straightforward as I expected. The main problem comes down to how to > >> define the base case. I think you might have the same problem also. > You > >> assume that you can safely go back to the mount point. But if the path > >> given is relative, you have to allow for that as well. Perhaps a call > to > >> os.path.abspath is in order. I also think that ismount() might not be > >> legal on Windows, if you care about that. > >> > >> Also, we have to worry about what happens when one of the directories > >> cannot be made for reasons unrelated to the syntax of the string. For > >> example, the user might not have write permissions for one or more of > the > >> directories. In fact, the user might not have read permissions either. > >> > >> > > I am actually passing in the path already os.path.abspath-ed. So, I > should > > probably move that into the function for better encapsulation. I am on > > Windows, so ismount is behaving correctly (I tested it in Idle before > going > > with that as my base case). Since this will end up being a throw-away, > I > > will probably not worry too much about permissions and failures, but I > can > > appreciate the need for such checks, should I decide to keep this for > more > > widespread use. > > > > Thanks again. I will send my solution when I get a chance to get back > to > > it (gotta get myself ahead in machine learning before the weekend gets > too > > close :) > > > > Mark > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > > < > http://mail.python.org/pipermail/tutor/attachments/20111129/991cc3a9/attachment-0001.html > > > > > > ------------------------------ > > > > Message: 3 > > Date: Tue, 29 Nov 2011 00:42:01 -0800 > > From: Mark Lybrand > > To: tutor at python.org > > Subject: [Tutor] Programming Collective Intelligence Study Group > > Message-ID: > > < > CALsUBtzSqtJh4MX2ixuVO-J5zTn5xqLT+O4ZdyeVSe1VJknLzg at mail.gmail.com> > > Content-Type: text/plain; charset="utf-8" > > > > Over on the Machine Learning Class, I mentioned the idea of setting up > some > > online resources to go through the Programming Collective Intelligence > book > > as a group. This would include a group or discussion board of some type, > > maybe a Google+ or Facebook page, and a wiki. Then we would set a pace > and > > work through the book. Since it is in Python, I thought this group > would > > be interested. Am I wrong? If it works out pretty good, we will > probably > > continue with Natural Language Processing (also Python) after we finish. > > > > So, what is the interest like here? Let me know and I will give you > guys a > > heads up when I get everything all set up. > > > > -- > > Mark :) > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > > < > http://mail.python.org/pipermail/tutor/attachments/20111129/82dcebaf/attachment-0001.html > > > > > > ------------------------------ > > > > Message: 4 > > Date: Tue, 29 Nov 2011 09:51:45 +0100 > > From: stm atoc > > To: Andreas Perstinger > > Cc: tutor at python.org > > Subject: Re: [Tutor] Do loop in Python > > Message-ID: > > < > CAHNhTs68PqEQ5XVk4Tn3C6hQYMENRBY1O7xnqn-fxjmdki4ftg at mail.gmail.com> > > Content-Type: text/plain; charset=ISO-8859-1 > > > > Thank you so much. This script and all information was totally helpful > > and actually helped me for the next step of my work as well. > > > > Have a great time..... > > Sue > > > > On Fri, Nov 25, 2011 at 10:44 PM, Andreas Perstinger > > wrote: > >> On 2011-11-25 14:46, stm atoc wrote: > >>> > >>> Here is the new version of the program: > >>> > >>> zvalues = [-200] ?# starting value > >>> hvalues = [10] ?# starting value > >>> increments = [1, 1, 1, 1, 1, 1, 1, 1] > >>> for N in increments: > >>> ? ? ? ?h = hvalues[-1] - N > >>> ? ? ? ?hvalues.append(h) > >>> ? ? ? ?z = zvalues[-1] + h > >>> ? ? ? ?zvalues.append(z) > >>> ? ? ? ?height = arange((z)*dz,0,dz) > >> > >> > >> There is no "arange" in python. Could it be that you use numpy and > >> import it > >> with "from numpy import *"? > >> > >>> ? ? ? ?for z,when in enumerate(height): > >> > >> > >> I'm pretty sure this line doesn't do what you expect it to do. You have > a > >> sequence (a numpy array) named "height" and after calling "enumerate" > you > >> get a list of tuples in the form of [(0, height[0]), (1, height[1]), > >> ...]. > >> Now the for-loop iterates over this list and assigns "z" to the first > >> value > >> of the tuple (the index-values) and "when" to the second (the values > from > >> "height"). You later never use "when" but just use "z". If you really > >> want > >> that, the "enumerate" is completly unnecessary and you could just use > >> "for z > >> in range(len(height))". But I'm not sure if numpy arrays work with > >> "len()". > >> > >> > >>> ? ? ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence > >>> diffusivity m**2/s > >>> ? ? ? ? ? ?nu.append(num + nuh[z]) > >>> > >>> The story is like this: > >>> I should define layers and thickness and see how the diffusion profile > >>> changes over the z. > >>> height (or depth) of the total thickness or 'z'. > >>> I basically, define 'z' in 10 layers and each layer is called ?' N' . > >>> Difference between each layer is 'h', which is equal 10 micrometer. > >>> Now, what I like to do is the modification of nu based on each zvalue > >>> In fact, for each 'zvalue' o'z' step, I need to calculate a different > >>> value for 'nu' based on the available equation in the program. > >>> > >>> BUT, I am not sure, exactly, how to add the new do loop of z inside > >>> another loop of nu. > >> > >> > >> For me your explanations are still too confusing. Could it be that you > >> are > >> thinking way too complicated? > >> > >> My guess is you want to have a range of material thicknesses (from 1 to > >> 200 > >> micrometers in 10 micrometer-steps) and then you want from each > >> thickness 10 > >> different layers, right? > >> > >> import math # you should always tell us which modules you import > >> num = 0.05 # some constant > >> nu = [] # list of resulting values > >> h = 10.0 # height of one layer > >> thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, > 10, > >> 20, ..., 190, 200) > >> layers = range(1,11) # a list from 1 to 10 > >> for t in thickness: > >> ?for l in layers: > >> ? ?z = t + h * l # I'm not sure if you want to add or subtract the > layer > >> thickness > >> ? ?nu = num + (0.01 * math.exp(-0.05 * (z + 200.0))) > >> > >> This will result in a big one-dimensional list where you calculate for > >> each > >> thickness the nu-value for 10 layers. Am I close? > >> I'm still not sure about the steps and the height of the layers. I also > >> wonder if it wouldn't be better to use a two-dimensional list. > >> > >> > >>> I have done this way as well (the other way around): > >>> > >>> height = arange((z)*dz,0,dz) > >>> for z,when in enumerate(height): > >>> ? ? for N in increments: > >>> ? ? ? ?h = hvalues[-1] - N > >>> ? ? ? ?hvalues.append(h) > >>> ? ? ? ?z = zvalues[-1] + h > >>> ? ? ? ?zvalues.append(z) > >>> ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence > >>> diffusivity m**2/s > >>> ? ? ? ?nu.append(num + nuh[z]) > >>> > >>> but still no sign of 'nu changes' over 'z'! > >> > >> > >> As Charles has already mentioned, the values for "nu" are very similar > >> (they > >> start beginning to differ just at the seventh digit after the comma). > >> How do > >> you further process this values? If you plot them what's your scale? > >> > >> Bye, Andreas > >> > >> _______________________________________________ > >> Tutor maillist ?- ?Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > > > > > > ------------------------------ > > > > Message: 5 > > Date: Tue, 29 Nov 2011 04:17:55 -0500 > > From: Dave Angel > > To: Mic > > Cc: tutor at python.org > > Subject: Re: [Tutor] How to handle try and except in this case > > Message-ID: <4ED4A343.1020406 at davea.name> > > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > > > On 11/29/2011 03:37 AM, Mic wrote: > >> > >> On 2011-11-27 17:58, Mic wrote: > >>>> Say that I want to try and open 10 files. If none of these exists, I > >>>> want an > >>>> error > >>>> message to appear. But only if NONE of these files exists. > >> > >>>> I know how to handle this with one file. But I don't know how to do > >>>> that > >>>> with more than one. > >>>> So the program should try and open all 10 files and if, and only if, > >>>> none > >>>> of the files exists I want en error message to appear. > >> > >> > >> [Andreas wrote]: > >>> Use a counter which increments with every existing file. After opening > >>> all files check if the counter is bigger than 0. > >> > >>> Or, if you need to know which files exist, use a list, append existing > >>> files to it and check at the end if it's not empty. > >> > >>> Do you need more help? > >> > >> Andreas, > >> > >> > >> Thanks for your answer. I am afraid I don't understand this: > >> "Use a counter which increments with every existing file. After opening > >> all files check if the counter is bigger than 0." > >> > > Could you explain what's unclear about it? Andreas couldn't get more > > specific, since you didn't say how these 10 names are provided. If > > they're in a list called filenames, you could do something like: > > > > fileobjects = [] > > for fname in filenames: > > try: > > fileobj = open(fname, "r") > > fileobjects.append(fileobj) > > catch SomeExceptionType as e: > > pass > > > > and when you're done, use something like: > > > > if len(fileobjects) == 0: > > print "no files could be opened" > > > >> > >> I thought I could co along those lines earlier > >> > >> try: > >> text_file=open("Hey","r") and text_file1=open("Hey","r") > > > > Unfortunately this isn't valid Python syntax. The equal sign has a > > specific statement syntax, and the only time you can have more than one > > of them in one statement, is the chained assignments, where they all get > > > bound to the same object. You wouldn't want to do this anyway, since it > > > would leave all those open files in an unspecified state. > > > > To go one step further, if it could work, it would give an exception if > > any ONE of the files couldn't be open, and you want the message to > > appear if none of the files could be opened. > > > >> except: > >> print("hi") > >> > >> > >> So that hi is printed only and only if both files aren't existing. > > If you didn't need to open them, but just to make sure they exist, you > > could use if os.exist(filename) much more easily. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlybrand at gmail.com Tue Nov 29 11:11:29 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Tue, 29 Nov 2011 02:11:29 -0800 Subject: [Tutor] Programming Collective Intelligence Study Group In-Reply-To: <4ED4AB97.9030300@pearwood.info> References: <4ED4AB97.9030300@pearwood.info> Message-ID: > > What are the Machine Learning Class and the Programming Collective > Intelligence book? Should I have heard of them before? > > Sorry for being unclear. Machine Learning Class is one of the free classes offered online by Stanford. http://www.ml-class.org This one started in October. Another round to start in January. I highly recommend it. Programming Collective Intelligence is a book by Toby Segaran from O'Reilly ISBN-13: 978-0596529321 It uses Python to apply machine learning techniques to real life problems and looks like loads of fun. The Natural Language Processing with Python book is freely available here: http://www.nltk.org/book > > If it's Google+ or Facebook, count me out. > > Well, that would only be one dimension of what I propose, so totally avoidable if you are that averse. You should be fine with the discussion forum and reference site I propose, which would be independent of any social networks. If I had any idea what you were talking about, other than "something to do with Python", then I might be. > Hopefully, I have done something to clarify what I was talking about. If not, don't hesitate to express your concerns via the list or to me personally, either by email or on Facebook (just kidding). Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy at enkelthed.dk Tue Nov 29 11:51:56 2011 From: tommy at enkelthed.dk (tommy at enkelthed.dk) Date: Tue, 29 Nov 2011 11:51:56 +0100 Subject: [Tutor] Programming Collective Intelligence Study Group (Mark Lybrand) In-Reply-To: References: <69e2ce06b4b1d51210fedda6bb319097@mail01> Message-ID: <63c29418c33b7ca1c7001f9710073c17@mail01> Excellent, Ill take a look at those. If you start up a G+ og Facebook group, Id like to participate, would give me a kick in the back with regards to actually starting on this, instead of just having it on my massive to-do list. I've dabble in programming for a while, done some java, c#, php, python, perl and some various unknown scripting languages developed by the companies i've worked with, but not enough to be fluent in any of the large established languages. On Tue, 29 Nov 2011 02:04:04 -0800, Mark Lybrand wrote: > Sorry about that. The book is called Programming Collective Intelligence. > It is from O'Reilly Press. It is written by Toby Segaran. ISBN-13: > 978-0596529321. > There is a PDF on the web, if you google around, but it doesn't seem that > kosher to me, so you are on your own if you decide to go that route. > > The other book that we are considering afterwards is Natural Language > Processing with Python. Also from O'Reilly. Written by Steven Bird, et al. > The book is legally freely available on the web. See here: > http://www.nltk.org/book > > I hope that helps. I will try to make my postings specific enough to be > able to participate without the book. And will try to point people to > information that might help. But I am also a noob (to all of it, Python, > NLP, ML). Man I miss my curly braces (although not as much as I thought I > would, since Python is making it real easy to love it) > > > On Tue, Nov 29, 2011 at 1:44 AM, wrote: > >> Hey Mark >> >> Id be very much interested in this. While I mostly lurk on the python >> mailing list and have only dabbled in a few quick scripts. Then I wouldnt >> mind getting deeper into via a collective group. >> >> This is the first I've heard of this, Im not sure if you've posted before >> but which book are you using? >> >> /Regards >> Tommy >> On Tue, 29 Nov 2011 10:18:25 +0100, tutor-request at python.org wrote: >> > 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: How to handle try and except in this case (Mic) >> > 2. Re: useful function or reinventing the wheel?? (Mark Lybrand) >> > 3. Programming Collective Intelligence Study Group (Mark Lybrand) >> > 4. Re: Do loop in Python (stm atoc) >> > 5. Re: How to handle try and except in this case (Dave Angel) >> > >> > >> > ---------------------------------------------------------------------- >> > >> > Message: 1 >> > Date: Tue, 29 Nov 2011 09:37:28 +0100 >> > From: "Mic" >> > To: >> > Subject: Re: [Tutor] How to handle try and except in this case >> > Message-ID: >> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; >> > reply-type=original >> > >> > >> > On 2011-11-27 17:58, Mic wrote: >> >>> Say that I want to try and open 10 files. If none of these exists, I >> >>> want >> >>> an >> >>> error >> >>> message to appear. But only if NONE of these files exists. >> > >> >>> I know how to handle this with one file. But I don't know how to do >> that >> >>> with more than one. >> >>> So the program should try and open all 10 files and if, and only if, >> >>> none >> >>> of the files exists I want en error message to appear. >> > >> > >> > [Andreas wrote]: >> >>Use a counter which increments with every existing file. After opening >> >>all files check if the counter is bigger than 0. >> > >> >>Or, if you need to know which files exist, use a list, append existing >> >>files to it and check at the end if it's not empty. >> > >> >>Do you need more help? >> > >> > Andreas, >> > >> > >> > Thanks for your answer. I am afraid I don't understand this: >> > "Use a counter which increments with every existing file. After opening >> > all files check if the counter is bigger than 0." >> > >> > >> > I thought I could co along those lines earlier >> > >> > try: >> > text_file=open("Hey","r") and text_file1=open("Hey","r") >> > except: >> > print("hi") >> > >> > >> > So that hi is printed only and only if both files aren't existing. >> > >> > >> > Thank you! >> > >> > >> > >> > >> > >> > >> > >> > ------------------------------ >> > >> > Message: 2 >> > Date: Tue, 29 Nov 2011 00:37:40 -0800 >> > From: Mark Lybrand >> > To: d at davea.name >> > Cc: tutor at python.org >> > Subject: Re: [Tutor] useful function or reinventing the wheel?? >> > Message-ID: >> > > BW5H3W3pcUr0DCtpRBg--2saA at mail.gmail.com> >> > Content-Type: text/plain; charset="utf-8" >> > >> >> >> >> >> >> You're welcome. I'd look forward to seeing your rewrite, and whether >> >> it's >> >> really shorter and more straightforward. >> >> >> >> Another advantage is doing less disk I/O if you start by trying the >> >> requested directory directly, and only recursing to parents if you >> can't >> >> make the requested directory. >> >> >> >> I took a quick stab at it (ask me later for mark.py) and it wasn't >> >> as >> >> straightforward as I expected. The main problem comes down to how to >> >> define the base case. I think you might have the same problem also. >> You >> >> assume that you can safely go back to the mount point. But if the >> >> path >> >> given is relative, you have to allow for that as well. Perhaps a call >> to >> >> os.path.abspath is in order. I also think that ismount() might not be >> >> legal on Windows, if you care about that. >> >> >> >> Also, we have to worry about what happens when one of the directories >> >> cannot be made for reasons unrelated to the syntax of the string. For >> >> example, the user might not have write permissions for one or more of >> the >> >> directories. In fact, the user might not have read permissions >> >> either. >> >> >> >> >> > I am actually passing in the path already os.path.abspath-ed. So, I >> should >> > probably move that into the function for better encapsulation. I am on >> > Windows, so ismount is behaving correctly (I tested it in Idle before >> going >> > with that as my base case). Since this will end up being a throw-away, >> I >> > will probably not worry too much about permissions and failures, but I >> can >> > appreciate the need for such checks, should I decide to keep this for >> more >> > widespread use. >> > >> > Thanks again. I will send my solution when I get a chance to get back >> to >> > it (gotta get myself ahead in machine learning before the weekend gets >> too >> > close :) >> > >> > Mark >> > -------------- next part -------------- >> > An HTML attachment was scrubbed... >> > URL: >> > >> < >> http://mail.python.org/pipermail/tutor/attachments/20111129/991cc3a9/attachment-0001.html >> > >> > >> > ------------------------------ >> > >> > Message: 3 >> > Date: Tue, 29 Nov 2011 00:42:01 -0800 >> > From: Mark Lybrand >> > To: tutor at python.org >> > Subject: [Tutor] Programming Collective Intelligence Study Group >> > Message-ID: >> > < >> CALsUBtzSqtJh4MX2ixuVO-J5zTn5xqLT+O4ZdyeVSe1VJknLzg at mail.gmail.com> >> > Content-Type: text/plain; charset="utf-8" >> > >> > Over on the Machine Learning Class, I mentioned the idea of setting up >> some >> > online resources to go through the Programming Collective Intelligence >> book >> > as a group. This would include a group or discussion board of some >> > type, >> > maybe a Google+ or Facebook page, and a wiki. Then we would set a pace >> and >> > work through the book. Since it is in Python, I thought this group >> would >> > be interested. Am I wrong? If it works out pretty good, we will >> probably >> > continue with Natural Language Processing (also Python) after we >> > finish. >> > >> > So, what is the interest like here? Let me know and I will give you >> guys a >> > heads up when I get everything all set up. >> > >> > -- >> > Mark :) >> > -------------- next part -------------- >> > An HTML attachment was scrubbed... >> > URL: >> > >> < >> http://mail.python.org/pipermail/tutor/attachments/20111129/82dcebaf/attachment-0001.html >> > >> > >> > ------------------------------ >> > >> > Message: 4 >> > Date: Tue, 29 Nov 2011 09:51:45 +0100 >> > From: stm atoc >> > To: Andreas Perstinger >> > Cc: tutor at python.org >> > Subject: Re: [Tutor] Do loop in Python >> > Message-ID: >> > < >> CAHNhTs68PqEQ5XVk4Tn3C6hQYMENRBY1O7xnqn-fxjmdki4ftg at mail.gmail.com> >> > Content-Type: text/plain; charset=ISO-8859-1 >> > >> > Thank you so much. This script and all information was totally helpful >> > and actually helped me for the next step of my work as well. >> > >> > Have a great time..... >> > Sue >> > >> > On Fri, Nov 25, 2011 at 10:44 PM, Andreas Perstinger >> > wrote: >> >> On 2011-11-25 14:46, stm atoc wrote: >> >>> >> >>> Here is the new version of the program: >> >>> >> >>> zvalues = [-200] ?# starting value >> >>> hvalues = [10] ?# starting value >> >>> increments = [1, 1, 1, 1, 1, 1, 1, 1] >> >>> for N in increments: >> >>> ? ? ? ?h = hvalues[-1] - N >> >>> ? ? ? ?hvalues.append(h) >> >>> ? ? ? ?z = zvalues[-1] + h >> >>> ? ? ? ?zvalues.append(z) >> >>> ? ? ? ?height = arange((z)*dz,0,dz) >> >> >> >> >> >> There is no "arange" in python. Could it be that you use numpy and >> >> import it >> >> with "from numpy import *"? >> >> >> >>> ? ? ? ?for z,when in enumerate(height): >> >> >> >> >> >> I'm pretty sure this line doesn't do what you expect it to do. You >> >> have >> a >> >> sequence (a numpy array) named "height" and after calling "enumerate" >> you >> >> get a list of tuples in the form of [(0, height[0]), (1, height[1]), >> >> ...]. >> >> Now the for-loop iterates over this list and assigns "z" to the first >> >> value >> >> of the tuple (the index-values) and "when" to the second (the values >> from >> >> "height"). You later never use "when" but just use "z". If you really >> >> want >> >> that, the "enumerate" is completly unnecessary and you could just use >> >> "for z >> >> in range(len(height))". But I'm not sure if numpy arrays work with >> >> "len()". >> >> >> >> >> >>> ? ? ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence >> >>> diffusivity m**2/s >> >>> ? ? ? ? ? ?nu.append(num + nuh[z]) >> >>> >> >>> The story is like this: >> >>> I should define layers and thickness and see how the diffusion >> >>> profile >> >>> changes over the z. >> >>> height (or depth) of the total thickness or 'z'. >> >>> I basically, define 'z' in 10 layers and each layer is called ?' N' . >> >>> Difference between each layer is 'h', which is equal 10 micrometer. >> >>> Now, what I like to do is the modification of nu based on each zvalue >> >>> In fact, for each 'zvalue' o'z' step, I need to calculate a different >> >>> value for 'nu' based on the available equation in the program. >> >>> >> >>> BUT, I am not sure, exactly, how to add the new do loop of z inside >> >>> another loop of nu. >> >> >> >> >> >> For me your explanations are still too confusing. Could it be that you >> >> are >> >> thinking way too complicated? >> >> >> >> My guess is you want to have a range of material thicknesses (from 1 >> >> to >> >> 200 >> >> micrometers in 10 micrometer-steps) and then you want from each >> >> thickness 10 >> >> different layers, right? >> >> >> >> import math # you should always tell us which modules you import >> >> num = 0.05 # some constant >> >> nu = [] # list of resulting values >> >> h = 10.0 # height of one layer >> >> thickness = range(0, 210, 10) # a list from 0 to 200 with step 10 (0, >> 10, >> >> 20, ..., 190, 200) >> >> layers = range(1,11) # a list from 1 to 10 >> >> for t in thickness: >> >> ?for l in layers: >> >> ? ?z = t + h * l # I'm not sure if you want to add or subtract the >> layer >> >> thickness >> >> ? ?nu = num + (0.01 * math.exp(-0.05 * (z + 200.0))) >> >> >> >> This will result in a big one-dimensional list where you calculate for >> >> each >> >> thickness the nu-value for 10 layers. Am I close? >> >> I'm still not sure about the steps and the height of the layers. I >> >> also >> >> wonder if it wouldn't be better to use a two-dimensional list. >> >> >> >> >> >>> I have done this way as well (the other way around): >> >>> >> >>> height = arange((z)*dz,0,dz) >> >>> for z,when in enumerate(height): >> >>> ? ? for N in increments: >> >>> ? ? ? ?h = hvalues[-1] - N >> >>> ? ? ? ?hvalues.append(h) >> >>> ? ? ? ?z = zvalues[-1] + h >> >>> ? ? ? ?zvalues.append(z) >> >>> ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence >> >>> diffusivity m**2/s >> >>> ? ? ? ?nu.append(num + nuh[z]) >> >>> >> >>> but still no sign of 'nu changes' over 'z'! >> >> >> >> >> >> As Charles has already mentioned, the values for "nu" are very similar >> >> (they >> >> start beginning to differ just at the seventh digit after the comma). >> >> How do >> >> you further process this values? If you plot them what's your scale? >> >> >> >> Bye, Andreas >> >> >> >> _______________________________________________ >> >> Tutor maillist ?- ?Tutor at python.org >> >> To unsubscribe or change subscription options: >> >> http://mail.python.org/mailman/listinfo/tutor >> > >> > >> > ------------------------------ >> > >> > Message: 5 >> > Date: Tue, 29 Nov 2011 04:17:55 -0500 >> > From: Dave Angel >> > To: Mic >> > Cc: tutor at python.org >> > Subject: Re: [Tutor] How to handle try and except in this case >> > Message-ID: <4ED4A343.1020406 at davea.name> >> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> > >> > On 11/29/2011 03:37 AM, Mic wrote: >> >> >> >> On 2011-11-27 17:58, Mic wrote: >> >>>> Say that I want to try and open 10 files. If none of these exists, I >> >>>> want an >> >>>> error >> >>>> message to appear. But only if NONE of these files exists. >> >> >> >>>> I know how to handle this with one file. But I don't know how to do >> >>>> that >> >>>> with more than one. >> >>>> So the program should try and open all 10 files and if, and only if, >> >>>> none >> >>>> of the files exists I want en error message to appear. >> >> >> >> >> >> [Andreas wrote]: >> >>> Use a counter which increments with every existing file. After >> >>> opening >> >>> all files check if the counter is bigger than 0. >> >> >> >>> Or, if you need to know which files exist, use a list, append >> >>> existing >> >>> files to it and check at the end if it's not empty. >> >> >> >>> Do you need more help? >> >> >> >> Andreas, >> >> >> >> >> >> Thanks for your answer. I am afraid I don't understand this: >> >> "Use a counter which increments with every existing file. After >> >> opening >> >> all files check if the counter is bigger than 0." >> >> >> > Could you explain what's unclear about it? Andreas couldn't get more >> > specific, since you didn't say how these 10 names are provided. If >> > they're in a list called filenames, you could do something like: >> > >> > fileobjects = [] >> > for fname in filenames: >> > try: >> > fileobj = open(fname, "r") >> > fileobjects.append(fileobj) >> > catch SomeExceptionType as e: >> > pass >> > >> > and when you're done, use something like: >> > >> > if len(fileobjects) == 0: >> > print "no files could be opened" >> > >> >> >> >> I thought I could co along those lines earlier >> >> >> >> try: >> >> text_file=open("Hey","r") and text_file1=open("Hey","r") >> > >> > Unfortunately this isn't valid Python syntax. The equal sign has a >> > specific statement syntax, and the only time you can have more than one >> > of them in one statement, is the chained assignments, where they all >> > get >> >> > bound to the same object. You wouldn't want to do this anyway, since >> > it >> >> > would leave all those open files in an unspecified state. >> > >> > To go one step further, if it could work, it would give an exception if >> > any ONE of the files couldn't be open, and you want the message to >> > appear if none of the files could be opened. >> > >> >> except: >> >> print("hi") >> >> >> >> >> >> So that hi is printed only and only if both files aren't existing. >> > If you didn't need to open them, but just to make sure they exist, you >> > could use if os.exist(filename) much more easily. >> _______________________________________________ >> 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 Nov 29 13:08:13 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Nov 2011 23:08:13 +1100 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: <4ED45EC6.3030101@gmail.com> References: <4ED45EC6.3030101@gmail.com> Message-ID: <4ED4CB2D.8060209@pearwood.info> bob gailer wrote: > On 11/28/2011 12:47 PM, James Reynolds wrote: >> >> >> On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams > > wrote: >> >> I am trying to pass a set of tuple strings from a file to a >> function I >> have defined. Each tuple is on a separate line, and looks something >> like this: >> ('note',2048) >> > > As already pointed out - this is a string (a representation of a tuple), > not a tuple. > > Your code must parse the string to extract the string representations of > the values, then convert as needed to the desired Python values. > > Tasks like this are not trivial. In general, parsing can be a hard problem. In this case though, it is easy to solve 95% of the problem with a hand-built converter, which may be good enough. def strto2tuple(s): """Convert a string like "('abc', 42)" to a tuple with two items.""" # Ignore leading and trailing whitespace. s = s.strip() # Check for round brackets (parentheses), and remove them. if s[0] != '(' or s[-1] != ')': raise ValueError('malformed string, missing ( or )') s = s[1:-1] # Split the string into exactly two pieces. # FIXME this assumes that the first item contains no commas. items = s.split(',') n = len(items) if n != 2: raise ValueError('expected exactly two items but found %d' % n) a, b = items # Ignore spaces around each item, e.g. ( 'abc' , 42 ) => ('abc', 42) a = a.strip() b = b.strip() # Make sure that the first item looks like a string. quotes = '"\'' # FIXME no support for triple quotes yet, or raw strings. assert len(quotes) == 2 for q in quotes: if a.startswith(q) and a.endswith(q): # Don't include the delimiter quotes in the string. a = a[1:-1] break else: # This executes if we don't hit a break in the for loop. raise ValueError('mismatched or missing quotes') assert isinstance(a, str) # Make sure the second item is an integer. b = int(b, 0) # Support hex and octal formats too. return (a, b) # And return a real tuple. This untested function will convert strings in a file like these: ( 'fe', 1) ( 'fi' ,2 ) ("fo",0x03) ( "fum" , 4 ) into proper tuples with a string and a number. Notice that we allow the user to be sloppy with spaces, but we are strict about quotation marks and brackets. Our converter function is both a little too strict (e.g. it forbids the user from including triple-quoted strings) and a little too lax (e.g. it allows malformed strings like ''abc'). You might not care about these weaknesses. If you do, you need to move up to a real parser, which is significantly more complex. -- Steven From steve at pearwood.info Tue Nov 29 13:26:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Nov 2011 23:26:01 +1100 Subject: [Tutor] How to use try and except in this case? In-Reply-To: References: Message-ID: <4ED4CF59.9070902@pearwood.info> Mic wrote: > Say that I want to try and open 10 files. If none of these exists, I > want an error > message to appear. But only if NONE of these files exists. > > I know how to handle this with one file. But I don't know how to do that > with more than one. > So the program should try and open all 10 files and if, and only if, > none of the files exists I want en error message to appear. Your description isn't quite clear enough. What happens if, say, only 3 of the files exist? Is the intention to open the first file that you can find? # Ten file names to try: names = ['file 1', 'file 2', 'a', 'b', 'c', 'backup file', 'backup file 2', 'spam', 'ham', 'eggs' ] # Find the first one that exists and is readable. for name in names: try: f = open(name, 'r') except (OSError, IOError): continue # try the next one break # this only runs when a file opens successfully else: # we didn't break raise ValueError('no file could be opened') Or is it your intention to open as many of the files as possible? # Ten file names to try: names = ['file 1', 'file 2', 'a', 'b', 'c', 'backup file', 'backup file 2', 'spam', 'ham', 'eggs' ] files = [] # list of opened file objects for name in names: try: f = open(name, 'r') files.append(f) except (OSError, IOError): continue # missing, go on to the next one if files == []: raise ValueError('no file could be opened') else: # do stuff with the files... # ... # ... # don't forget to close them when done (optional but recommended) for f in files: f.close() -- Steven From steve at pearwood.info Tue Nov 29 13:38:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 29 Nov 2011 23:38:04 +1100 Subject: [Tutor] How to raise error without the stack trace In-Reply-To: <4ED2290E.2020104@gmail.com> References: <4ED0BC94.1060401@gmail.com> <4ED0D07F.3020607@pearwood.info> <4ED2290E.2020104@gmail.com> Message-ID: <4ED4D22C.1020905@pearwood.info> Karim wrote: > I did not explain myself clearly. I Kow when I fired it because it is in > code like: > > If not value: > raise MyError('You did wrong here!') > > And in that case I did not want the stack trace because I know perfectly > where the message is triggered. Really? You must have amazingly tiny programs that are incredibly bug free then. I'm jealous :-) In my programs, if I get MyError('You did wrong here!'), I need all the help I can get to find out what sort of wrong it was, why value is incorrect, what function called it, and where the value came from originally. The stack trace is often very helpful for that: the variable might get the wrong value half a dozen function calls away from where the exception happens. Sometimes the error is obvious, and the stack trace is easy to ignore. It's the cases that aren't obvious that you should care about. If you think Python stack traces are annoying, you haven't seen anything. Once, I saw a SAP application unexpected crash, and it printed (I am not exaggerating, or joking) half a ream of printouts. Seriously. The stack of printouts was two centimetres thick. We called the supplier and asked if they wanted the printouts for debugging, and they said no. -- Steven From __peter__ at web.de Tue Nov 29 13:38:32 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Nov 2011 13:38:32 +0100 Subject: [Tutor] pass tuples to user defined function(beginner) References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> Message-ID: Steven D'Aprano wrote: > bob gailer wrote: >> On 11/28/2011 12:47 PM, James Reynolds wrote: >>> >>> >>> On Mon, Nov 28, 2011 at 12:32 PM, Mayo Adams >> > wrote: >>> >>> I am trying to pass a set of tuple strings from a file to a >>> function I >>> have defined. Each tuple is on a separate line, and looks something >>> like this: >>> ('note',2048) >>> >> >> As already pointed out - this is a string (a representation of a tuple), >> not a tuple. >> >> Your code must parse the string to extract the string representations of >> the values, then convert as needed to the desired Python values. >> >> Tasks like this are not trivial. > > > In general, parsing can be a hard problem. In this case though, it is easy > to solve 95% of the problem with a hand-built converter, which may be good > enough. > > def strto2tuple(s): > """Convert a string like "('abc', 42)" to a tuple with two items.""" > # Ignore leading and trailing whitespace. > s = s.strip() > # Check for round brackets (parentheses), and remove them. > if s[0] != '(' or s[-1] != ')': > raise ValueError('malformed string, missing ( or )') > s = s[1:-1] > # Split the string into exactly two pieces. > # FIXME this assumes that the first item contains no commas. > items = s.split(',') > n = len(items) > if n != 2: > raise ValueError('expected exactly two items but found %d' % n) > a, b = items > # Ignore spaces around each item, e.g. ( 'abc' , 42 ) => ('abc', 42) > a = a.strip() > b = b.strip() > # Make sure that the first item looks like a string. > quotes = '"\'' # FIXME no support for triple quotes yet, or raw > strings. assert len(quotes) == 2 > for q in quotes: > if a.startswith(q) and a.endswith(q): > # Don't include the delimiter quotes in the string. > a = a[1:-1] > break > else: > # This executes if we don't hit a break in the for loop. > raise ValueError('mismatched or missing quotes') > assert isinstance(a, str) > # Make sure the second item is an integer. > b = int(b, 0) # Support hex and octal formats too. > return (a, b) # And return a real tuple. > > > This untested function will convert strings in a file like these: > > ( 'fe', 1) > ( 'fi' ,2 ) > ("fo",0x03) > ( "fum" , 4 ) > > into proper tuples with a string and a number. Notice that we allow the > user to be sloppy with spaces, but we are strict about quotation marks and > brackets. > > > Our converter function is both a little too strict (e.g. it forbids the > user from including triple-quoted strings) and a little too lax (e.g. it > allows malformed strings like ''abc'). You might not care about these > weaknesses. If you do, you need to move up to a real parser, which is > significantly more complex. And here's the lazy-bastard version: >>> lines = """( 'fe', 1) ... ( 'fi' ,2 ) ... ("fo",0x03) ... ( "fum" , 4 ) ... ("gvn", __import__("os").remove("that could be your valuable data.txt")) ... """.splitlines() >>> import ast >>> for line in lines: ... print ast.literal_eval(line.strip()) ... ('fe', 1) ('fi', 2) ('fo', 3) ('fum', 4) Traceback (most recent call last): File "", line 2, in File "/usr/lib/python2.6/ast.py", line 68, in literal_eval return _convert(node_or_string) File "/usr/lib/python2.6/ast.py", line 58, in _convert return tuple(map(_convert, node.elts)) File "/usr/lib/python2.6/ast.py", line 67, in _convert raise ValueError('malformed string') ValueError: malformed string From steve at pearwood.info Tue Nov 29 14:00:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Nov 2011 00:00:45 +1100 Subject: [Tutor] Do loop in Python In-Reply-To: References: <4ECF7DB5.60305@pearwood.info> Message-ID: <4ED4D77D.4040500@pearwood.info> stm atoc wrote: > Thank you so much for your reply. It was very helpful information and > I used it in order to improve the program.... > > Here is the new version of the program: > > zvalues = [-200] # starting value > hvalues = [10] # starting value > increments = [1, 1, 1, 1, 1, 1, 1, 1] > for N in increments: > h = hvalues[-1] - N > hvalues.append(h) > z = zvalues[-1] + h > zvalues.append(z) > height = arange((z)*dz,0,dz) > for z,when in enumerate(height): > nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence > diffusivity m**2/s > nu.append(num + nuh[z]) I'm afraid I still don't know what the arange function is. Is that a function you have written yourself? However, I can see that it doesn't actually get used! You create an arange object, and call it "height". height = arange((z)*dz,0,dz) You should insert a print statement after this line to see what value height is given, and check that it is what you expect it to be. Presumably height is some sort of list or sequence of values, because you next use it in a for-loop: for z,when in enumerate(height): ... So now we know that z takes on the values 0, 1, 2, 3, ... and when takes on the values from height, whatever they are. But in the rest of your code, you don't use when at all: nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) nu.append(num + nuh[z]) No when, hence the values from height aren't actually used. Strange. Also, what are dz and num? You use them both, but I can't see where they are defined or what value they have. Likewise nuh and nu, although I can guess they are probably lists because you append to them. Because I don't know what values to use, and I don't know what arange is, I can't run your code to see what it does. So I'm reduced to guessing. If I take a wild stab in the dark that dz is a small number, say, 0.01, I can see what values nuh gets: py> from math import exp py> dz = 0.01 py> nuh = [] py> for z in range(10): ... nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) ... py> from pprint import pprint py> pprint(nuh) [3.6787944117144236e-06, 3.6604463480401533e-06, 3.6421897957152333e-06, 3.624024298324903e-06, 3.6059494017307832e-06, 3.587964654059516e-06, 3.5700696056914737e-06, 3.5522638092495153e-06, 3.5345468195878014e-06, 3.5169181937806692e-06] Is that the sort of behaviour you expect for nuh? Since the nuh values are changing, num+nuh[z] should also be changing, which implies nu should be changing. Unless num is so large that rounding error wipes out the nuh values. -- Steven From steve at pearwood.info Tue Nov 29 14:02:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Nov 2011 00:02:48 +1100 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> Message-ID: <4ED4D7F8.5000507@pearwood.info> Peter Otten wrote: > And here's the lazy-bastard version: [...] > ... print ast.literal_eval(line.strip()) Nice! -- Steven From cranky.frankie at gmail.com Tue Nov 29 15:14:21 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 29 Nov 2011 09:14:21 -0500 Subject: [Tutor] problem with msg widget & button Message-ID: OK, I've stripped out all the comments and put it here: http://www.pastie.org/2938751 This works but the button doesn't put the next comment in the window. The only way I could figure to get the next comment in the window is to add the msg_widget line to the disp_quote function, but when I do that, it puts out *another* msg-widget! That is not what I want at all. I just want the next quote button to put the next quote in the box. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From jiaxiaolei19871112 at gmail.com Tue Nov 29 15:28:42 2011 From: jiaxiaolei19871112 at gmail.com (=?GB2312?B?vNbP/sDa?=) Date: Tue, 29 Nov 2011 22:28:42 +0800 Subject: [Tutor] python webservice suds In-Reply-To: References: Message-ID: hi, all: is someone familiar to suds. I'm making a webservice client, and meet some problems. I try to ask helps from soap at python.org, lists at libertylost.org, python-tornado at googlegroups.com, while, the problem still exist. part 1: how do you think the xml in the url: "http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl" part 2: in fact, the server is made by Axis, which is a web service framework in Java. Before i develop the client, there already have a java client for the server. the code are below: if (temp.length % MTINFO_LENGTH != 0) { String[] remainBlock = new String[temp.length - jMark]; for (int i = 0; i < remainBlock.length; i++) { remainBlock[i] = temp[jMark]; jMark++; } mark = lnxss.sendMt(remainBlock); After read the code, we know that the the inparams of sendMt is String[]. In fact, the purpose of senMt() is to send some shotmessage to a mobile phone. you can find remobile in the parameters. part 3: Besides, the server has some check, which i have add it in the newest code. servicecode: PABB4BEIJING passwd: QWERTPABB namespace: service.global.v1_0.wsdl.protocol.xxt (you can see it in the url) I have tried to add the service code and passwd in the code. while, what still puzzled me is that in suds, how to add the namespace to the client. how to use the ArrayOf_soapen_string is a problem. in my code, i provide a list which contains some string. in my view, i should provide a object like your code, aoss = client.factory.create('ArrayOf_soapen_string') then, what should i do next? how to assign a value for the parameter of aoss? part 4: # the newest code : import suds def test_sms4(): import logging logging.basicConfig(level=logging.ERROR) url = " http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl" from suds.transport.https import HttpAuthenticated credentials = dict(username='PABB4BEIJING', password='QWERTPABB') t = HttpAuthenticated(**credentials) client = suds.client.Client(url,transport=t,cache=None,xstq=False,faults=False) #client = suds.client.Client(url,cache=None,xstq=False) aoss = client.factory.create('ArrayOf_soapenc_string') #client.set_options(namespace='service.global.v1_0.wsdl.protocol.xxt') print 'client', client item1 = "{'msgid':'1234567890','bizcode':'15140237310','serviceId':'1234567','recomobile':'15110791945','sendtime':'1322573860','content':'hi, this is just a test. you can ignore it. --jiaxiaolei'}" item2 = "{'msgid':'1234567891','bizcode':'15140237310','serviceId':'1234567','recomobile':'15110791946','sendtime':'1322573870','content':'hi, this is just a test. you can ignore it. --jiaxiaolei'}" req = [item1, item2] #client.service.sendMt(aoss) output = client.service.sendMt(mtinfo=req) print 'output', output # output: w_jiaxiaolei at drone-009:~/tornadows-0.9.1/demos$ python suds_client.py client Suds ( https://fedorahosted.org/suds/ ) version: 0.3.7 GA build: R580-20091016 Service ( LNXxtSyncServiceService ) tns="service.global.v1_0.wsdl.protocol.xxt" Prefixes (3) ns0 = "http://common.v1_0.obj.protocol.xxt" ns1 = "http://schemas.xmlsoap.org/soap/encoding/" ns2 = "service.global.v1_0.wsdl.protocol.xxt" Ports (1): (LNXxtSyncService) Methods (5): sendMo(ArrayOf_soapenc_string moInfo, ) sendMt(ArrayOf_soapenc_string mtInfo, ) syncCorp(ArrayOf_tns2_GroupOrderInfo orderInfo, ) syncResponseRpt(ArrayOf_soapenc_string rpt, ) syncStaff(ArrayOf_tns2_UserOrderInfo orderInfo, ) Types (54): ns1:Array ArrayOf_soapenc_string ArrayOf_tns2_GroupOrderInfo ArrayOf_tns2_UserOrderInfo ... ERROR:suds.client: output (500, (detail){ fault = (fault){ _href = "#id0" } exceptionName = "xxt.protocol.obj.v1_0.common.ServiceException" hostname = "ln_xxt_mh01" }) -- jiaxiaolei 2011/11/29 xin zou > Sorry that I used many "should" as my subjective judgment, you can try to > test with the closed correct args of "*array_soapenc_str*" refer the > related document. > > Thanks, > Xin > > ? 2011?11?29? ??8:20?xin zou ??? > > Hi, >> >> Here are my testing code with your supplied service: >> >> =============================================================== >> from suds.client import Client >> import logging >> >> #logging.basicConfig(level=logging.DEBUG) >> >> url = ' >> http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl >> ' >> client = Client(url) >> >> array_soapenc_str = client.factory.create('ArrayOf_soapenc_string') >> array_soapenc_str._arrayType = 'test' >> array_soapenc_str._offset = '1' >> array_soapenc_str._id = '1' >> array_soapenc_str._href = "http://www.test.com" >> array_soapenc_str._arrayType = 'test2' >> >> print client.service.sendMt(array_soapenc_str) >> >> =============================================================== >> >> My occurred error was " WebFault: Server raised fault: '' "(you can >> remove the DEBUG comment for more information), I think it should be my >> testing args were incorrect. You should be familiar with these request >> args, as well as you should have the corresponding document of this web >> service (e.g. what is the purpose of the "sendMt" operation), right? Hope >> these are helpful for you. Good luck! >> >> BTW, the more detailed document of the released web service, the better >> for the client :) >> >> Thanks, >> Xin >> >> >> >> >> 2011/11/29 ??? >> >>> Hi, all: >>> >>> First of all, I will admire I am a novice to web service. I read >>> someting about webservie about tornado webservice and find thant nearly all >>> the client is developed by suds. >>> >>> What I need now is to invoke a method sendMt provided by the web >>> service server(prehaps the server is made by java language using a framwork >>> named Axis). >>> >>> I try to invoke the sendMt method provided by the server, then failded. >>> There are the tests as follows: >>> >>> you can see the whole wsdl file in " >>> http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl", >>> or read in the attachment(when i use suds, in /tmp/suds/* i find them) . >>> >>> method 1: >>> >>> import suds >>> >>> def test_sms(): >>> #TODO: it's failed >>> url = " >>> http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl >>> " >>> #client = suds.client.Client(url,faults=False) >>> client = suds.client.Client(url) >>> print 'client', client >>> a = ['jia','xiao'] >>> output = client.service.sendMt(a) >>> print 'output', output >>> >>> >>> # the output: >>> >>> client >>> Suds ( https://fedorahosted.org/suds/ ) version: 0.3.7 GA build: >>> R580-20091016 >>> >>> Service ( LNXxtSyncServiceService ) >>> tns="service.global.v1_0.wsdl.protocol.xxt" >>> Prefixes (3) >>> ns0 = "http://common.v1_0.obj.protocol.xxt" >>> ns1 = "http://schemas.xmlsoap.org/soap/encoding/" >>> ns2 = "service.global.v1_0.wsdl.protocol.xxt" >>> Ports (1): >>> (LNXxtSyncService) >>> Methods (5): >>> sendMo(ArrayOf_soapenc_string moInfo, ) >>> sendMt(ArrayOf_soapenc_string mtInfo, ) >>> syncCorp(ArrayOf_tns2_GroupOrderInfo orderInfo, ) >>> syncResponseRpt(ArrayOf_soapenc_string rpt, ) >>> syncStaff(ArrayOf_tns2_UserOrderInfo orderInfo, ) >>> Types (54): >>> ns1:Array >>> ArrayOf_soapenc_string >>> ArrayOf_tns2_GroupOrderInfo >>> ArrayOf_tns2_UserOrderInfo >>> ns1:ENTITIES >>> ns1:ENTITY >>> ... >>> No handlers could be found for logger "suds.client" >>> Traceback (most recent call last): >>> File "suds_client.py", line 124, in >>> test_sms2() >>> File "suds_client.py", line 99, in test_sms2 >>> output = client.service.sendMt(a) >>> File >>> "/usr/local/lib/python2.6/dist-packages/suds-0.3.7-py2.6.egg/suds/client.py", >>> line 535, >>> >>> in __call__ >>> return client.invoke(args, kwargs) >>> File >>> "/usr/local/lib/python2.6/dist-packages/suds-0.3.7-py2.6.egg/suds/client.py", >>> line 595, >>> >>> in invoke >>> result = self.send(msg) >>> File >>> "/usr/local/lib/python2.6/dist-packages/suds-0.3.7-py2.6.egg/suds/client.py", >>> line 630, >>> >>> in send >>> result = self.failed(binding, e) >>> File >>> "/usr/local/lib/python2.6/dist-packages/suds-0.3.7-py2.6.egg/suds/client.py", >>> line 681, >>> >>> in failed >>> r, p = binding.get_fault(reply) >>> File >>> "/usr/local/lib/python2.6/dist-packages/suds-0.3.7-py2.6.egg/suds/bindings/binding.py", >>> >>> line 235, in get_fault >>> raise WebFault(p, faultroot) >>> suds.WebFault: Server raised fault: 'No such operation 'sendMt'' >>> >>> >>> #Note: >>> 1: the url " >>> http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl" >>> is >>> >>> develped in Internet, anyone can use it. >>> 2: in my view, the server is made by java Axis, and the inparams of >>> sendmt is >>> >>> ArrayOf_soapenc_string(In java, it means a array of String, in python, >>> it means a list whose >>> >>> items are string). >>> 3: the problem has puzzled me for nearly a week, please someone can give >>> me some points. >>> >>> >>> # besides the suds, i try other methods as follows, whlie, still failed. >>> >>> method 2: >>> >>> from SOAPpy import SOAPProxy >>> def test_sms(): >>> """test for ln sms java webservice >>> """ >>> #TODO:invoke sms is stil failed >>> url = " >>> http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService" >>> server = SOAPProxy(url) >>> args = ['jia','xiao'] >>> print server.sendMt(args) >>> >>> >>> # output: >>> w_jiaxiaolei at drone-009:~/tornadows-0.9.1/demos$ python soappy_client.py >>> Traceback (most recent call last): >>> File "soappy_client.py", line 59, in >>> test_sms() >>> File "soappy_client.py", line 31, in test_sms >>> print server.sendMt(args) >>> File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 470, in >>> __call__ >>> return self.__r_call(*args, **kw) >>> File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 492, in >>> __r_call >>> self.__hd, self.__ma) >>> File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 406, in >>> __call >>> raise p >>> SOAPpy.Types.faultType: >> >> >>> detail at 26709888>: {'fault': >> 26707800>: {'text': >>> >>> 'SoapHeader is null', 'messageId': 'SEV_0003'}, 'exceptionName': >>> >>> 'xxt.protocol.obj.v1_0.common.ServiceException', 'hostname': >>> 'ln_xxt_mh01'}> >>> >>> >>> method 3: >>> >>> from SOAPpy import WSDL >>> >>> def test_sms(): >>> """for sms >>> """ >>> url = " >>> http://211.137.45.104:9006/LnXxtCpInterface/services/LNXxtSyncService?wsdl >>> " >>> server = WSDL.Proxy(url) >>> #print 'methods:',server.methods.keys() >>> #print 'input type:',server.methods['sendMt'].inparams[0].type >>> #print 'input name:',server.methods['sendMt'].inparams[0].name >>> #print 'output type:',server.methods['sendMt'].outparams[0].type >>> #print 'output name:',server.methods['sendMt'].outparams[0].name >>> a = ['jia','xiao'] >>> results=server.sendMt(a) >>> print results >>> >>> # output: >>> w_jiaxiaolei at drone-009:~/tornadows-0.9.1/demos$ python wsdl_client.py >>> /usr/lib/pymodules/python2.6/SOAPpy/wstools/XMLSchema.py:2871: >>> DeprecationWarning: >>> >>> object.__init__() takes no parameters >>> tuple.__init__(self, args) >>> Traceback (most recent call last): >>> File "wsdl_client.py", line 48, in >>> test_sms() >>> File "wsdl_client.py", line 41, in test_sms >>> results=server.sendMt(a) >>> File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 470, in >>> __call__ >>> return self.__r_call(*args, **kw) >>> File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 492, in >>> __r_call >>> self.__hd, self.__ma) >>> File "/usr/lib/pymodules/python2.6/SOAPpy/Client.py", line 406, in >>> __call >>> raise p >>> SOAPpy.Types.faultType: >> >> >>> detail at 31753352>: {'fault': >> 31753280>: {'text': >>> >>> 'SoapHeader is null', 'messageId': 'SEV_0003'}, 'exceptionName': >>> >>> 'xxt.protocol.obj.v1_0.common.ServiceException', 'hostname': >>> 'ln_xxt_mh01'}> >>> >> >> > -- NAME: ???/Jia Xiaolei MOBILE: 13011292217 QQ: 281304051 MICRO-BLOG: http://weibo.com/2183890715 GMAIL: jiaxiaolei19871112 at gmail.com -- NAME: ???/Jia Xiaolei MOBILE: 13011292217 QQ: 281304051 MICRO-BLOG: http://weibo.com/2183890715 GMAIL: jiaxiaolei19871112 at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From o0MB0o at hotmail.se Tue Nov 29 15:54:59 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 15:54:59 +0100 Subject: [Tutor] Making a function run every second. In-Reply-To: References: Message-ID: Hi I want a function to run every second , how do I do that? Say that the function look like this: def hi(): print("hi") Thanks! Mic From o0MB0o at hotmail.se Tue Nov 29 16:09:02 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 16:09:02 +0100 Subject: [Tutor] Creating a line in a text file every time a button is pressed. In-Reply-To: References: Message-ID: Hey again. I figured I would first post this piece of code and then ask my questions. FREE = "green" OCCUPIED = "red" class Mainwindow(Frame): def __init__(self,master): super(Mainwindow,self).__init__(master) self.grid() self.create_mainwidgets() def create_mainwidgets(self): self.klicka=Button(self, text="Press the button", command=self.uppdatera) self.klicka.grid() def uppdatera(self): SeatWindow(root) class SeatButton(tk.Button): def __init__(self, master, index): text = str(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "Germany_France{}.txt".format(index+1) self.occupied = False if os.path.exists(self.filename): self["bg"]=OCCUPIED def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close() else: self["bg"] = FREE os.remove(self.filename) class SeatWindow(tk.Toplevel): def __init__(self, master): super (SeatWindow, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root=Tk() root.title("testV2") app=Mainwindow(root) root.mainloop() I am now writing another program. It turned out just fine, but I have one question. If button one is pressed I want the program to write, say hi_1, on the first line in a text file. If button one is pressed again, the first line should be empty. If button two is pressed I want the program to write hi_2 in the second line in the text file. If button two is pressed again, the second line in the text file should be empty. If button three is pressed I want the program to write hi_3 in the third line in the text file. if button three is pressed again, the third line in the text file should be empty. There shouldn't be any other changes to the program other than this above. There is already a text file created, the program doesn't need to create one. We can call that file "Hi". I hope you understand what I want to do here. I have tried the entire evening yesterday to get this to work, I tried using writeline() but I can't get it to work. What are your suggestions to this? Thank you for your help and time! From o0MB0o at hotmail.se Tue Nov 29 16:16:26 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 16:16:26 +0100 Subject: [Tutor] How to handle try and except in this case In-Reply-To: <4ED4A343.1020406@davea.name> References: <4ED4A343.1020406@davea.name> Message-ID: >Could you explain what's unclear about it? Andreas couldn't get more >specific, since you didn't say how these 10 names are provided. Yes, it was probably my fault. Sorry about that. I have come up with a new way of working around a problem in my main program so I only need two files to be tested if they exist instead of say 10 files. So, the program should check if two text files exist. If neither of them exist, and only if neither of them, then the program should print say "hi". If only one of them exist, the program should continue to run without crashing. I hope this was more easy to understand! >> I thought I could co along those lines earlier >> >> try: >> text_file=open("Hey","r") and text_file1=open("Hey","r") >Unfortunately this isn't valid Python syntax. The equal sign has a >specific statement syntax, and the only time you can have more than one of >them in one statement, is the chained assignments, where they all get bound >to the same object. You wouldn't want to do this anyway, since it would >leave all those open files in an unspecified state. Thanks for the information. I figured that it was a little strange what I wrote. Mic From bodsda at googlemail.com Tue Nov 29 16:19:11 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 29 Nov 2011 15:19:11 +0000 Subject: [Tutor] Making a function run every second. In-Reply-To: References: Message-ID: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> You won't get it exactly on because the time it takes to call the function will affect your trigger time. I would use something like an infinite loop with a 1 second sleep after the function call Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: "Mic" Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Tue, 29 Nov 2011 15:54:59 To: Subject: [Tutor] Making a function run every second. Hi I want a function to run every second , how do I do that? Say that the function look like this: def hi(): print("hi") Thanks! Mic _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Tue Nov 29 16:19:55 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Nov 2011 16:19:55 +0100 Subject: [Tutor] problem with msg widget & button References: Message-ID: Cranky Frankie wrote: > OK, I've stripped out all the comments and put it here: > > http://www.pastie.org/2938751 > > > This works but the button doesn't put the next comment in the window. > The only way I could figure to get the next comment in the window is > to add the msg_widget line to the disp_quote function, but when I do > that, it puts out *another* msg-widget! That is not what I want at > all. I just want the next quote button to put the next quote in the > box. Hm, your description doesn't match with the code you posted which only creates one Message. Also you still initialize the command parameter with the function result Button(..., command=f()) # wrong instead of the function itself Button(..., command=f) # correct. Here's a fixed version: #!/usr/bin/python3 import random from tkinter import * quote_dict = { 1:["Kahlil Gibran", "A candle loses nothing of its light when lighting another."], # ... } def choose_quote(): rand_quote = (random.randrange(len(quote_dict))+1) quote = quote_dict[rand_quote][1] author = quote_dict[rand_quote][0] return (quote+"\n\n"+author) def display_quote(): msg_widget["text"] = choose_quote() root = Tk() win = Frame() win.pack() label_widget = Label(win, text="Welcome to Quote of the Day") label_widget.pack(side = TOP, expand=YES, fill=BOTH) msg_widget = Message( win, anchor=NW, justify=LEFT, width=1000, bd=2, bg="white", relief=SOLID, text=choose_quote()) msg_widget.pack() next_button = Button(win, text="Next Quote", command=display_quote) next_button.pack(side=LEFT) quit_button = Button(win, text="QUIT", fg="red", command=quit) quit_button.pack(side=RIGHT) root.mainloop() From delegbede at dudupay.com Tue Nov 29 16:22:42 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Tue, 29 Nov 2011 15:22:42 +0000 Subject: [Tutor] Making a function run every second. In-Reply-To: References: Message-ID: <1749007006-1322580163-cardhu_decombobulator_blackberry.rim.net-1947379784-@b18.c12.bise7.blackberry> In my opinion, you probably have to think of how many times it has to run. If you want to run forever, you can just make an infinite loop. Here's my try. import time def myloop(): while True: print 'Hi' time.sleep(1) This would run forever and print Hi after every 1 second when you run the program. What exactly are you trying to achieve. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: "Mic" Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Tue, 29 Nov 2011 15:54:59 To: Subject: [Tutor] Making a function run every second. Hi I want a function to run every second , how do I do that? Say that the function look like this: def hi(): print("hi") Thanks! Mic _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From d at davea.name Tue Nov 29 16:25:09 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 10:25:09 -0500 Subject: [Tutor] How to handle try and except in this case In-Reply-To: References: <4ED4A343.1020406@davea.name> Message-ID: <4ED4F955.5000304@davea.name> (You top-posted again. Try to put your remarks AFTER the part you're quoting, so that the message is self-descriptive) On 11/29/2011 10:16 AM, Mic wrote: >> Could you explain what's unclear about it? Andreas couldn't get more >> specific, since you didn't say how these 10 names are provided. > > > Yes, it was probably my fault. Sorry about that. I have come up with a > new way of working around > a problem in my main program so I only need two files to be tested if > they exist instead of say 10 files. > > So, the program should check if two text files exist. If neither of them > exist, and only if neither of them, > then the program should print say "hi". > > If only one of them exist, the program should continue to run without > crashing. > > > I hope this was more easy to understand! > The os.path.exists(filename) returns a boolean, and doesn't tie up resources, so you are welcome to use it in an if expression. if not (os.path.exists(file1) and os.path.exists(file2)): print "hi" -- DaveA From o0MB0o at hotmail.se Tue Nov 29 16:31:35 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 16:31:35 +0100 Subject: [Tutor] Making a function run every second. In-Reply-To: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> References: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> Message-ID: -----Ursprungligt meddelande----- From: bodsda at googlemail.com Sent: Tuesday, November 29, 2011 4:19 PM To: Mic ; tutor-bounces+bodsda=googlemail.com at python.org ; Tutor - python List Subject: Re: [Tutor] Making a function run every second. >You won't get it exactly on because the time it takes to call the function >will affect your trigger time. Alright, but that doesn't matter. About every second would be good. >I would use something like an infinite loop with a 1 second sleep after the >function call I see, could you explain a little more detailed? Thanks you for your reply! From __peter__ at web.de Tue Nov 29 16:31:36 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Nov 2011 16:31:36 +0100 Subject: [Tutor] Making a function run every second. References: Message-ID: Mic wrote: > I want a function to run every second , how do I do that? > > Say that the function look like this: > > def hi(): > print("hi") For a console app you could use a for-loop with time.sleep() or http://docs.python.org/dev/py3k/library/sched.html For a script that uses tkinter there's the after() method. Example: root = Tk() def hi(): print("ho") def hi_reschedule(): hi() # make tkinter call it again after 1000 milliseconds root.after(1000, hi_reschedule) hi_reschedule() # call it manually the first time http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html From d at davea.name Tue Nov 29 16:33:41 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 10:33:41 -0500 Subject: [Tutor] Making a function run every second. In-Reply-To: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> References: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> Message-ID: <4ED4FB55.1000201@davea.name> (You put your response in the wrong place; it belongs after the part you're quoting.) he On 11/29/2011 10:19 AM, bodsda at googlemail.com wrote: > You won't get it exactly on because the time it takes to call the function will affect your trigger time. > > I would use something like an infinite loop with a 1 second sleep after the function call > > Bodsda > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: "Mic" > Sender: tutor-bounces+bodsda=googlemail.com at python.org > Date: Tue, 29 Nov 2011 15:54:59 > To: > Subject: [Tutor] Making a function run every second. > > Hi > > I want a function to run every second , how do I do that? > > Say that the function look like this: > > def hi(): > print("hi") > > > Thanks! > > > Mic Without a clearer spec, there are too many possible answers. As Bobsda says, you can't get it exactly one second apart. But you also have the problem of whether a drift is okay. For example, if you have a global you're incrementing each time that function runs, and you want it to represent the total time the program has been running, then a simple sleep() is totally wrong. What I was concerned about is that perhaps this is for one of the tkinter programs Mic is writing. For an event-driven program, sleep() calls of even a second are unaccepable. And if you literally write a while loop like that, your whole program would stop responding. So Mik: Tell us more about the real requirements. Is drift acceptable, is this a console program or some gui environment, are there any other hidden assumptions? -- DaveA From o0MB0o at hotmail.se Tue Nov 29 16:35:22 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 16:35:22 +0100 Subject: [Tutor] How to handle try and except in this case In-Reply-To: <4ED4F955.5000304@davea.name> References: <4ED4A343.1020406@davea.name> <4ED4F955.5000304@davea.name> Message-ID: -----Ursprungligt meddelande----- From: Dave Angel Sent: Tuesday, November 29, 2011 4:25 PM To: Mic Cc: tutor at python.org Subject: Re: [Tutor] How to handle try and except in this case >(You top-posted again. Try to put your remarks AFTER the part you're >quoting, so that the message is self-descriptive) I did? I thought I posted this: """ >Could you explain what's unclear about it? Andreas couldn't get more >specific, since you didn't say how these 10 names are provided. Yes, it was probably my fault. Sorry about that. I have come up with a new way of working around a problem in my main program so I only need two files to be tested if they exist instead of say 10 files. """ Is that top posting? >The os.path.exists(filename) returns a boolean, and doesn't tie up >resources, so you are welcome to use it in an if expression. >if not (os.path.exists(file1) and os.path.exists(file2)): >print "hi" Thank you! What do you mean with that it "doesn't tie up resources"? Mic From maxskywalker1 at gmail.com Mon Nov 28 15:47:06 2011 From: maxskywalker1 at gmail.com (Max gmail) Date: Mon, 28 Nov 2011 09:47:06 -0500 Subject: [Tutor] why doesn't python show error In-Reply-To: References: Message-ID: In some cases, it is a useful fact that Python only shows error messages when they are encountered. For example, I can test a program while keeping away from an area that still doesn't work, rather than having to make it work flawlessly before my first test. Python *can* generate executables with py2exe, though if you use Python 3 you'll need to learn to convert your code to Python 2. Or, as Blender does, you could include Python in the download of your program, so that the user installs both your program and Python. On Nov 28, 2011, at 4:53 AM, surya k wrote: > > 1. Why doesn't python show error(description given below) at the beginning when we use functions which aren't present in the standard modules... > > Example: > > TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look closely, I used a wrong function to find length of the string. [ strlen( ) belongs to C ].When I run the program, it didn't show any error but when entered input, it then showed up!.Why python doesn't show error at the beginning just like C does?2. Why doesn't python create executable file (.exe ) when we run the code.. If this doesn't do, how can I share my program.. does everyone need to have python to check others code and know what it does? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Tue Nov 29 16:48:00 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 10:48:00 -0500 Subject: [Tutor] How to handle try and except in this case In-Reply-To: References: <4ED4A343.1020406@davea.name> <4ED4F955.5000304@davea.name> Message-ID: <4ED4FEB0.60708@davea.name> On 11/29/2011 10:35 AM, Mic wrote: > > > -----Ursprungligt meddelande----- From: Dave Angel Sent: Tuesday, > November 29, 2011 4:25 PM To: Mic Cc: tutor at python.org Subject: Re: > [Tutor] How to handle try and except in this case >> (You top-posted again. Try to put your remarks AFTER the part you're >> quoting, so that the message is self-descriptive) > > > > Is that top posting? > No, you're absolutely right. I don't know what I was looking at. Maybe I had your message scrolled when I was reading it. I am sorry. >> The os.path.exists(filename) returns a boolean, and doesn't tie up >> resources, so you are welcome to use it in an if expression. > >> if not (os.path.exists(file1) and os.path.exists(file2)): > >print "hi" > > > Thank you! What do you mean with that it "doesn't tie up resources"? If you do multiple opens in the same expression, you can't easily* capture all the file objects, especially in the case of an exception. So there may be files left open that will get closed an indeterminate amount of time in the future. That sort of thing is probably acceptable if the program is short-lived, but even then you can run into file-sharing conflicts. Note that current CPython versions are pretty good about closing files if you don't save the object, but other versions might not get around to it for a while. > > > Mic > * (you can partially solve this if you put the open inside a list comprehension or equivalent, but exceptions still rear their ugly heads) -- DaveA From o0MB0o at hotmail.se Tue Nov 29 16:52:47 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 16:52:47 +0100 Subject: [Tutor] Making a function run every second. In-Reply-To: <4ED4FB55.1000201@davea.name> References: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> <4ED4FB55.1000201@davea.name> Message-ID: -----Ursprungligt meddelande----- From: Dave Angel Sent: Tuesday, November 29, 2011 4:33 PM To: bodsda at googlemail.com Cc: Mic ; Tutor - python List Subject: Re: [Tutor] Making a function run every second. >(You put your response in the wrong place; it belongs after the part you're quoting.) Okay, thanks. On 11/29/2011 10:19 AM, bodsda at googlemail.com wrote: >> You won't get it exactly on because the time it takes to call the >> function will affect your trigger time. >> >> I would use something like an infinite loop with a 1 second sleep after >> the function call >> Bodsda > Sent from my BlackBerry? wireless device > >>> -----Original Message----- >>> From: "Mic" >>> Sender: tutor-bounces+bodsda=googlemail.com at python.org >>> Date: Tue, 29 Nov 2011 15:54:59 >>> To: >>> Subject: [Tutor] Making a function run every second. >>> Hi >>> I want a function to run every second , how do I do that? > >>> Say that the function look like this: > >>> def hi(): > print("hi") >Without a clearer spec, there are too many possible answers. As Bobsda >says, you can't get it exactly one second apart. But you also have the >problem of whether a drift is okay. For example, if you have a global >you're incrementing each time that function runs, and you want it to >represent the total time the program has been running, then a simple >sleep() is totally wrong. Okay, I undestand. Hmm, what is a drift? >What I was concerned about is that perhaps this is for one of the tkinter >programs Mic is writing. For an event-driven program, sleep() calls of >even a second are unaccepable. And if you literally write a while loop >like that, your whole program would stop responding. Yes, this is one of my tkinter programs :) Why would the program stop responding using a sleep()? >So Mik: >Tell us more about the real requirements. Is drift acceptable, is this a >console program or some gui environment, are there any other hidden >assumptions? Okay, this function approximately runs every second and check what the time is. (Well, every 30 second or every minute would be okay if that makes it easier) If the time is 15:00 it is supposed to remove a file. That should be all requirements! I have figured out how to make the function check what time it is and how to remove the file when the time is 15:00, but I don't know how to make it run every second or something like that. Thanks! Mic From cranky.frankie at gmail.com Tue Nov 29 16:54:49 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 29 Nov 2011 10:54:49 -0500 Subject: [Tutor] problem with msg widget & button Message-ID: Peter Otten <__peter__ at web.de> wrote: snip <> What I meant to say was, yes, I only want one message object, but I want that same object to be updated each time the next quote button is pressed. <> snip again OK, I think I tried it several ways and couldn't get any of them to work, but I tried your version and the button now works! My only question is this line, which is what I was missing: def display_quote(): msg_widget["text"] = choose_quote() Isn't msg_widget an object, like everything else in Python. If so, why is it not def display_quote(): msg_widget.text = choose_quote() That is one of the things I tried. I don't understand why the ["test"] pair works above. Now my only problem is the msg_widget box resizing. I'm using the .pack frame manager like the examples I've been reading say. I know there's a grid manager as well. I'll have to try that. All I want is the msg_widget to display the same size each time, no matter what size string is in it. Thanks Peter! -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From o0MB0o at hotmail.se Tue Nov 29 17:01:50 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 17:01:50 +0100 Subject: [Tutor] Making a function run every second. In-Reply-To: References: Message-ID: Mic wrote: >> I want a function to run every second , how do I do that? >> >> Say that the function look like this: >> >> def hi(): >> print("hi") >For a script that uses tkinter there's the after() method. >Example: >root = Tk() >def hi(): >print("ho") >def hi_reschedule(): > hi() ># make tkinter call it again after 1000 milliseconds >root.after(1000, hi_reschedule) >hi_reschedule() # call it manually the first time >http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html Nice! Thank you! ------------------------------ Message: 3 Date: Tue, 29 Nov 2011 10:33:41 -0500 From: Dave Angel To: bodsda at googlemail.com Cc: Tutor - python List , Mic Subject: Re: [Tutor] Making a function run every second. Message-ID: <4ED4FB55.1000201 at davea.name> Content-Type: text/plain; charset=windows-1252; format=flowed (You put your response in the wrong place; it belongs after the part you're quoting.) he On 11/29/2011 10:19 AM, bodsda at googlemail.com wrote: > You won't get it exactly on because the time it takes to call the function > will affect your trigger time. > > I would use something like an infinite loop with a 1 second sleep after > the function call > > Bodsda > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: "Mic" > Sender: tutor-bounces+bodsda=googlemail.com at python.org > Date: Tue, 29 Nov 2011 15:54:59 > To: > Subject: [Tutor] Making a function run every second. > > Hi > > I want a function to run every second , how do I do that? > > Say that the function look like this: > > def hi(): > print("hi") > > > Thanks! > > > Mic Without a clearer spec, there are too many possible answers. As Bobsda says, you can't get it exactly one second apart. But you also have the problem of whether a drift is okay. For example, if you have a global you're incrementing each time that function runs, and you want it to represent the total time the program has been running, then a simple sleep() is totally wrong. What I was concerned about is that perhaps this is for one of the tkinter programs Mic is writing. For an event-driven program, sleep() calls of even a second are unaccepable. And if you literally write a while loop like that, your whole program would stop responding. So Mik: Tell us more about the real requirements. Is drift acceptable, is this a console program or some gui environment, are there any other hidden assumptions? -- DaveA ------------------------------ Message: 4 Date: Tue, 29 Nov 2011 16:35:22 +0100 From: "Mic" To: Cc: tutor at python.org Subject: Re: [Tutor] How to handle try and except in this case Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response -----Ursprungligt meddelande----- From: Dave Angel Sent: Tuesday, November 29, 2011 4:25 PM To: Mic Cc: tutor at python.org Subject: Re: [Tutor] How to handle try and except in this case >(You top-posted again. Try to put your remarks AFTER the part you're >quoting, so that the message is self-descriptive) I did? I thought I posted this: """ >Could you explain what's unclear about it? Andreas couldn't get more >specific, since you didn't say how these 10 names are provided. Yes, it was probably my fault. Sorry about that. I have come up with a new way of working around a problem in my main program so I only need two files to be tested if they exist instead of say 10 files. """ Is that top posting? >The os.path.exists(filename) returns a boolean, and doesn't tie up >resources, so you are welcome to use it in an if expression. >if not (os.path.exists(file1) and os.path.exists(file2)): >print "hi" Thank you! What do you mean with that it "doesn't tie up resources"? Mic ------------------------------ Message: 5 Date: Mon, 28 Nov 2011 09:47:06 -0500 From: Max gmail To: surya k Cc: Python Tutor Subject: Re: [Tutor] why doesn't python show error Message-ID: Content-Type: text/plain; charset=iso-8859-1 In some cases, it is a useful fact that Python only shows error messages when they are encountered. For example, I can test a program while keeping away from an area that still doesn't work, rather than having to make it work flawlessly before my first test. Python *can* generate executables with py2exe, though if you use Python 3 you'll need to learn to convert your code to Python 2. Or, as Blender does, you could include Python in the download of your program, so that the user installs both your program and Python. On Nov 28, 2011, at 4:53 AM, surya k wrote: > > 1. Why doesn't python show error(description given below) at the beginning > when we use functions which aren't present in the standard modules... > > Example: > > TheString = raw_input('enter a string')lengthofStr = strlen(TheString)Look > closely, I used a wrong function to find length of the string. [ strlen( ) > belongs to C ].When I run the program, it didn't show any error but when > entered input, it then showed up!.Why python doesn't show error at the > beginning just like C does?2. Why doesn't python create executable file > (.exe ) when we run the code.. If this doesn't do, how can I share my > program.. does everyone need to have python to check others code and know > what it does? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ------------------------------ Message: 6 Date: Tue, 29 Nov 2011 10:48:00 -0500 From: Dave Angel To: Mic Cc: tutor at python.org Subject: Re: [Tutor] How to handle try and except in this case Message-ID: <4ED4FEB0.60708 at davea.name> Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 11/29/2011 10:35 AM, Mic wrote: > > > -----Ursprungligt meddelande----- From: Dave Angel Sent: Tuesday, > November 29, 2011 4:25 PM To: Mic Cc: tutor at python.org Subject: Re: > [Tutor] How to handle try and except in this case >> (You top-posted again. Try to put your remarks AFTER the part you're >> quoting, so that the message is self-descriptive) > > > > Is that top posting? > No, you're absolutely right. I don't know what I was looking at. Maybe I had your message scrolled when I was reading it. I am sorry. >> The os.path.exists(filename) returns a boolean, and doesn't tie up >> resources, so you are welcome to use it in an if expression. > >> if not (os.path.exists(file1) and os.path.exists(file2)): > >print "hi" > > > Thank you! What do you mean with that it "doesn't tie up resources"? If you do multiple opens in the same expression, you can't easily* capture all the file objects, especially in the case of an exception. So there may be files left open that will get closed an indeterminate amount of time in the future. That sort of thing is probably acceptable if the program is short-lived, but even then you can run into file-sharing conflicts. Note that current CPython versions are pretty good about closing files if you don't save the object, but other versions might not get around to it for a while. > > > Mic > * (you can partially solve this if you put the open inside a list comprehension or equivalent, but exceptions still rear their ugly heads) -- DaveA ------------------------------ Message: 7 Date: Tue, 29 Nov 2011 16:52:47 +0100 From: "Mic" To: , Cc: Tutor - python List Subject: Re: [Tutor] Making a function run every second. Message-ID: Content-Type: text/plain; format=flowed; charset="Windows-1252"; reply-type=response -----Ursprungligt meddelande----- From: Dave Angel Sent: Tuesday, November 29, 2011 4:33 PM To: bodsda at googlemail.com Cc: Mic ; Tutor - python List Subject: Re: [Tutor] Making a function run every second. >(You put your response in the wrong place; it belongs after the part you're quoting.) Okay, thanks. On 11/29/2011 10:19 AM, bodsda at googlemail.com wrote: >> You won't get it exactly on because the time it takes to call the >> function will affect your trigger time. >> >> I would use something like an infinite loop with a 1 second sleep after >> the function call >> Bodsda > Sent from my BlackBerry? wireless device > >>> -----Original Message----- >>> From: "Mic" >>> Sender: tutor-bounces+bodsda=googlemail.com at python.org >>> Date: Tue, 29 Nov 2011 15:54:59 >>> To: >>> Subject: [Tutor] Making a function run every second. >>> Hi >>> I want a function to run every second , how do I do that? > >>> Say that the function look like this: > >>> def hi(): > print("hi") >Without a clearer spec, there are too many possible answers. As Bobsda >says, you can't get it exactly one second apart. But you also have the >problem of whether a drift is okay. For example, if you have a global >you're incrementing each time that function runs, and you want it to >represent the total time the program has been running, then a simple >sleep() is totally wrong. Okay, I undestand. Hmm, what is a drift? >What I was concerned about is that perhaps this is for one of the tkinter >programs Mic is writing. For an event-driven program, sleep() calls of >even a second are unaccepable. And if you literally write a while loop >like that, your whole program would stop responding. Yes, this is one of my tkinter programs :) Why would the program stop responding using a sleep()? >So Mik: >Tell us more about the real requirements. Is drift acceptable, is this a >console program or some gui environment, are there any other hidden >assumptions? Okay, this function approximately runs every second and check what the time is. (Well, every 30 second or every minute would be okay if that makes it easier) If the time is 15:00 it is supposed to remove a file. That should be all requirements! I have figured out how to make the function check what time it is and how to remove the file when the time is 15:00, but I don't know how to make it run every second or something like that. Thanks! Mic ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 93, Issue 173 ************************************** From waynejwerner at gmail.com Tue Nov 29 17:06:08 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 29 Nov 2011 10:06:08 -0600 Subject: [Tutor] problem with msg widget & button In-Reply-To: References: Message-ID: On Tue, Nov 29, 2011 at 9:54 AM, Cranky Frankie wrote: > Peter Otten <__peter__ at web.de> wrote: > > Isn't msg_widget an object, like everything else in Python. If so, why is > it not > > def display_quote(): > msg_widget.text = choose_quote() > > That is one of the things I tried. I don't understand why the ["test"] > pair works above. > Just because msg_widget is an object doesn't automatically give it a .text attribute. Just like the following dictionary (which is an object): >>> knights = {'Aurthur': 'King of the Britons', 'Robin':'The Brave'} >>> knights['Robin'] 'The Brave' >>> knights['Robin'] = 'The Coward' >>> knights.Robin Traceback (most recent call last): File "", line 1, in AttributeError: 'dict' object has no attribute 'Robin' They simply made a design choice to allow access to the data via index (in this case "text" is the index), rather than by object attribute. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Nov 29 17:09:15 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 11:09:15 -0500 Subject: [Tutor] Making a function run every second. In-Reply-To: References: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> <4ED4FB55.1000201@davea.name> Message-ID: <4ED503AB.8010701@davea.name> On 11/29/2011 10:52 AM, Mic wrote: > > > -----Ursprungligt meddelande----- From: Dave Angel > Sent: Tuesday, November 29, 2011 4:33 PM > > >>>> -----Original Message----- >>>> From: "Mic" >>>> Sender: tutor-bounces+bodsda=googlemail.com at python.org >>>> Date: Tue, 29 Nov 2011 15:54:59 >>>> To: >>>> Subject: [Tutor] Making a function run every second. > >>>> Hi > >>>> I want a function to run every second , how do I do that? >> >>>> Say that the function look like this: >> >>>> def hi(): >> print("hi") > >> Without a clearer spec, there are too many possible answers. As Bobsda >> says, you can't get it exactly one second apart. But you also have the >> problem of whether a drift is okay. For example, if you have a global >> you're incrementing each time that function runs, and you want it to >> represent the total time the program has been running, then a simple >> sleep() is totally wrong. > > Okay, I undestand. Hmm, what is a drift? > >> What I was concerned about is that perhaps this is for one of the >> tkinter programs Mic is writing. For an event-driven program, sleep() >> calls of even a second are unaccepable. And if you literally write a >> while loop like that, your whole program would stop responding. > > Yes, this is one of my tkinter programs :) Why would the program stop > responding using a sleep()? > I'm not that familiar with tkinter details. But like all (almost??) GUI's it relies on an event loop. Each event has to be "quick" for some definition of quick. In the case of tkinter, I believe that eventloop is called mainloop(). That loop won't return till you hit the X button in the corner, or do something else that triggers program cancellation. That loop is the thing that interacts with the OS, and calls various event handlers as things happen. If you were to do a loop of sleep() before you got to the mainloop() call, the GUI would never start. If you do it inside some event, then the mainloop() never gets control again. tkinter provides a couple of specific timer events, and I now see your reply to a message that said to use the after() method, which is a one-shot. I believe there's another one that sets a periodic timer so you don't have to do an after() call each time it fires. >> So Mik: >> Tell us more about the real requirements. Is drift acceptable, is this >> a console program or some gui environment, are there any other hidden >> assumptions? > > Okay, this function approximately runs every second and check what the > time is. > (Well, every 30 second or every minute would be okay if that makes it > easier) > If the time is 15:00 it is supposed to remove a file. That should be all > requirements! > > I have figured out how to make the function check what time it is and > how to > remove the file when the time is 15:00, but I don't know how to make it > run every > second or something like that. > > > Thanks! > > Mic > -- DaveA From waynejwerner at gmail.com Tue Nov 29 17:22:56 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 29 Nov 2011 10:22:56 -0600 Subject: [Tutor] Making a function run every second. In-Reply-To: <4ED503AB.8010701@davea.name> References: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> <4ED4FB55.1000201@davea.name> <4ED503AB.8010701@davea.name> Message-ID: On Tue, Nov 29, 2011 at 10:09 AM, Dave Angel wrote: > tkinter provides a couple of specific timer events, and I now see > your reply to a message that said to use the after() method, which is a > one-shot. I believe there's another one that sets a periodic timer so you > don't have to do an after() call each time it fires. > Not in Tkinter - you have to do what Peter Otten suggested: > For a script that uses tkinter there's the after() method. > Example: > root = Tk() > def hi(): > print("ho") > def hi_reschedule(): > hi() > # make tkinter call it again after 1000 milliseconds > root.after(1000, hi_reschedule) > hi_reschedule() # call it manually the first time HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Nov 29 17:32:18 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 29 Nov 2011 08:32:18 -0800 Subject: [Tutor] useful function or reinventing the wheel?? In-Reply-To: References: Message-ID: On 11/28/2011 8:30 PM Mark Lybrand said... > I am a habitual wheel re-inventor, For anyone who hasn't yet discovered effbot's guide to the python library, it's a good place to start as you expand your python skills. see http://effbot.org/librarybook and in particular for your current question, you'll find makedirs with sample code at http://effbot.org/media/downloads/librarybook-core-modules.pdf Although dated, it's still a great place to start as most internal functions have changed little over the years. Emile so it would not surprise me, but I > made this little function that I was kinda proud of (seeing that I have > only been learning python like a week now): > > It just takes a directory and checks to see if all the directories, > sub-directories exist and creates them if they don't: > > def insure_exists_dir(dir): > grow_path = [dir] > while not os.path.ismount(grow_path[0]): > part_tuple = os.path.split(grow_path[0]) > grow_path.insert(0, part_tuple[0]) > > del(grow_path[0]) > while grow_path: > if not os.path.exists(grow_path[0]): > os.mkdir(grow_path[0]) > del(grow_path[0]) > return(dir) > > > Opinions? What should I really be using? > > -- > Mark :) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Tue Nov 29 18:46:40 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 12:46:40 -0500 Subject: [Tutor] Making a function run every second. In-Reply-To: <4ED503AB.8010701@davea.name> References: <975725611-1322579952-cardhu_decombobulator_blackberry.rim.net-705649369-@b4.c12.bise7.blackberry> <4ED4FB55.1000201@davea.name> <4ED503AB.8010701@davea.name> Message-ID: <4ED51A80.8030909@davea.name> On 11/29/2011 11:09 AM, Dave Angel wrote: > On 11/29/2011 10:52 AM, Mic wrote: >> >> >> Okay, I undestand. Hmm, what is a drift? >> I just noticed I hadn't answered that one. It doesn't matter any more since you're running tkinter. But for completeness: If you had a non-event driven program (eg. a console app), and you had a loop like the following: SLEEPTIME = 1 while True: sleep(SLEEPTIME) myfunc() myfunc() would be called about once a second. However, in a heavily loaded system, it might be 1.2 seconds one time, and 1.1 the next. So it might be called only 50 times in that minute, rather than 60. I believe that in some OS's, it might be called 75 times in a minute. Anyway, if drift is to be avoided, you need to keep track of the time that the next call should be made, compare it to "now", and calculate what to pass as a parameter to sleep(). In untested approx. code, import time import itertools starttime = float(now()) SLEEPTIME = 1 (for one second) for intervalnum in itertools.count(): delayneeded = starttime + SLEEPTIME*intervalnum - now() time.sleep(delayneeded) myfunc() if this drifts, it tries to compensate on the next iteration. Note that there are cleverer implementations of this fundamental scheme, depending on other requirements or goals. -- DaveA From cranky.frankie at gmail.com Tue Nov 29 19:02:50 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Tue, 29 Nov 2011 13:02:50 -0500 Subject: [Tutor] tkinter message & button questions Message-ID: I changed the quote program to use the grid manager: http://www.pastie.org/2939778 Still, the message widget box keeps resizing based on the length of the quote. I'm thinking it has to be something to do with the message widget itself, not the pack vs. grid manager. When I research this I find that a lot of the information on the message widget does not work in Python 3.1 - for example, the height parameter does not work in 3.1. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From o0MB0o at hotmail.se Tue Nov 29 19:02:52 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 19:02:52 +0100 Subject: [Tutor] How to write lines in a text file (GUI) In-Reply-To: References: Message-ID: Hey again. I figured I would first post this piece of code and then ask my questions. FREE = "green" OCCUPIED = "red" class Mainwindow(Frame): def __init__(self,master): super(Mainwindow,self).__init__(master) self.grid() self.create_mainwidgets() def create_mainwidgets(self): self.klicka=Button(self, text="Press the button", command=self.uppdatera) self.klicka.grid() def uppdatera(self): SeatWindow(root) class SeatButton(tk.Button): def __init__(self, master, index): text = str(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "Germany_France{}.txt".format(index+1) self.occupied = False if os.path.exists(self.filename): self["bg"]=OCCUPIED def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close() else: self["bg"] = FREE os.remove(self.filename) class SeatWindow(tk.Toplevel): def __init__(self, master): super (SeatWindow, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root=Tk() root.title("testV2") app=Mainwindow(root) root.mainloop() I am now writing another program. It turned out just fine, but I have one question. If button one is pressed I want the program to write, say hi_1, on the first line in a text file. If button one is pressed again, the first line should be empty. If button two is pressed I want the program to write hi_2 in the second line in the text file. If button two is pressed again, the second line in the text file should be empty. If button three is pressed I want the program to write hi_3 in the third line in the text file. if button three is pressed again, the third line in the text file should be empty. There shouldn't be any other changes to the program other than this above. There is already a text file created, the program doesn't need to create one. We can call that file "Hi". I hope you understand what I want to do here. I have tried the entire evening yesterday to get this to work, I tried using writeline() but I can't get it to work. What are your suggestions to this? Thank you for your help and time! From d at davea.name Tue Nov 29 19:19:53 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 13:19:53 -0500 Subject: [Tutor] How to write lines in a text file (GUI) In-Reply-To: References: Message-ID: <4ED52249.3080108@davea.name> On 11/29/2011 01:02 PM, Mic wrote: > Hey again. > > I figured I would first post this piece of code and then ask my > questions. How is this different from the question you posted 3 hours ago, with subject: "[Tutor] Creating a line in a text file every time a button is pressed." I'm working on a response to that one, but I wanted to wait for my lunch hour. Don't forget that everyone here's a volunteer. If you don't get a response for a couple of days, reply to the original message to add some more information, or to get people's attention. If it's the same question, keep it in the same thread. -- DaveA From bodsda at googlemail.com Tue Nov 29 19:27:39 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 29 Nov 2011 18:27:39 +0000 Subject: [Tutor] How to write lines in a text file (GUI) In-Reply-To: References: Message-ID: <216050534-1322591262-cardhu_decombobulator_blackberry.rim.net-890480418-@b4.c12.bise7.blackberry> Hi, This is a very simple objective to achieve, so instead of giving you a straight up solution, I will just nudge your train of thought in the right direction. Note: I'm struggling to follow your code whilst reading on my phone so the following suggestions make no reference to your particular codebase Let's first assume that all buttons could be pressed in any order, therefore given the following presses: but1, but2, but2, but3, we will have the first line with hi_1, the second line empty and the third line hi_3. Now I also assume that there is no 'update file' button, therefore each press of a button needs to update the file making a change to a single line. That sounds to me like a good use for an update_file function that accepts a parameter of which line should be updated. So the main challenge is to write a function that can read/write to a file certain data depending on the argument passed. The function should: Read file Identify line to be changed If line empty Change line to hi_# Write file When you open a file, you could then use the read function to read the whole file, or you could use the readlines function to read the file line by line. Experiment with both, see what data types they both return and decide which is most suitable. Bear in mind you need to easily differentiate each line and access them individually. If your still struggling to write this function, show us how far you get and we can go from there. Hope this helps, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: "Mic" Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Tue, 29 Nov 2011 19:02:52 To: Subject: [Tutor] How to write lines in a text file (GUI) Hey again. I figured I would first post this piece of code and then ask my questions. FREE = "green" OCCUPIED = "red" class Mainwindow(Frame): def __init__(self,master): super(Mainwindow,self).__init__(master) self.grid() self.create_mainwidgets() def create_mainwidgets(self): self.klicka=Button(self, text="Press the button", command=self.uppdatera) self.klicka.grid() def uppdatera(self): SeatWindow(root) class SeatButton(tk.Button): def __init__(self, master, index): text = str(index+1) super(SeatButton, self).__init__(master, text=text, bg=FREE, command=self.clicked) self.filename = "Germany_France{}.txt".format(index+1) self.occupied = False if os.path.exists(self.filename): self["bg"]=OCCUPIED def clicked(self): self.occupied = not self.occupied if self.occupied: self["bg"] = OCCUPIED text_file=open(self.filename,"w") text_file.write(self.filename) text_file.close() else: self["bg"] = FREE os.remove(self.filename) class SeatWindow(tk.Toplevel): def __init__(self, master): super (SeatWindow, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): for index in range(20): button = SeatButton(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root=Tk() root.title("testV2") app=Mainwindow(root) root.mainloop() I am now writing another program. It turned out just fine, but I have one question. If button one is pressed I want the program to write, say hi_1, on the first line in a text file. If button one is pressed again, the first line should be empty. If button two is pressed I want the program to write hi_2 in the second line in the text file. If button two is pressed again, the second line in the text file should be empty. If button three is pressed I want the program to write hi_3 in the third line in the text file. if button three is pressed again, the third line in the text file should be empty. There shouldn't be any other changes to the program other than this above. There is already a text file created, the program doesn't need to create one. We can call that file "Hi". I hope you understand what I want to do here. I have tried the entire evening yesterday to get this to work, I tried using writeline() but I can't get it to work. What are your suggestions to this? Thank you for your help and time! _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From d at davea.name Tue Nov 29 19:27:15 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 13:27:15 -0500 Subject: [Tutor] Creating a line in a text file every time a button is pressed. In-Reply-To: References: Message-ID: <4ED52403.9030700@davea.name> On 11/29/2011 10:09 AM, Mic wrote: > Hey again. > > > root=Tk() > root.title("testV2") > app=Mainwindow(root) > root.mainloop() > > > What's that code got to do with the question below? > > I am now writing another program. It turned out just fine, but I have > one question. > > If button one is pressed I want the program to write, say hi_1, on the > first line in a text file. > If button one is pressed again, the first line should be empty. > > If button two is pressed I want the program to write hi_2 in the > second line in the text file. > If button two is pressed again, the second line in the text file > should be empty. > You can't in general write randomly to a text file, especially if the line length changes. > If button three is pressed I want the program to write hi_3 in the > third line in the text file. > if button three is pressed again, the third line in the text file > should be empty. > > There shouldn't be any other changes to the program other than this > above. There is already a text file > created, the program doesn't need to create one. We can call that file > "Hi". > > > I hope you understand what I want to do here. I have tried the entire > evening yesterday to get this to work, I tried using writeline() but I > can't get it to work. > What are your suggestions to this? > You have at least three choices: 1) abandon the notion of a text file for this purpose. Make it a structured (binary) file, with fixed length fields. 2) same thing, but fake it in a text file, either by changing the contents so it's always the same size, or putting in redundant blanks. 3) reconstruct the entire file every time you want to change a line (other than the last one) to something larger or smaller. For #3, If the file is only about 3 lines, keep a list in memory, and dump the whole list to the file every time you change one of the items. For #1 and #2, you should look up the seek() method of the file class. -- DaveA From o0MB0o at hotmail.se Tue Nov 29 19:29:53 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 19:29:53 +0100 Subject: [Tutor] How to write lines in a text file (GUI) In-Reply-To: <4ED52249.3080108@davea.name> References: <4ED52249.3080108@davea.name> Message-ID: >How is this different from the question you posted 3 hours ago, with >subject: "[Tutor] Creating a line in a text file every time a button is >pressed." Sorry about the repost. My Email-client is set to resend the mail if it is marked as spam by the reciever. So, it wasn't the case, you didn't get it as spam mail? Hmm, this is the second time it happens today, could it be that I am sending from an hotmail address, perhaps they think that these addresses are more likely to be spam? I'm working on a response to that one, but I wanted to wait for my lunch hour. Don't forget that everyone here's a volunteer. If you don't get a response for a couple of days, reply to the original message to add some more information, or to get people's attention. If it's the same question, keep it in the same thread. Oh, where are you living if you are waiting for lunch? It's past dinner here, so that's why I got mails in the middle of the night! I thought most people were from UK! Mic From __peter__ at web.de Tue Nov 29 19:39:04 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 29 Nov 2011 19:39:04 +0100 Subject: [Tutor] tkinter message & button questions References: Message-ID: Cranky Frankie wrote: > I changed the quote program to use the grid manager: > > http://www.pastie.org/2939778 > > Still, the message widget box keeps resizing based on the length of > the quote. I'm thinking it has to be something to do with the message > widget itself, not the pack vs. grid manager. I've no experience with the place layout manager, but the following seems to be what you want: root = Tk() win = Frame(root) win.place(relheight=1, relwidth=1) label_widget = Label(win, text="Welcome to Quote of the Day") label_widget.pack(side=TOP, expand=YES, fill=BOTH) msg_widget = Message( win, anchor=NW, justify=LEFT, width=1000, bd=2, bg="white", relief=SOLID, text=choose_quote()) msg_widget.pack(fill=BOTH) next_button = Button(win, text="Next Quote", command=display_quote) next_button.pack(side=LEFT) quit_button = Button(win, text="QUIT", fg="red", command=quit) quit_button.pack(side=RIGHT) root.geometry("400x100") root.mainloop() From o0MB0o at hotmail.se Tue Nov 29 20:24:24 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 29 Nov 2011 20:24:24 +0100 Subject: [Tutor] How to write lines in a text file (GUI) In-Reply-To: <216050534-1322591262-cardhu_decombobulator_blackberry.rim.net-890480418-@b4.c12.bise7.blackberry> References: <216050534-1322591262-cardhu_decombobulator_blackberry.rim.net-890480418-@b4.c12.bise7.blackberry> Message-ID: >Note: I'm struggling to follow your code whilst reading on my phone so the >following suggestions make no reference to your particular codebase Okay I understand. Perhaps it doesn't matter. >Let's first assume that all buttons could be pressed in any order, >therefore given the following presses: but1, but2, but2, but3, we will have >the first line with hi_1, the second line empty and the third line hi_3. >Now I also assume that there >is no 'update file' button, therefore each >press of a button needs to update the file making a change to a single >line. That sounds to me like a good use for an update_file function that >accepts a parameter of which line should be updated. >So the main challenge >is to write a function that can read/write to a file certain data depending >on the argument passed. The function should: >Read file >Identify line to be changed >If line empty >Change line to hi_# >Write file >When you open a file, you could then use the read function to read the >whole file, or you could use the readlines function to read the file line >by line. Experiment with both, see what data types they both return and >decide which is most >suitable. Bear in mind you need to easily >differentiate each line and access them individually. >If your still struggling to write this function, show us how far you get >and we can go from there. Actually, I nearly know how do to solve this problem. I just have one problem. Can I use writeline() to write text into line 3 or line 5 for example? Say that I want to write the text "hi" into line five of a text file, can I do this using writeline(), if so, how ? Thanks for the response! Hope this helps, Bodsda Sent from my BlackBerry? wireless device From kellyadrian at hotmail.com Tue Nov 29 21:31:56 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Tue, 29 Nov 2011 20:31:56 +0000 Subject: [Tutor] list, tuple or dictionary Message-ID: i am trying to create a program that will allow users to enter items and their prices; should i be looking at a list, tuple or what? many thanksadrian -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Tue Nov 29 21:36:12 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 29 Nov 2011 20:36:12 +0000 Subject: [Tutor] How to write lines in a text file (GUI) Message-ID: <1570585607-1322598973-cardhu_decombobulator_blackberry.rim.net-1241030845-@b4.c12.bise7.blackberry> I'm not sure, I also don't have access to the python docs atm, but the simplest method would be to read the whole file into a list, edit the correct item (remembering to count from 0 not 1) and then writing the whole list back to the file. Bodsda ------Original Message------ From: Mic To: bodsda at googlemail.com To: tutor-bounces+bodsda=googlemail.com at python.org To: Tutor - python List Subject: Re: [Tutor] How to write lines in a text file (GUI) Sent: 29 Nov 2011 19:24 >Note: I'm struggling to follow your code whilst reading on my phone so the >following suggestions make no reference to your particular codebase Okay I understand. Perhaps it doesn't matter. >Let's first assume that all buttons could be pressed in any order, >therefore given the following presses: but1, but2, but2, but3, we will have >the first line with hi_1, the second line empty and the third line hi_3. >Now I also assume that there >is no 'update file' button, therefore each >press of a button needs to update the file making a change to a single >line. That sounds to me like a good use for an update_file function that >accepts a parameter of which line should be updated. >So the main challenge >is to write a function that can read/write to a file certain data depending >on the argument passed. The function should: >Read file >Identify line to be changed >If line empty >Change line to hi_# >Write file >When you open a file, you could then use the read function to read the >whole file, or you could use the readlines function to read the file line >by line. Experiment with both, see what data types they both return and >decide which is most >suitable. Bear in mind you need to easily >differentiate each line and access them individually. >If your still struggling to write this function, show us how far you get >and we can go from there. Actually, I nearly know how do to solve this problem. I just have one problem. Can I use writeline() to write text into line 3 or line 5 for example? Say that I want to write the text "hi" into line five of a text file, can I do this using writeline(), if so, how ? Thanks for the response! Hope this helps, Bodsda Sent from my BlackBerry? wireless device Sent from my BlackBerry? wireless device From bodsda at googlemail.com Tue Nov 29 21:37:54 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 29 Nov 2011 20:37:54 +0000 Subject: [Tutor] list, tuple or dictionary In-Reply-To: References: Message-ID: <1216168036-1322599077-cardhu_decombobulator_blackberry.rim.net-2136952888-@b4.c12.bise7.blackberry> You could use any of them, but a dict would be the most logical assuming no duplicate items Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: ADRIAN KELLY Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Tue, 29 Nov 2011 20:31:56 To: Subject: [Tutor] list, tuple or dictionary _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From waynejwerner at gmail.com Tue Nov 29 21:49:00 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 29 Nov 2011 14:49:00 -0600 Subject: [Tutor] list, tuple or dictionary In-Reply-To: References: Message-ID: On Tue, Nov 29, 2011 at 2:31 PM, ADRIAN KELLY wrote: > i am trying to create a program that will allow users to enter items and > their prices; should i be looking at a list, tuple or what? > The entering part isn't as important as how you want to display the data. For instance, here's a program that allows the user to input an unlimited amount of data (using Python 3.x): while input("Enter q to quit, or an item: ").lower() not in ('q', 'quit', 'goodbye'): input("Enter the price: ") Of course it doesn't store the data, so it's pretty useless. But it does allow the user to input whatever they want. If you wanted to simply create a collection of items you could do it as a list with alternating values: inventory = ['Crunchy Frog', 4.13, 'Anthrax Ripple', 12.99999999999, 'Spring Surprise', 0.00] for x in range(0, len(inventory)-1, 2): print(inventory[x], inventory[x+1]) Or as a list of tuples: inventory = [('Norwegian Blue', 500.00), ('Slug', 500.00), ('Cage', 50.00)] for item in inventory: print(item[0], item[1]) Or a dictionary: inventory = {'Spam':5.00, 'Spam on eggs':10.00, 'Spam on Spam':7.50} for item, price in inventory.items(): print(item, price) Or if you wanted to get ridiculous, you could go with a list of classes: class Item: def __init__(self, desc='', price=0.00): self.desc = desc self.price = price def __repr__(self): return str(self) def __str__(self): return "{0} - {1}".format(self.desc, self.price) inventory = [Item('Lumberjack', 5.5), Item('Tree', 50), Item('Flapjack', 0.5)] for item in inventory: print(item) It just depends on how complex you want to get! HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Tue Nov 29 22:04:35 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Tue, 29 Nov 2011 21:04:35 +0000 Subject: [Tutor] list, tuple or dictionary In-Reply-To: References: , Message-ID: thanks guy, i was thinking of using a dictionary:- Stock_list = {"White Bread": 1.24, "Biscuits": 1.77, "Banana" : 0.23, "Tea Bags" : 2.37, "Eggs" : 1.23, "Beans" : 0.57} how would i go about adding, for example tea and eggs to get a subtotal? Adrian Kelly 1 Bramble Close Baylough Athlone County Westmeath 0879495663 From: waynejwerner at gmail.com Date: Tue, 29 Nov 2011 14:49:00 -0600 Subject: Re: [Tutor] list, tuple or dictionary To: kellyadrian at hotmail.com CC: tutor at python.org On Tue, Nov 29, 2011 at 2:31 PM, ADRIAN KELLY wrote: i am trying to create a program that will allow users to enter items and their prices; should i be looking at a list, tuple or what? The entering part isn't as important as how you want to display the data. For instance, here's a program that allows the user to input an unlimited amount of data (using Python 3.x): while input("Enter q to quit, or an item: ").lower() not in ('q', 'quit', 'goodbye'): input("Enter the price: ") Of course it doesn't store the data, so it's pretty useless. But it does allow the user to input whatever they want. If you wanted to simply create a collection of items you could do it as a list with alternating values: inventory = ['Crunchy Frog', 4.13, 'Anthrax Ripple', 12.99999999999, 'Spring Surprise', 0.00] for x in range(0, len(inventory)-1, 2): print(inventory[x], inventory[x+1]) Or as a list of tuples: inventory = [('Norwegian Blue', 500.00), ('Slug', 500.00), ('Cage', 50.00)] for item in inventory: print(item[0], item[1]) Or a dictionary: inventory = {'Spam':5.00, 'Spam on eggs':10.00, 'Spam on Spam':7.50} for item, price in inventory.items(): print(item, price) Or if you wanted to get ridiculous, you could go with a list of classes: class Item: def __init__(self, desc='', price=0.00): self.desc = desc self.price = price def __repr__(self): return str(self) def __str__(self): return "{0} - {1}".format(self.desc, self.price) inventory = [Item('Lumberjack', 5.5), Item('Tree', 50), Item('Flapjack', 0.5)]for item in inventory: print(item) It just depends on how complex you want to get! HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Nov 29 22:11:46 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 29 Nov 2011 15:11:46 -0600 Subject: [Tutor] list, tuple or dictionary In-Reply-To: References: Message-ID: On Tue, Nov 29, 2011 at 3:04 PM, ADRIAN KELLY wrote: > thanks guy, i was thinking of using a dictionary:- > Stock_list = {"White Bread": 1.24, > "Biscuits": 1.77, > "Banana" : 0.23, > "Tea Bags" : 2.37, > "Eggs" : 1.23, > "Beans" : 0.57} > > how would i go about *adding, *for example tea and eggs to get a subtotal? > Why, you would add tea and eggs, of course! print("Subtotal: ", Stock_list["Tea Bags"] + Stock_list["Eggs"]) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kellyadrian at hotmail.com Tue Nov 29 22:25:17 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Tue, 29 Nov 2011 21:25:17 +0000 Subject: [Tutor] list, tuple or dictionary In-Reply-To: References: , , Message-ID: Sound Wayne, thank you From: waynejwerner at gmail.com Date: Tue, 29 Nov 2011 15:11:46 -0600 Subject: Re: [Tutor] list, tuple or dictionary To: kellyadrian at hotmail.com CC: tutor at python.org On Tue, Nov 29, 2011 at 3:04 PM, ADRIAN KELLY wrote: thanks guy, i was thinking of using a dictionary:- Stock_list = {"White Bread": 1.24, "Biscuits": 1.77, "Banana" : 0.23, "Tea Bags" : 2.37, "Eggs" : 1.23, "Beans" : 0.57} how would i go about adding, for example tea and eggs to get a subtotal? Why, you would add tea and eggs, of course! print("Subtotal: ", Stock_list["Tea Bags"] + Stock_list["Eggs"]) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mayoadams at gmail.com Tue Nov 29 22:40:49 2011 From: mayoadams at gmail.com (Mayo Adams) Date: Tue, 29 Nov 2011 16:40:49 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: <4ED4D7F8.5000507@pearwood.info> References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> Message-ID: Apologies for my numerous offenses to protocol, and gratitude for the suggestions all around.And yet... as to the notion of a tuple existing in some non-Platonic sense, I suspect I will have carry my confusion away in order to dispel it by further reading. "Wrong on both counts?" Hey, you win! I WAS wrong. But if it is not a tuple that is in the file, it would be helpful to know what it is. Presumably, a string representing a tuple. And as to the matter of representation, I cant immediately see how anything in a script is anything other than a representation of some kind, hence the distinction between representamen and object does no work for me. Yes, I should have been clearer as to what I was trying to achieve, but I underestimated the good will of this community(in most cases)and their willingness to help. For which, as I said, much thanks. On Tue, Nov 29, 2011 at 8:02 AM, Steven D'Aprano wrote: > Peter Otten wrote: > >> And here's the lazy-bastard version: > > [...] >> >> ... ? ? print ast.literal_eval(line.strip()) > > Nice! > > > -- > Steven > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Mayo Adams 287 Erwin Rd. Chapel Hill, NC 27514 (919)-968-7889 mayoadams at gmail.com From waynejwerner at gmail.com Tue Nov 29 23:12:41 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 29 Nov 2011 16:12:41 -0600 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> Message-ID: On Tue, Nov 29, 2011 at 3:40 PM, Mayo Adams wrote: > I cant immediately see how anything in a script is > anything other than a representation of some kind, hence the > distinction between representamen and object does no work for me. > That's exactly it - when you have something like this in a file named, say data.txt: ("This", 'is', 'a', 'silly', 'tuple') Then that's all it is - just text data. I happens to *look* like a tuple, but it's not. If you rename that file to data.py... well, it's still text data. If you add an assignment operation to the line: data = ("This", 'is', 'a', 'silly', 'tuple') Then you could actually import it with `from data import data`. Once the data is actually evaluated, then it's "live" - it really is a tuple, and it can be used in tuple-ish ways. I think the main reason to make a distinction like that is that if you encounter a .py file with data like this: > "__import__('os').system('echo i got you now rm-rf')" You know it's probably going to do some bad things to your system if you run it. If you open that in a text editor, on the other hand, it's unlikely to do anything painful. I think there's also some use in making the distinction between data and code. Python provides you with /ridiculously/ easy ways to read in data. So if you have a bunch of strings that you want in a tuple you should do something like: data = tuple(f.open('data.txt').readlines()) Which has the added advantage of *just* reading in strings. If you want to convert that data into other types (integer, float, etc.) then you can easily do it explicitly, and explicit is better than implicit. In reality of course, all the data is just 1's and 0's floating out there, but I think it's helpful to develop these abstractions. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Nov 29 23:12:55 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 17:12:55 -0500 Subject: [Tutor] How to write lines in a text file (GUI) In-Reply-To: References: <216050534-1322591262-cardhu_decombobulator_blackberry.rim.net-890480418-@b4.c12.bise7.blackberry> Message-ID: <4ED558E7.1000707@davea.name> On 11/29/2011 02:24 PM, Mic wrote: > > > > Actually, I nearly know how do to solve this problem. I just have one > problem. Can I use writeline() to write text into line 3 or line 5 for > example? > Say that I want to write the text "hi" into line five of a text file, > can I do this using writeline(), if so, how ? > This is why you should stick to one thread for one problem. Read my reply on your original thread. You cannot safely update intermediate lines in a text file unless you're positive they're the same length. And even then, using seek() to position yourself is fraught with problems, especially if you have to work on Windows. Either use a binary file, or write the whole file out each time. -- DaveA From d at davea.name Wed Nov 30 00:16:30 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 18:16:30 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> Message-ID: <4ED567CE.1070405@davea.name> On 11/29/2011 04:40 PM, Mayo Adams wrote: > Apologies for my numerous offenses to protocol, and gratitude for the > suggestions all around.And yet... as to the notion of a tuple > existing in some non-Platonic sense, I suspect I will have carry my > confusion away in order to dispel it by further reading. > "Wrong on both counts?" Hey, you win! I WAS wrong. But if it is not a > tuple that is in the file, it would be helpful to know what it is. > Presumably, a string representing a tuple. And as to the matter of > representation, I cant immediately see how anything in a script is > anything other than a representation of some kind, hence the > distinction between representamen and object does no work for me. > > Yes, I should have been clearer as to what I was trying to achieve, > but I underestimated the good will of this community(in most cases)and > their willingness to help. For which, as I said, much thanks. Nicely worded. We appreciate your confusion, but please realize that each of us comes from a different background, computing-wise. In traditional (compiled) languages, there was a sharp and uncrossable division between the stuff in source files and the stuff in data files. The former got compiled (by multi-million dollar machines) into machine code, which used the latter as data, both input and output. The data the user saw never got near a compiler, so the rules of interpreting it were entirely different. A file was just a file, a bunch of bytes made meaningful only by the particular application that dealt with it. And the keyboard, screen and printer (and the card punch/reader) were in some sense just more files. This had some (perhaps unforeseen) advantages in isolating the differing parts of the application. Source code was written by highly trained people, who tried to eliminate the bugs and crashes before releasing the executable to the public. Once debugged, this code was extremely protected against malicious and careless users (both human and virus, both local and over the internet) who might manage to corrupt things. The operating systems and hardware were also designed to make this distinction complete, so that even buggy programs couldn't harm the system itself. I've even worked on systems where the code and the data weren't even occupying the same kind of memory. When a program crashed the system, it was our fault, not the users' because we didn't give him (at least not on purpose) the ability to run arbitrary code. then came the days of MSDOS, which is a totally unprotected operating system, and scripting languages and interpreters, which could actually run code from data files, and the lines became blurry. People were writing malicious macros into word processing data, and the machines actually would crash from it. (Actually things were not this linear, interpreters have been around practically forever, but give me a little poetic license) So gradually, we've added protection back into our personal systems that previously was only on mainframes. But the need for these protections is higher today than ever before, mainly because of the internet. So to Python. Notice that the rules for finding code are different than those for finding data files. No accident. We WANT to treat them differently. We want data files to be completely spec'ed out, as to what data is permissible and what is not. Without such a spec, programs are entirely unpredictable. The whole Y2K problem was caused because too many programmers made unwarranted assumptions about their data (in that case about the range of valid dates). And they were also saving space, in an era where hard disks were available for maybe three thousand dollars for 10 megabytes. Ever filled in a form which didn't leave enough room for yout town name, or that assumed that city would not have spaces? Ever had software that thought that apostrophes weren't going to happen in a person's name? Or that zip codes are all numeric (true in US, not elsewhere). Or that names only consist of the 26 English letters. Or even that only the first letter would be capitalized. Anyway, my post was pointing out that without constraining the data, it was impractical/unsafe/unwise to encode the data in a byte stream(file), and expect to decode it later. In your example, you encoded a tuple that was a string and an integer. You used repr() to do it, and that can be fine. But the logic to transform that string back into a tuple is quite complex, if you have to cover all the strange cases. And impossible, if you don't know anything about the data. A tuple object in memory doesn't look anything like the text you save to that file. It's probably over a hundred bytes spread out over at least three independent memory blocks. But we try to pretend that the in-memory object is some kind of idealized tuple, and don't need to know the details. Much of the space is taken up by pointers, and pointers to pointers, that reference the code that knows how to manipulate it. You might want to look into shelve or pickle, which are designed to save objects to a file and restore them later. These have to be as general as possible, and the complexity of both the code and the resultant data file reflects that. -- DaveA From steve at pearwood.info Wed Nov 30 00:22:03 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 30 Nov 2011 10:22:03 +1100 Subject: [Tutor] list, tuple or dictionary In-Reply-To: References: Message-ID: <4ED5691B.1060209@pearwood.info> ADRIAN KELLY wrote: > i am trying to create a program that will allow users to enter items and their prices; should i be looking at a list, tuple or what? > many thanksadrian Translated to a version more familiar in the "real world": "I'm looking to build a wooden wardrobe that will allow the user to store their clothes. Should I be using a saw, a hammer, a drill, or what?" The only correct answer is "Yes you should." Lists, tuples and dicts are all basic tools in your programming toolbox, you should ALWAYS be looking at using them. But you use them for different purposes. Perhaps if you narrow your question down to something more specific we can give a more useful answer. Or... just try it! Don't be scared to write some code to throw it away. Especially when learning, there is no better way to learn than to write some code, discover what you can and can't do with the tools, learn the limitations by trying it, and then using that knowledge to write better code. -- Steven From emile at fenx.com Wed Nov 30 00:40:44 2011 From: emile at fenx.com (emile) Date: Tue, 29 Nov 2011 15:40:44 -0800 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: <4ED567CE.1070405@davea.name> References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> <4ED567CE.1070405@davea.name> Message-ID: <4ED56D7C.1020708@fenx.com> Dave Angel wrote: > The whole Y2K problem was caused because > too many programmers made unwarranted assumptions about their data (in > that case about the range of valid dates). Well, yes. But we knew then that the stuff we were writing wouldn't still be in play 25 years out. :) > And they were also saving > space, in an era where hard disks were available for maybe three > thousand dollars for 10 megabytes. I remember it well... if not fondly. 5Mb internal and 5Mb removable. Eventually (by 1980) we could buy 80Mb drives dumbed down to 35Mb for $20k. Quite a bit better than the IBM mag-card system I started with, itself a step up from single use punch cards... Emile From d at davea.name Wed Nov 30 01:44:21 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 19:44:21 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: <4ED56D7C.1020708@fenx.com> References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> <4ED567CE.1070405@davea.name> <4ED56D7C.1020708@fenx.com> Message-ID: <4ED57C65.6040507@davea.name> On 11/29/2011 06:40 PM, emile wrote: > Dave Angel wrote: > > > > > The whole Y2K problem was caused because >> too many programmers made unwarranted assumptions about their data (in >> that case about the range of valid dates). > > Well, yes. But we knew then that the stuff we were writing wouldn't > still be in play 25 years out. :) > >> And they were also saving space, in an era where hard disks were >> available for maybe three thousand dollars for 10 megabytes. > > I remember it well... if not fondly. 5Mb internal and 5Mb removable. > Eventually (by 1980) we could buy 80Mb drives dumbed down to 35Mb for > $20k. Quite a bit better than the IBM mag-card system I started with, > itself a step up from single use punch cards... > > Emile > > > I also started on punched cards, for maybe the first 30,000 "lines" of code. I also had to deal with paper tape for object file transport. Talk about unreliable. Any chance you were a customer or vendor of Wang? That 80mb drive, dumbed down, for prices around $20k, rings a bell. -- DaveA From alan.gauld at btinternet.com Wed Nov 30 01:52:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Nov 2011 00:52:33 +0000 Subject: [Tutor] why doesn't python show error In-Reply-To: References: Message-ID: On 28/11/11 10:31, surya k wrote: > Thanks for that information. I understood what you are saying but in > general when python doesn't give us executable files (whether its in > Mac/ Linux/ Windows).. how could people develop programs ?. > At some point of time people need to provide a file that runs without > the help of a python interpreter.. As Stephen pointed out many programs run in interpreted environments including almost every web client side program. But even if you compile the code to a native exe it will usually still not be truly standalone. Any Windows program will rely on the existence of the standard Windows DLLs and libraries such as msvcrt. Unix programs expect the standard libc and other libraries to be there. Unless you are in the extremely unusual position of writing software for an embedded device without any OS support then your code needs support files. What difference does it make whether they are in the form of shared libraries or an interpreter like .NET or the Java JVM or the Python interpreter? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mlybrand at gmail.com Wed Nov 30 02:09:34 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Tue, 29 Nov 2011 17:09:34 -0800 Subject: [Tutor] Treating lists as lists Message-ID: I am pretty sure I saw this somewhere but now I can't. Here's the problem: list = ['hello', 'world'] template = '%s %s' print template % list But it appears that list is just one (list) when I want to treat it as two (items). I can do that right? How, pretty please? Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Nov 30 02:14:40 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 30 Nov 2011 02:14:40 +0100 Subject: [Tutor] Treating lists as lists In-Reply-To: References: Message-ID: On Wed, Nov 30, 2011 at 2:09 AM, Mark Lybrand wrote: > I am pretty sure I saw this somewhere but now I can't.? Here's the problem: > list = ['hello', 'world'] > template = '%s %s' > print template % list > > But it appears that list is just one (list) when I want to treat it as two > (items).? I can do that right?? How, pretty please? > > Mark > The % operator doesn't work with lists, you need to make that a tuple. It should work then. Hugo From alan.gauld at btinternet.com Wed Nov 30 02:16:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Nov 2011 01:16:14 +0000 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> Message-ID: On 29/11/11 21:40, Mayo Adams wrote: > tuple that is in the file, it would be helpful to know what it is. > Presumably, a string representing a tuple. Exactly so, everything in the file is a string. If it's a binary file it is a string of bytes, if it is a text file a string of characters. The interpretation of those bytes or characters is down to the reading program. The program must convert the string into data. The string represents the data that will be eventually created in the computer's memory within the interpreter's execution environment. > representation, I cant immediately see how anything in a script is > anything other than a representation of some kind, hence the > distinction between representamen and object does no work for me. While it is in the file it is just a string. a string representation of a program. The interpreter reads that string and converts it into symbol tables, executable objects and data structures. Your program, when it reads a file must do exactly the same, it must convert the string read from the file into whatever data structure it represents and, if necessary, assign that data to a variable for future reference. The process of reading a string and interpreting its meaning as data is what's known as parsing. There are several parsers available in Python to help with that task, as well as some tools to help you write your own parser. Examples are the csv module, HTMLParser, xpat and ElementTree. But even with these you will often have to do the final type conversion from string to integer or Boolean etc yourself. The other option is to use binary files where the data is stored in strings of bytes. In this case you still need to interpret the string but you do so by reading the exact number of bytes needed to store the particular data type, for example 4 bytes for a 32 bit integer. You then have to convert those 4 bytes into an integer. Again Python offers some help in the form of the struct module. Binary files are usually more compact than text files storing the same information, but they are far harder to interpret. There are other standard types of binary file and Python offers support for some, most notably there are libraries to read Excel files, various databases and PDF documents. Most of these libraries will also contain functions that help you write data back out to the files in the same format as well. The goal of all of these libraries is to make it comparatively easy to read a string representation from a file and convert it into real data that we can manipulate in our programs. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Wed Nov 30 02:22:58 2011 From: d at davea.name (Dave Angel) Date: Tue, 29 Nov 2011 20:22:58 -0500 Subject: [Tutor] Treating lists as lists In-Reply-To: References: Message-ID: <4ED58572.5050207@davea.name> On 11/29/2011 08:09 PM, Mark Lybrand wrote: > I am pretty sure I saw this somewhere but now I can't. Here's the problem: > list = ['hello', 'world'] > template = '%s %s' > print template % list > > But it appears that list is just one (list) when I want to treat it as two > (items). I can do that right? How, pretty please? > > Mark > print template % tuple(list) -- DaveA From alan.gauld at btinternet.com Wed Nov 30 02:23:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Nov 2011 01:23:40 +0000 Subject: [Tutor] Making a function run every second. In-Reply-To: References: Message-ID: On 29/11/11 14:54, Mic wrote: > I want a function to run every second , how do I do that? > > Say that the function look like this: > > def hi(): > print("hi") The answer depends on whether you want to do it in a GUI or in a command line program. Since your other posts have included GUI code I'd suggest you check out the documentation for the after() method in Tkinter. If it's for command line look at time.sleep() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 30 02:30:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Nov 2011 01:30:52 +0000 Subject: [Tutor] How to write lines in a text file (GUI) In-Reply-To: References: <4ED52249.3080108@davea.name> Message-ID: On 29/11/11 18:29, Mic wrote: > Oh, where are you living if you are waiting for lunch? It's past dinner > here, so that's why I got mails in the middle of the night! I thought most > people were from UK! You are on the internet, its global! :-) Most tutor subscribers are actually US based I suspect, but we literally have subscribers in every continent. But I'm in the UK and it's way past midnight :-) And I'm off to bed now, got a 8:30am start tomorrow... :-( -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Wed Nov 30 03:44:46 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 29 Nov 2011 21:44:46 -0500 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: <4ED56D7C.1020708@fenx.com> References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> <4ED567CE.1070405@davea.name> <4ED56D7C.1020708@fenx.com> Message-ID: <4ED5989E.2080509@gmail.com> On 11/29/2011 6:40 PM, emile wrote: > Dave Angel wrote: > > ... single use punch cards... > You didn't have an IBM 719 CARD punch? (ChAd Restoration Device). Made reuse of punch cards very easy. -- Bob Gailer 919-636-4239 Chapel Hill NC From mlybrand at gmail.com Wed Nov 30 03:54:38 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Tue, 29 Nov 2011 18:54:38 -0800 Subject: [Tutor] Treating lists as lists In-Reply-To: <4ED58572.5050207@davea.name> References: <4ED58572.5050207@davea.name> Message-ID: Thanks everyone. Right before quitting time my brain froze up :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From therealdotcomboy at gmail.com Wed Nov 30 04:22:01 2011 From: therealdotcomboy at gmail.com (Rodney Lewis) Date: Tue, 29 Nov 2011 19:22:01 -0800 Subject: [Tutor] Programming Collective Intelligence Study Group In-Reply-To: References: Message-ID: Sounds like an awesome idea to me. I'm on board. Keep the list informed about that please. And thanks for the links to the machine learning and nlp resources! http://www.squidoo.com/introductiontopython On Tue, Nov 29, 2011 at 12:42 AM, Mark Lybrand wrote: > Over on the Machine Learning Class, I mentioned the idea of setting up some > online resources to go through the Programming Collective Intelligence book > as a group. This would include a group or discussion board of some type, > maybe a Google+ or Facebook page, and a wiki. ?Then we would set a pace and > work through the book. ?Since it is in Python, I thought this group would be > interested. ?Am I wrong? ?If it works out pretty good, we will probably > continue with Natural Language Processing (also Python) after we finish. > So, what is the interest like here? ?Let me know and I will give you guys a > heads up when I get everything all set up. > > -- > Mark :) > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Rodney Lewis Please Visit My Homepage: http://www.squidoo.com/dotcomboy From bgailer at gmail.com Wed Nov 30 04:55:48 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 29 Nov 2011 22:55:48 -0500 Subject: [Tutor] Programming Collective Intelligence Study Group In-Reply-To: References: Message-ID: <4ED5A944.3020308@gmail.com> On 11/29/2011 3:42 AM, Mark Lybrand wrote: > Over on the Machine Learning Class, I mentioned the idea of setting up > some online resources to go through the Programming Collective > Intelligence book as a group. This would include a group or discussion > board of some type, maybe a Google+ or Facebook page, and a wiki. > Then we would set a pace and work through the book. Since it is in > Python, I thought this group would be interested. Am I wrong? If it > works out pretty good, we will probably continue with Natural Language > Processing (also Python) after we finish. > > So, what is the interest like here? Let me know and I will give you > guys a heads up when I get everything all set up. I'm interested too. -- Bob Gailer 919-636-4239 Chapel Hill NC From mlybrand at gmail.com Wed Nov 30 08:52:15 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Tue, 29 Nov 2011 23:52:15 -0800 Subject: [Tutor] Programming Collective Intelligence Study Group In-Reply-To: <4ED5A944.3020308@gmail.com> References: <4ED5A944.3020308@gmail.com> Message-ID: Before I launch in on my master scheme. I have come across another couple of interesting Machine Learning/Python books: Mining the Social Web by Matthew Russell. O'Reilly ISBN-13: 978-1449388348 Machine Learning: An Algorithmic Perspective by Stephen Marsland. ISBN-13: 978-1420067187 Okay, this is what I am thinking of trying out: 1. I will read through a chapter and try to provide a write up of the material with the algorithms. Hopefully enough that even those without the book can follow the source code and our discussions. 2. This will be communicated to Twitter, Google+ (I will make a page) and Google Groups (I will make a group) 3. I will put a Wiki on my website and give anyone who wants it edit access (just contact me). There we can store notes and links and general resources, with the idea that it could be a good Python/Machine Learning/AI resource for us and others. I will try to get up an initial post in the next week our two and announce it here to allow folks to hook in via their preferred media. This post is being made at the Machine Learning forum and to the Python Tutor mailing list. If you think of anywhere else to get the word out, just holler. I am thinking maybe the AI reddit group, AIQUS and the forum on the AI class site. Others? Mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Wed Nov 30 15:32:37 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Wed, 30 Nov 2011 09:32:37 -0500 Subject: [Tutor] tkinter message & button questions Message-ID: Peter Otten <__peter__ at web.de> wrote: To: tutor at python.org Subject: Re: [Tutor] tkinter message & button questions Message-ID: Content-Type: text/plain; charset="ISO-8859-1" <> Peter thanks again. The msg_widget is still resizing vertically depending on the lenght of the quote, but at least now the horizontal sizing is staying the same. Ideally the msg_widget would be the *same size*, no matter what the quote length is, but since this program is really just a learning exercise and to show database adminstrators a simple Python GUI application I can live with it. The syntax you used, like "root.geometry("400x100")", I have not seen before, and I've done a lot of searching. Again, much of the tkinter stuff I see seems to be based on Python 2.6. If there is a definitive book or reference on using tkinter in Python 3.x I'd really like to know about it. Thanks again Peter, Wayne, and everyone else on the tutor list, you guys are great. -- Frank L. "Cranky Frankie" Palmeri From waynejwerner at gmail.com Wed Nov 30 16:03:50 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 30 Nov 2011 09:03:50 -0600 Subject: [Tutor] tkinter message & button questions In-Reply-To: References: Message-ID: On Wed, Nov 30, 2011 at 8:32 AM, Cranky Frankie wrote: > Peter Otten <__peter__ at web.de> wrote: > Peter thanks again. The msg_widget is still resizing vertically > depending on the lenght of the quote, but at least now the horizontal > sizing is staying the same. Ideally the msg_widget would be the *same > size*, no matter what the quote length is, but since this program is > really just a learning exercise and to show database adminstrators a > simple Python GUI application I can live with it. > The whole purpose of the Message widget is that it *does* resize. If you wanted something to be a static size, I think a Label would fit the bill - though I haven't played around enough with that in recent time. > > The syntax you used, like "root.geometry("400x100")", I have not seen > before, and I've done a lot of searching. Again, much of the tkinter > stuff I see seems to be based on Python 2.6. If there is a definitive > book or reference on using tkinter in Python 3.x I'd really like to > know about it. > > That's the great thing about Python - most of the syntax is identical, and there should be only minor differences between Python 2.x and 3.x - especially where Tkinter is concerned. I would go ahead and look at 2.x tutorials/articles for Tkinter and just be aware that you'll encounter some issues (probably mostly dealing with Unicode strings, and occasionally something numeric - based on my experience). With that preparation then you should be able to easily search for answers to the problems you encounter. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Nov 30 17:09:16 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 30 Nov 2011 17:09:16 +0100 Subject: [Tutor] tkinter message & button questions References: Message-ID: Cranky Frankie wrote: > Peter thanks again. The msg_widget is still resizing vertically > depending on the lenght of the quote, but at least now the horizontal > sizing is staying the same. Ideally the msg_widget would be the *same > size*, no matter what the quote length is, but since this program is > really just a learning exercise and to show database adminstrators a > simple Python GUI application I can live with it. Well, you can place() everything yourself: root = Tk() win = Frame(root) win.place(relheight=1, relwidth=1) label_widget = Label(win, text="Welcome to Quote of the Day") label_widget.place(width=300, height=20) msg_widget = Message( win, anchor=NW, justify=LEFT, width=1000, bd=2, bg="white", relief=SOLID, text=choose_quote()) msg_widget.place(width=300, height=50, y=20) next_button = Button(win, text="Next Quote", command=display_quote) next_button.place(y=70) quit_button = Button(win, text="QUIT", fg="red", command=quit) quit_button.place(y=70, x=200) root.geometry("400x100") root.mainloop() The disadvantage of that approach is of course that you have to place everything yourself ;) From alan.gauld at btinternet.com Wed Nov 30 20:22:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 30 Nov 2011 19:22:39 +0000 Subject: [Tutor] tkinter message & button questions In-Reply-To: References: Message-ID: On 30/11/11 14:32, Cranky Frankie wrote: > The syntax you used, like "root.geometry("400x100")", I have not seen > before, and I've done a lot of searching. Again, much of the tkinter > stuff I see seems to be based on Python 2.6. If there is a definitive > book or reference on using tkinter in Python 3.x I'd really like to > know about it. For those times when help() fails to provide enough detail... The definitive reference for Tkinter is usually the Tk documentation. But that is expressed in terms of Tcl rather than Python - although they are trying to address that. But it does require some translation. I usually look here first: http://docs.python.org/py3k/library/tk.html and http://www.pythonware.com/library/tkinter/introduction/index.htm For the Tk docs try: http://www.tcl.tk/man/tcl8.5/TkLib/contents.htm And finally this shows promise but is still under construction : http://www.tkdocs.com/index.html It tries to cover other languages, including Python but its a bit patchy so far... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From stm.at.oc at googlemail.com Wed Nov 30 22:08:52 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Wed, 30 Nov 2011 22:08:52 +0100 Subject: [Tutor] plotting in python Message-ID: Hi there, I have a question regarding plotting with Python. I have the following python script: # coding: utf-8 from pylab import * import numpy filename='ourtest_out.list' fh=open(filename) line=fh.readline() fh.close z=array([ float(val) for val in line.split()[1:] ]) a = numpy.loadtxt(filename,skiprows=3) N=100 t = a[:,0] nu = a[0:,1:N+1] #Conc = a[1:,N+1:] Conc = a[1:,N+1:] levels=arange(-10,1) levels=levels[-3]-levels t=t/360. figure() plot(Conc[0],z) xlabel('C') ylabel('z') #show() savefig('Conc.png') close() #########nu figure() lw = 2.0 #linewidth dpi = 96 levels=arange(-10,1) levels=levels[-3]-levels plot(nu[0],z) xlabel('nu') ylabel('z') savefig('nu.png') close() --------However, once I run the program (run.py) I have error like this: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /Users/?./run.py in () 24 25 figure() ---> 26 plot(Conc[0],z) 27 28 xlabel('C') /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/pyplot.py in plot(*args, **kwargs) 2284 ax.hold(hold) 2285 try: -> 2286 ret = ax.plot(*args, **kwargs) 2287 draw_if_interactive() 2288 finally: /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py in plot(self, *args, **kwargs) 3781 lines = [] 3782 -> 3783 for line in self._get_lines(*args, **kwargs): 3784 self.add_line(line) 3785 lines.append(line) /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py in _grab_next_args(self, *args, **kwargs) 315 return 316 if len(remaining) <= 3: --> 317 for seg in self._plot_args(remaining, kwargs): 318 yield seg 319 return /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py in _plot_args(self, tup, kwargs) 292 x = np.arange(y.shape[0], dtype=float) 293 --> 294 x, y = self._xy_from_xy(x, y) 295 296 if self.command == 'plot': /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py in _xy_from_xy(self, x, y) 232 y = np.atleast_1d(y) 233 if x.shape[0] != y.shape[0]: --> 234 raise ValueError("x and y must have same first dimension") 235 if x.ndim > 2 or y.ndim > 2: 236 raise ValueError("x and y can be no greater than 2-D") ValueError: x and y must have same first dimension -------So, What would you suggest? Thanks in advance, Sue From stm.at.oc at googlemail.com Wed Nov 30 22:32:58 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Wed, 30 Nov 2011 22:32:58 +0100 Subject: [Tutor] Do loop in Python In-Reply-To: <4ED4D77D.4040500@pearwood.info> References: <4ECF7DB5.60305@pearwood.info> <4ED4D77D.4040500@pearwood.info> Message-ID: Yes. Actually, I have changed it to this kine od script: # == model loop == #Optione1 if True: z=zeros( (numlayers,) ) thickness= (thickness*1.0) for l in layers: z = arange ((-thickness - h * l),0,dz) ## z= t -h * l nu = num+ (0.001*exp(-0.005*(z+200.))*dz) #Option2 if False: thickness = range(-200 , 0, 10) # a list from -200 to 0 with step 10 (0, 10, 20, ..., 190, 200) layers = range(1,11) # a list from 1 to 10 for t in thickness: for l in layers: z = arange(( t + h * l ), 0, dz ) #zvalues = arange(-200.,0,dz) nu = num+ (0.001*exp(-0.005*(z+200.))) plot(nu,z) Then it seems it works. it should have a trend to reducing values... - Show quoted text - On Tue, Nov 29, 2011 at 2:00 PM, Steven D'Aprano wrote: > stm atoc wrote: >> >> Thank you so much for your reply. It was very helpful information and >> I used it in order to improve the program.... >> >> Here is the new version of the program: >> >> zvalues = [-200] ?# starting value >> hvalues = [10] ?# starting value >> increments = [1, 1, 1, 1, 1, 1, 1, 1] >> for N in increments: >> ? ? ? h = hvalues[-1] - N >> ? ? ? hvalues.append(h) >> ? ? ? z = zvalues[-1] + h >> ? ? ? zvalues.append(z) >> ? ? ? height = arange((z)*dz,0,dz) >> ? ? ? for z,when in enumerate(height): >> ? ? ? ? ? nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) #turbulence >> diffusivity m**2/s >> ? ? ? ? ? nu.append(num + nuh[z]) > > > > I'm afraid I still don't know what the arange function is. Is that a > function you have written yourself? However, I can see that it doesn't > actually get used! > > You create an arange object, and call it "height". > > ? ?height = arange((z)*dz,0,dz) > > You should insert a print statement after this line to see what value height > is given, and check that it is what you expect it to be. > > Presumably height is some sort of list or sequence of values, because you > next use it in a for-loop: > > ? ?for z,when in enumerate(height): > ? ? ? ?... > > So now we know that z takes on the values 0, 1, 2, 3, ... and when takes on > the values from height, whatever they are. But in the rest of your code, you > don't use when at all: > > ? ? ? ?nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) > > ? ? ? ?nu.append(num + nuh[z]) > > No when, hence the values from height aren't actually used. Strange. > > Also, what are dz and num? You use them both, but I can't see where they are > defined or what value they have. Likewise nuh and nu, although I can guess > they are probably lists because you append to them. > > Because I don't know what values to use, and I don't know what arange is, I > can't run your code to see what it does. So I'm reduced to guessing. > > If I take a wild stab in the dark that dz is a small number, say, 0.01, I > can see what values nuh gets: > > > py> from math import exp > py> dz = 0.01 > py> nuh = [] > py> for z in range(10): > ... ? ? nuh.append(0.001 * exp(-0.005*(z+200.0))*dz) > ... > py> from pprint import pprint > py> pprint(nuh) > [3.6787944117144236e-06, > ?3.6604463480401533e-06, > ?3.6421897957152333e-06, > ?3.624024298324903e-06, > ?3.6059494017307832e-06, > ?3.587964654059516e-06, > ?3.5700696056914737e-06, > ?3.5522638092495153e-06, > ?3.5345468195878014e-06, > ?3.5169181937806692e-06] > > Is that the sort of behaviour you expect for nuh? > > Since the nuh values are changing, num+nuh[z] should also be changing, which > implies nu should be changing. > > Unless num is so large that rounding error wipes out the nuh values. > > > > > -- > Steven > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From norman at khine.net Wed Nov 30 22:34:32 2011 From: norman at khine.net (Norman Khine) Date: Wed, 30 Nov 2011 22:34:32 +0100 Subject: [Tutor] is there a better way to organise this code Message-ID: hello, is there a better way to organise this code or optimise it. http://pastie.org/2944797 thanks norman From waynejwerner at gmail.com Wed Nov 30 23:30:26 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 30 Nov 2011 16:30:26 -0600 Subject: [Tutor] plotting in python In-Reply-To: References: Message-ID: On Wed, Nov 30, 2011 at 3:08 PM, stm atoc wrote: > Hi there, > > I have a question regarding plotting with Python. > > > ValueError: x and y must have same first dimension > > It looks like something is wrong with the data that you're trying to plot. Specifically, the data that you're trying to plot has the wrong dimensions (like it says). An example: # 2d space: x = [(1, 1), (2, 2), (3,3)] y = [(1,1,1), (2,2,2), (3,3,3)] x is a series of points in 2 dimensions, and y is a series in 3. If your data really is supposed to look like that then you'll need to pad or trim the data so you've got the correct dimensions. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Nov 30 23:04:43 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 30 Nov 2011 14:04:43 -0800 Subject: [Tutor] plotting in python In-Reply-To: References: Message-ID: On 11/30/2011 1:08 PM stm atoc said... > Hi there, > > I have a question regarding plotting with Python. > > I have the following python script: > > # coding: utf-8 > from pylab import * > import numpy > > filename='ourtest_out.list' > > fh=open(filename) > line=fh.readline() > fh.close > > z=array([ float(val) for val in line.split()[1:] ]) > > > a = numpy.loadtxt(filename,skiprows=3) > N=100 > t = a[:,0] > nu = a[0:,1:N+1] > #Conc = a[1:,N+1:] > Conc = a[1:,N+1:] > > levels=arange(-10,1) > levels=levels[-3]-levels > t=t/360. > > figure() > plot(Conc[0],z) > > xlabel('C') > ylabel('z') > #show() > savefig('Conc.png') > close() > > #########nu > figure() > lw = 2.0 #linewidth > dpi = 96 > > levels=arange(-10,1) > levels=levels[-3]-levels > plot(nu[0],z) > xlabel('nu') > ylabel('z') > savefig('nu.png') > close() > > > --------However, once I run the program (run.py) > > I have error like this: > > --------------------------------------------------------------------------- > ValueError Traceback (most recent call last) > /Users/?./run.py in() > 24 > 25 figure() > ---> 26 plot(Conc[0],z) > 27 > 28 xlabel('C') > > /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/pyplot.py > in plot(*args, **kwargs) > 2284 ax.hold(hold) > 2285 try: > -> 2286 ret = ax.plot(*args, **kwargs) > 2287 draw_if_interactive() > 2288 finally: > > /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py > in plot(self, *args, **kwargs) > 3781 lines = [] > 3782 > -> 3783 for line in self._get_lines(*args, **kwargs): > 3784 self.add_line(line) > 3785 lines.append(line) > > /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py > in _grab_next_args(self, *args, **kwargs) > 315 return > 316 if len(remaining)<= 3: > --> 317 for seg in self._plot_args(remaining, kwargs): > 318 yield seg > 319 return > > /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py > in _plot_args(self, tup, kwargs) > 292 x = np.arange(y.shape[0], dtype=float) > 293 > --> 294 x, y = self._xy_from_xy(x, y) > 295 > 296 if self.command == 'plot': > > /Library/Frameworks/EPD64.framework/Versions/7.1/lib/python2.7/site-packages/matplotlib/axes.py > in _xy_from_xy(self, x, y) > 232 y = np.atleast_1d(y) > 233 if x.shape[0] != y.shape[0]: > --> 234 raise ValueError("x and y must have same first dimension") > 235 if x.ndim> 2 or y.ndim> 2: > 236 raise ValueError("x and y can be no greater than 2-D") > > ValueError: x and y must have same first dimension > > > -------So, What would you suggest? Looking over the traceback and code, it would appear the error is saying that there is an inconsistency with the arguments expected vs the arguments passed, which appears in this case to relate to ... plot(Conc[0],z) ... which derives its parameters from the two lines ... z=array([ float(val) for val in line.split()[1:] ]) ... and ... a = numpy.loadtxt(filename,skiprows=3) So, I'd conclude that I'd need a better understanding of how to use the functions plot, array and numpy.loadtext. Neither plot nor array are python builtins nor defined within your script, so they're likely brought in from ... from pylab import * ... which is generally not something you want to do except when first starting to experiment and learn a new module, and then I'd keep things to the interactive interpreter for testing and discovery. This form of import is generally thought of as polluting the namespace and may allow library specific names to mask python builtins. For example. suppose a module 'xyz' contains a special 'print' function. Executing 'from xyz import *' would shadow the python builtin print function essentially making it inaccessible. It's possible (although unlikely in the case of pylab specifically) that any python builtins that are used in your script have been replaced with pylab versions. A better technique is to simply import pylab and refer to its functions as pylab.xyz so that no ambiguity is possible. So, read up on pylab, find their support list [1], and follow up there. We focus mainly on getting you far enough along with python basics and generally leave specific library support to the library authors and support groups. HTH Emile [1] start at http://www.scipy.org/Mailing_Lists From waynejwerner at gmail.com Wed Nov 30 23:48:31 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 30 Nov 2011 16:48:31 -0600 Subject: [Tutor] is there a better way to organise this code In-Reply-To: References: Message-ID: On Wed, Nov 30, 2011 at 3:34 PM, Norman Khine wrote: > hello, > > is there a better way to organise this code or optimise it. > > http://pastie.org/2944797 > > After glancing at it the only change that I would recommend (possibly) making is lines 58 and 39 - you can wrap the dictionaries (line line 7) and that will bring all your lines < 80 characters. Other than that it looks perfectly readable. You could add some docstrings for completeness. As far as anything else - is this code too slow? If not, why bother trying to optimise it? Obviously if you were doing something horribly inefficient like a bubble sort (especially considering Python has a built-in sort), then you would want to get rid of that, but I didn't really notice anything. Though now that I took a few more seconds, it does look like you're not using rows, aside from looping over it. If you only care about the values and not the collection as a whole you could (and should) change the list comprehension to a generator expression: >>> [x for x in (1,2,3)] [1, 2, 3] >>> (x for x in (1,2,3)) at 0x01BFB6C0> If you're not familiar with a generators, I highly recommend this set of slides: http://www.dabeaz.com/generators/Generators.pdf HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: