Re: [Tutor] Misunderstanding the Entry Widget
Title: Signature.html On a branch off this thread, I've mentioned a problem with this approach. It seems right, but I haven't bridged it yet. Do you have some simple Tk Python code that shows how to do this? Alan Gauld wrote: "Wayne Watson" wrote Signature.htmlAnother thought occurred to me about this situation. Suppose I have a dialog with two Entry objects in a dialog object called TwoEntries: entry1 = Entry(master, width=10).grid(row=4, column=1) entry2 = Entry(master, width=10).grid(row=5, column=1) and I do not use a StringVar to return the values entered. Is it possible to reach inside TwoEntries, after returning from it, and grab entry1 and 2? It would seem so if the call was dialog=TwoEntries(...). Sure, just use x = dialog.entry1.get() y = dialog.entry2.get() There really is nothing special going on. I have no idea of the history of these variables, but they have very limited descriptions and examples. I assume because they have a very simple and specific purpose. There is probably more on them if you look at the original Tcl/Tk documentation. Remember Tkinter is just a wrapper arpund Tcl/Tkl and Tk has been around for a long time (20 years now) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] memory error
On Fri, Mar 6, 2009 at 5:03 PM, Harris, Sarah L wrote: > fname=filter(isfile, glob.glob('*.zip')) > for fname in fname: > zipnames=filter(isfile, glob.glob('*.zip')) > for zipname in zipnames: > ... It looks you're using an unnecessary extra loop. Aren't the contents of fname similar to zipnames? I tried it with one loop (for zipname in zipnames:) and it worked. P.S. You're at jpl? That's awesome! I was looking at internships they have few days ago. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary to Decimal conversion
You're making it more complicated than it needs to. Also, you first used binnum then binum, and you didn't define binsum. It could easily be done like this: binnum = raw_input("Please enter a binary number: ") decnum = 0 rank = 1 for i in reversed(binnum): decnum += rank * int(i) rank *= 2 Moos ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 61, Issue 32
"WM." wrote From: "Alan Gauld" Pyton's error message told you exactly what you had done wrong although you may not have quite understood it. But do you now see what the error message was telling you when it said: ... Can you understand it clearly enough that when a similar error comes up in future you will know what to look for and where? No, Mr. G., I cannot. OK, Let's revisit it to try and unravel what it is saying. File "C:\Python26\TicTacToeD.py", line 150, in main DisplayBoard(board) File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard print "\n\t", board[1], "|", board[2], "|", board[3] TypeError: 'function' object is unsubscriptable Start at the bottom and work upwards. TypeError: 'function' object is unsubscriptable unsubscriptable means you can't use the [] indexing syntax, it is not supported by the object to which you have applied it And the object to which you applied it is a function. File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard print "\n\t", board[1], "|", board[2], "|", board[3] The thing you subscripted was board. Therefore board must be a function, not something that you can subscript. File "C:\Python26\TicTacToeD.py", line 150, in main DisplayBoard(board) This is where you call DisplayBoard and pass in board as an argument to DisplayBoard. So you need to look at the code in TicTacToeD.py to see how board comes to be a function. There are really only two possibilities: a) Is it a function to begin with? ie do you have code that looks like def board(...): or b) Did you assign board to a function? ie is there a line like board = In your case it was 'b', an assignment. Now at this stage we have reached the end of what the Python error message is telling us. We need to do some actual debugging to find out what we assigned to board. Was it a function? Should it have been? And here experience comes into play, and we might either guess that we intended to call the function rather than assign it - ie we need the parens at the end. OR we check the source code we are copying to see whether we made a mistake in typing it in. (Which was the case here) If that had not yielded any joy we would need to get into deeper debugging and trace back the source of whatever we assigned to board. Maybe using print type() to check at what stage our errant value became a function. But in this case it was not necessary. The faulty line was board = NewBoard<<<--This line And NewBoard we could tell (because it was defined as such in our code) was a function, so we almost certainly should have added parens. board = NewBoard() 80% of this was deductable from the Python error message once you get used to reading them carefully and with some experience. That is why it's important not just to fix the problems but to understand what Python was telling you for future reference. If you look back the thread John Fouhy actually told you that you probably missed some parens within 2 hours of your original post: He just got the location wrong... --- something that doesn't support them. It's telling you that 'board' is a function (as opposed to a list or a dict, for example) and functions don't support []. Possibly you're meant to call board: print "\n\t", board(1), "|", board(2), "|", board(3) Or, alternatively, you may have assigned to it by mistake somewhere. --- But it took Brett to point out where you needed to apply the parens! Which he did by locating the original source code you had copied. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] compare csv file values against a python dictionary and create a new list from this.
ski wrote: hello, i have created this function that compares the values of a csv file against a dictionary, you can see the code, here http://paste.lisp.org/display/76705 the affiliations list has 130 items. is there a better way to build the 'items' list? Please define "better". If you mean less code, create a list of just the variable values: values = [['AAC', 'Association of Airline Cons.'], ['AALA', 'Adv. Activity Licence. Auth.'], ...] then provide some code to read the list and construct the dicts. In the above I assume all is_selected are False so there is no need to include that. But why a list of dictionaries? Would not the values list be sufficient? Or possibly even better define a class (Cls) and make each list entry an instance of the class. Then values = [Cls('AAC', 'Association of Airline Cons.'), Cls('AALA', 'Adv. Activity Licence. Auth.'), ...] That I think would be far more useful in the long run. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary to Decimal conversion
Chris Castillo wrote: I am having some difficulties in producing the correct code for a simple binary to decimal conversion program. The arithmetic I want to use is the doubling method - so if I wanted to get the decimal equivalent of 1001, I would start with multiplying 0 * 2 and adding the left most digit. I would then take the sum of 1 and multiply it by 2 and add the next digit to that product and so on and so forth until I come to an end sum of 9. I seem to come up with something like this: binnum = raw_input("Please enter a binary number: ") for i in range(0, len(binum), 1): item = "0" if i < len(binum) - 1: item = binum[i + 1] binsum = binsum * int(item) * 2 + binsum + int(binum[i]) print "\nThe binary number ", binum, " you entered converts to", binsum, " in decimal." Having said that I will point out 1 - to access elements of a sequence you may write: for item in binnum: 2 - the first element of binnum is binnum[0]. Your code starts by accessing the 2nd element. 3- you use binsum before assigning anything to it. That is bound to raise a Name error. 4 - I don't understand binsum = binsum * int(item) * 2 + binsum + int(binum[i]) That does not agree with your verbal algorithm. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary to Decimal conversion
Chris Castillo wrote: I am having some difficulties in producing the correct code for a simple binary to decimal conversion program. The arithmetic I want to use is the doubling method - so if I wanted to get the decimal equivalent of 1001, I would start with multiplying 0 * 2 and adding the left most digit. I would then take the sum of 1 and multiply it by 2 and add the next digit to that product and so on and so forth until I come to an end sum of 9. I seem to come up with something like this: binnum = raw_input("Please enter a binary number: ") for i in range(0, len(binum), 1): item = "0" if i < len(binum) - 1: item = binum[i + 1] binsum = binsum * int(item) * 2 + binsum + int(binum[i]) print "\nThe binary number ", binum, " you entered converts to", binsum, " in decimal." I can't really figure out what is going wrong here. I don't see anything going wrong. All I see is some Python code. Would you be kind enough to tell us why you think something is going wrong. If there is an error post the traceback If you get a result you did not expect tell us what the input was, the desired result and the actual result. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Binary to Decimal conversion
I am having some difficulties in producing the correct code for a simple binary to decimal conversion program. The arithmetic I want to use is the doubling method - so if I wanted to get the decimal equivalent of 1001, I would start with multiplying 0 * 2 and adding the left most digit. I would then take the sum of 1 and multiply it by 2 and add the next digit to that product and so on and so forth until I come to an end sum of 9. I seem to come up with something like this: binnum = raw_input("Please enter a binary number: ") for i in range(0, len(binum), 1): item = "0" if i < len(binum) - 1: item = binum[i + 1] binsum = binsum * int(item) * 2 + binsum + int(binum[i]) print "\nThe binary number ", binum, " you entered converts to", binsum, " in decimal." I can't really figure out what is going wrong here. Please help me - this has been driving me insane. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comparing lists of dictionaries
On Mon, Mar 9, 2009 at 5:56 PM, ski wrote: > i was looking to list all the items in list1 that are not in list2 based on > the key['id] and key['affiliation'] respectively. OK. Generally, when you want to test for membership, a set or dict is a good choice. In this case, I would first make a set of the keys from list2: In [6]: list2 = [{'affiliation': 'ABTA', 'affiliation_no': u'G3903'}, {'affiliation': 'AAC', 'affiliation_no': u'none'}] In [8]: list2keys = set(item['affiliation'] for item in list2) In [9]: list2keys Out[9]: set(['AAC', 'ABTA']) Now you can filter list1 items by whether their id is in list2keys: In [10]: list1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] In [11]: for item in list1: : if item['id'] not in list2keys: : print item {'title': 'Adv. Activity Licence. Auth.', 'id': 'AALA', 'is_selected': False} {'title': 'Association of British Prof. Conf. Organisation', 'id': 'ABPCO', 'is_selected': False} {'title': 'Association of Bonded Travel Organisation Trust', 'id': 'ABTOT', 'is_selected': False} {'title': 'Association of Europe Rail Agents', 'id': 'AERA', 'is_selected': False} Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 61, Issue 32
'Enter word:') ??? word = word1.lower() ??? sig = code(word) ??? i = 1 ??? if sig in wordList: ??? print "Anagrams:" ??? while i <= len(wordList):? # when the sig of the inputed word is in the word list, ??? if sig == wordList[i] ??? print wordList[i-1]? # the corresponding words are printed ??? i += 2 # then adds two because codes are every other entry ??? else: ??? print "No anagrams" ??? choice = raw_input("Continue? (yes/no)") ??? if choice == 'y' or choice == 'yes': ??? continue ??? else: ??? break ??? ??? ??? ??? ??? ??? ? ??? ??? ??? -- next part -- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20090309/54781b33/attachment-0001.htm> -- Message: 4 Date: Mon, 9 Mar 2009 08:39:44 - From: "Alan Gauld" Subject: Re: [Tutor] UNSUBSCRIPTABLE? To: tutor@python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "WM." wrote Well, Mr. Wilkins takes the biscuit. He found where I did not enter a pair of parens.() But do you understand *why* you got the error and what it was telling you? Pyton's error message told you exactly what you had done wrong although you may not have quite understood it. But do you now see what the error message was telling you when it said: -- File "C:\Python26\TicTacToeD.py", line 150, in main DisplayBoard(board) File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard print "\n\t", board[1], "|", board[2], "|", board[3] TypeError: 'function' object is unsubscriptable -- Can you understand it clearly enough that when a similar error comes up in future you will know what to look for and where? No, Mr. G., I cannot. My approach has been to key in most of Dawson's programs, to get accustomed to the jargon and to get used to some keys that I didn't know were on the keyboard. My long term memory seems to be pretty shot and the stuff is not soaking in. I have found your tutorial, and some others in the Python B/G file of interest, but not retainable. Two O'Reilly books are worthless to me. Dawson's book is very clear; being half way through it, I should know a great deal more than I do. Oh, well, one should not bring a cap-pistol to a knife fight, nor a leaky brain to an academic task. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Newby Linux Program review + help with regular expressions
"David" wrote and compare with others, ask for help etc. Am I using the subrocess module too much because I am comfortable with the commands? Should I just write this type of program in bash. Personally I'd use bash for this kind of thing. If you wanted to post process the report then I'd use Python. You could do a faitr bit with Python commands, especially the functions in the os module, but since the scripts already exist you might as well use them. One thing though, you could use triple quoted strings and string formatting more: fobj.write(nick) fobj.write(" \n") fobj.write(make) fobj.write(" \n") fobj.write(model) fobj.write(" \n") fobj.close()Could be: fobj.write("%s\n%s\n%s\n" % (nick,make,model) ) #This is a comment with 5 spaces you can use the lstrip() methjod of a string: if line.lstrip().startswith('#'): isComment = True HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] i can only write one line of code on python shell helpplease ?
"mustafa akkoc" wrote - In python shell , i can only write one line of code when I go to next line this sign appears >>> how can write the code like in script mode and run You can't. Shell mode means you are entering code directly into the interpreter so it executes the code line by line (or as a block if it is a block, like a for loop say) If you are using IDLE (or Pyhonwin) you can open a new window which will alow you to create a new Python script and run that from within IDLE. And you can keep entering lines in the shell window, the results from previous lines are stored as they would be in a normal program. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comparing lists of dictionaries
i was looking to list all the items in list1 that are not in list2 based on the key['id] and key['affiliation'] respectively. thanks Kent Johnson wrote: On Mon, Mar 9, 2009 at 4:20 PM, ski wrote: what am i missing here, i would like to get a list of the diff between list1 and list2 What do you mean by diff in this case? Items in one list and not in the other? Items that are in both lists but with different elements? What elements do you want to use for the comparison? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] comparing lists of dictionaries
On Mon, Mar 9, 2009 at 4:20 PM, ski wrote: > what am i missing here, i would like to get a list of the diff between list1 > and list2 What do you mean by diff in this case? Items in one list and not in the other? Items that are in both lists but with different elements? What elements do you want to use for the comparison? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] comparing lists of dictionaries
hello again, i am trying to get my head around this but without success, here is what i have so far: >>> list1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] >>> list2 = [{'affiliation': 'ABTA', 'affiliation_no': u'G3903'}, {'affiliation': 'AAC', 'affiliation_no': u'none'}] >>> for dic1 in list1: ... for dic2 in list2: ... diff = [k for k, v in dic1.iteritems() if v != dic2['affiliation']] ... print k, v ... is_selected False is_selected False is_selected False is_selected True is_selected False is_selected False >>> what am i missing here, i would like to get a list of the diff between list1 and list2 again thanks in advance. norman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM
Just glancing at your program, I would guess that you have a ":" where you want a "]" on the line below. prod = prod * letter_to_prime[word_list[j] [i]: HTH, Chris jessica cruz Sent by: tutor-bounces+christopher.henk=allisontransmission@python.org 03/09/2009 02:38 PM To Tutor@python.org cc Subject [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM I made this program but it says that there is an error and I have a hard time trying to solve the problem with program. Here is the program: #this reads all of the words in the file into a list infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') wdcount = int(infile.readline()) #first item is count of all the words word_list = infile.readlines() #print them out from the internal list i = 0 while i < wdcount: print word_list[i], i = i + 1 #map of alphabet to prime numbers with respect to frecuency #more frequent the letter the smaller the assigment prime letter_to_prime = { 'a':7, 'b':59, 'c':29, 'd':31, 'e':2, 'f':67, 'g':41, 'h':53, 'i':3, 'j':97, 'k':73, 'l':23, 'm':47, 'n':13, 'o':19, 'p':43, 'q':101, 'r':11, 's':5, 't':17, 'u':37, 'v':71, 'w':79, 'x':89, 'y':61, 'z':83}, j = 0 while j < wdcount: print word_list [j], prod = 1 i = 0 while i < len(word_list[j])-2: prod = prod * letter_to_prime[word_list[j] [i]: i = i + 1 print prod (right here is where it says that there's an error I try to fix it ) j = j =1 # code that will be compared will be a histogram type code with frequency # characters def code(w): hist = [] chars = list(w) chars.sort() for letter in chars: if not letter in hist: # when the letter is not already in hist, hist.extend([letter, str(w.count(letter))]) # its added to hist along with its freq. else: continue coding = "".join(hist) # then they are joined as one string return coding # new list is made with words in word_list followed by its code for word in word_list: wordList.append(word) wordList.append(code(word[:(len(word)-2)])) while True: word1 = raw_input('Enter word:') word = word1.lower() sig = code(word) i = 1 if sig in wordList: print "Anagrams:" while i <= len(wordList): # when the sig of the inputed word is in the word list, if sig == wordList[i]: print wordList[i-1] # the corresponding words are printed i += 2 # then adds two because codes are every other entry else: print "No anagrams" choice = raw_input("Continue? (yes/no)") if choice == 'y' or choice == 'yes': continue else: break I don't know how to figure out the error since the only message that I get is that "there's an error: invalid syntax" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Newby Linux Program review + help with regular expressions
This program generates a report of a Linux System and some important .conf files. The goal is for users to be able to post their information and compare with others, ask for help etc. Am I using the subrocess module too much because I am comfortable with the commands? Should I just write this type of program in bash. I am trying to get rid of all the comments generated in the report. I got rid of blank lines and lines starting with #. But can not figure out how the get rid of a line like; #This is a comment with 5 spaces I never programed before so everything is new to me. Here is my code; http://asterisklinks.com/wiki/doku.php?id=wiki:gentoo_report The report it generates is at the bottom. I didn't want to post it all here. Thanks, -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM
On Mon, Mar 9, 2009 at 10:38 AM, jessica cruz wrote: > I made this program but it says that there is an error and I have a hard > time trying to solve the problem with program. > : > I don't know how to figure out the error since the only message that I get > is that "there's an error: invalid syntax" hi jessica, in order for us to help you more effectively, you'll need to cut-n-paste the entire error traceback as well as tell us what version of Python you're using including what platform (i.e., mac, PC, etc.) also, keep in mind that we aren't able to do your homework for you but would be able to help out with small difficulties you face on the way to your own solution(s)! thanks, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] HELP ON A ANAGRAM PYTHON PROGRAM
On Mon, Mar 9, 2009 at 1:38 PM, jessica cruz wrote: > I don't know how to figure out the error since the only message that I get > is that "there's an error: invalid syntax" Please copy & paste the whole error message including the traceback so we know where the error is. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] HELP ON A ANAGRAM PYTHON PROGRAM
I made this program but it says that there is an error and I have a hard time trying to solve the problem with program. Here is the program: #this reads all of the words in the file into a list infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') wdcount = int(infile.readline()) #first item is count of all the words word_list = infile.readlines() #print them out from the internal list i = 0 while i < wdcount: print word_list[i], i = i + 1 #map of alphabet to prime numbers with respect to frecuency #more frequent the letter the smaller the assigment prime letter_to_prime = { 'a':7, 'b':59, 'c':29, 'd':31, 'e':2, 'f':67, 'g':41, 'h':53, 'i':3, 'j':97, 'k':73, 'l':23, 'm':47, 'n':13, 'o':19, 'p':43, 'q':101, 'r':11, 's':5, 't':17, 'u':37, 'v':71, 'w':79, 'x':89, 'y':61, 'z':83}, j = 0 while j < wdcount: print word_list [j], prod = 1 i = 0 while i < len(word_list[j])-2: prod = prod * letter_to_prime[word_list[j] [i]: i = i + 1 print prod (right here is where it says that there's an error I try to fix it ) j = j =1 # code that will be compared will be a histogram type code with frequency # characters def code(w): hist = [] chars = list(w) chars.sort() for letter in chars: if not letter in hist: # when the letter is not already in hist, hist.extend([letter, str(w.count(letter))]) # its added to hist along with its freq. else: continue coding = "".join(hist) # then they are joined as one string return coding # new list is made with words in word_list followed by its code for word in word_list: wordList.append(word) wordList.append(code(word[:(len(word)-2)])) while True: word1 = raw_input('Enter word:') word = word1.lower() sig = code(word) i = 1 if sig in wordList: print "Anagrams:" while i <= len(wordList): # when the sig of the inputed word is in the word list, if sig == wordList[i]: print wordList[i-1] # the corresponding words are printed i += 2 # then adds two because codes are every other entry else: print "No anagrams" choice = raw_input("Continue? (yes/no)") if choice == 'y' or choice == 'yes': continue else: break I don't know how to figure out the error since the only message that I get is that "there's an error: invalid syntax" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Misunderstanding the Entry Widget
Title: Signature.html I had commented out # entry = Entry(master, width=10, textvariable=self.slowdownVar).grid(row=4, column=1), which had worked fine previously to my changes. I added your two statements after remarking entry = Entry(master, width=10).grid(row=4, column=1) IDLE & the Command prompt window produced, which was really what I was showing in the image that I removed: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python25\Lib\lib-tk\Tkinter.py", line 1403, in __call__ return self.func(*args) File "C:\Sandia_Meteors\Sentinel_Development\Development_Sentuser-Utilities\sentuser\sentuserNC25-Dev5.py", line 579, in OperationalSettings dialog = OperationalSettingsDialog( self.master, set_loc_dict ) File "C:\Sandia_Meteors\Sentinel_Development\Development_Sentuser-Utilities\sentuser\sentuserNC25-Dev5.py", line 84, in __init__ tkSimpleDialog.Dialog.__init__(self, parent) File "C:\Python25\lib\lib-tk\tkSimpleDialog.py", line 64, in __init__ self.initial_focus = self.body(body) File "C:\Sandia_Meteors\Sentinel_Development\Development_Sentuser-Utilities\sentuser\sentuserNC25-Dev5.py", line 115, in body entry.insert(0,self.slowdown) AttributeError: OperationalSettingsDialog instance has no attribute 'slowdown' Kent Johnson wrote: On Mon, Mar 9, 2009 at 8:30 AM, Wayne Watson wrote: entry = Entry(master, width=10).grid(row=4, column=1) You have to write this as entry = Entry(master, width=10) entry.grid(row=4, column=1) The grid() method returns None, that is why entry is None. Kent -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] creating a list of all imported modules
Hello, how do I create a list of all modules imported by my module/script? I am looking for something like %who in Ipython. Thanks for your help in advance. Regards, Timmie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] compare csv file values against a python dictionary and create a new list from this.
hello, i have created this function that compares the values of a csv file against a dictionary, you can see the code, here http://paste.lisp.org/display/76705 the affiliations list has 130 items. is there a better way to build the 'items' list? thanks norman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating new dictionary based on membership testing
thank you all, great feedback. Sander Sweers wrote: 2009/3/9 A.T.Hofkamp : You can do something like [d for d in d1 if d['is_selected'] == False] to get your dicts. If 'is_selected' is not always present, it gets a bit more complicated, I'll leave that as an exercise for the interested reader :) You would use d.get('is_selected', False) == False. If nothing is found then .get() will return False instead of None. Greets Sander ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating new dictionary based on membership testing
On Mon, Mar 9, 2009 at 10:28 AM, ski wrote: > hello, > > i have this list which contains a number of dictionaries. > d1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] > > what would be the correct way to create a new list with the dictionaries but > only for dictionaries with key > > 'is_selected': False > > here is what I have tried, so far, perhaps there is a better and less error > prone method: > d2 = [] for x in d1: > ... if False in x.values(): > ... d2.append(x) This doesn't take advantage of dict lookup and it doesn't do exactly what you asked; it will exclude dicts having any False value, not just for is_selected. Better would be d2 = [] for x in d1: if x['is_selected'] != False: d2.append(x) This can be further simplified; you probably can just test x['is_selected'] without comparing to False, and you can use a list comprehension to simplify the structure: d2 = [ x for x in d1 if x['is_selected'] ] Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating new dictionary based on membership testing
2009/3/9 A.T.Hofkamp : > You can do something like > [d for d in d1 if d['is_selected'] == False] > to get your dicts. > > If 'is_selected' is not always present, it gets a bit more complicated, I'll > leave that as an exercise for the interested reader :) You would use d.get('is_selected', False) == False. If nothing is found then .get() will return False instead of None. Greets Sander ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating new dictionary based on membership testing
ski wrote: hello, i have this list which contains a number of dictionaries. >>>d1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] what would be the correct way to create a new list with the dictionaries but only for dictionaries with key 'is_selected': False here is what I have tried, so far, perhaps there is a better and less error prone method: >>> d2 = [] >>> for x in d1: ... if False in x.values(): ... d2.append(x) This code is wrong, x.values() gives a list of values in the dictionary x, and if 'False' is in it, you append the dict. You never check for the key. Thus d1 = [ {'id':False} ] would also be copied. Also, if you have a dict, and you know which key to use, use that key!! Key-lookup in a dict is very much faster than a linear search in a list like x.values(). You can do something like [d for d in d1 if d['is_selected'] == False] to get your dicts. If 'is_selected' is not always present, it gets a bit more complicated, I'll leave that as an exercise for the interested reader :) Sincerely, Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] i can only write one line of code on python shell help please ?
mustafa akkoc wrote: > Hello , > > - In python shell , i can only write one line of code when I go to > next line this sign appears >>> how can write the code like in > script mode and run > > thanks > -- > Mustafa Akkoc > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > This should help; http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ -- powered by Gentoo/GNU Linux http://linuxcrazy.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] creating new dictionary based on membership testing
hello, i have this list which contains a number of dictionaries. >>>d1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] what would be the correct way to create a new list with the dictionaries but only for dictionaries with key 'is_selected': False here is what I have tried, so far, perhaps there is a better and less error prone method: >>> d2 = [] >>> for x in d1: ... if False in x.values(): ... d2.append(x) ... >>> d2 [{'is_selected': False, 'id': 'AAC', 'title': 'Association of Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 'title': 'Association of British Prof. Conf. Organisation'}, {'is_selected': False, 'id': 'ABTOT', 'title': 'Association of Bonded Travel Organisation Trust'}, {'is_selected': False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}] Thank you Norman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Misunderstanding the Entry Widget
Title: Signature.html Very good. Thanks. (I posted this about 20 hours ago with an image of my screen output. It appears it's waiting for moderator approval, so I'm posting it again w/o the image. Maybe the image will show up later. I think some progress can be made with out it. ) Well, the idea of using Entry1,2 logic hit a snag. First, the program has an oddity that I do not understand. Here's the problem area. See the highlighted code stuff in purple and bold at the bottom. Above that code, it's forming buttons and so on with no return object from anywhere, then "entry = Entry(master, width=10, ..." appears. I put some debug code in there, and ended it wih a return of entry before 20-30 lines of code using Label, etc. that use no assignment to any object. After that is the original return entry. It's puzzling why it returns just entry. I suspect that should cause the return to be a OperationalSettingsDialog object; however, when I print the object and its type, they are None, and type 'NoneType'. REMOVED IMAGE HERE. It shows the None-NoneType msg and other Python msgs. class OperationalSettingsDialog(tkSimpleDialog.Dialog): def __init__(self, parent, sdict): self.sdict = sdict print "Set OSDiag sdict" print tkSimpleDialog.Dialog.__init__(self, parent) def body(self,master): self.title("Operational Settings") print "body from OSDialog, self =", self, "type =", type(self) self.colorVar = IntVar() Radiobutton( master, text="Gray Scale", value=1, variable=self.colorVar).grid(row=0, sticky=W) Radiobutton( master, text="Pseudo Color", value=2, variable=self.colorVar).grid(row=1, sticky=W) self.colorVar.set( self.sdict["color"] ) self.post_event_stackVar = IntVar() Checkbutton( master, text="Make long exposure after each event", variable=self.post_event_stackVar).grid(row=2, sticky=W) self.post_event_stackVar.set( self.sdict["post_event_stack"] ) self.show_real_timeVar = IntVar() Checkbutton( master, text="Show event as it is being received", variable=self.show_real_timeVar).grid(row=3, sticky=W) self.show_real_timeVar.set( self.sdict["show_real_time"] ) Label( master, text="Playback Slowdown: ").grid(row=4, stick=W) self.slowdownVar = StringVar() # entry = Entry(master, width=10, textvariable=self.slowdownVar).grid(row=4, column=1) entry = Entry(master, width=10).grid(row=4, column=1) print "entry, entry type:", entry,type(entry) entry.insert(0,self.slowdown) slowdown = entry print "holly cow: ",slowdown #self.slowdownVar.set( "%d" % self.sdict["slowdown"] ) return entry Alan Gauld wrote: "Alan Gauld" wrote Yep, when I bowed of programming long ago, I had Ousterhout's It was a good book in its day but is now well overdue an update. And lo and behold, listed on Amazon is the 2nd edition due in August 2009! How's that for service :-) BTW I also noticed that there is also now an O'Reilly pocket reference which might be even more useful to Python Tkinter users than the Nutshell - smaller and cheaper and even more terse! Although it doesn't appear to cover Tix... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) “In mathematics you don't understand things. You just get used to them.” -- John Von Neumann (P.S. The same is true in life.) Web Page:___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] i can only write one line of code on python shell help please ?
Hello , - In python shell , i can only write one line of code when I go to next line this sign appears >>> how can write the code like in script mode and run thanks -- Mustafa Akkoc ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] if inside if help python
> I have question if we make if statement inside if like cprogramming below > how to do in python Indentation is the key here. It is very simple. x=1 y=2 if x == 1: print "inside first if" if x == 2: print "inside second if" -- Senthil ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] if inside if help python
I have question if we make if statement inside if like cprogramming below how to do in python int x-1 , y=2; if (x==1) { printf(" inside first if "); if (y==2) { printf ("inside second if "); } } -- Mustafa Akkoc ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Excel addin in Python
Dear All, I have created an excel addin in python; everything is working pretty fine when I execute the python file, addin is getting added and I am able to use it fine. But I want to distribute this addin to users so I used py2exe to convert it in to an exe so far so good I am able to create exe but when I run this exe it works fine and say registering excel addin but I am not able to see the addin in excel but the entry in registry is present. Any pointers on what may be going wrong?? -- Cheers, Vishwajeet http://www.singhvishwajeet.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with an anagram program
"jessica cruz" wrote I just started learning python an I'm currently working on this program. The purpose of this program is to read a string of letters from user input and print out all the words which are anagrams of the input string. Where you define an anagram to be a word that is in wordlist I assume? it says that there is an error "invalid syntax" but I can't figure out where. Always send us the full error message, it usually tells us where to look, which is easier than reading the full program! #this reads all of the words in the file into a list infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') wdcount = int(infile.readline()) #first item is count of all the words You do not use this, why bother? word_list = infile.readlines() wordList = [] # code that will be compared will be a histogram type code with frequency # characters def code(w): hist = [] chars = list(w) chars.sort() for letter in chars: if not letter in hist: # when the letter is not already in hist, hist.extend([letter, str(w.count(letter))]) # its added to hist along with its freq. else: continue coding = "".join(hist) # then they are joined as one string return coding # new list is made with words in word_list followed by its code for word in word_list: wordList.append(word) wordList.append(code(word[:(len(word)-2)])) word[:len(word)-2] could be written much more clearly as word[:-2] while True: word1 = raw_input('Enter word:') word = word1.lower() sig = code(word) i = 1 if sig in wordList: print "Anagrams:" while i <= len(wordList): # when the sig of the inputed word is in the word list, if sig == wordList[i] This looks like the syntax error - no colon. I stopped here. I think there are easier ways to do this! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Long list error
"William Stephens" wrote I was working on a sieve of eratosthenes and ran into an error I don't understand. >>> size = 100 >>> l = [0,1]*(size/2) OverflowError: cannot fit 'long' into an index-sized integer Is there a type or something that I can do to prevent this error? The problem is not really to do with the type, despite the error. You are multiplying the list contents by 5 billion. This will create a list with 10 billion entries. Python cannot handle lists of that length. BUT, I doubt if your PC can even if Python could. Does your PC really have around 40G of Memory? I on the wrong track for such large primes? I think so. Your PC does not have infinitely large memory. You need to find an algorithm that keeps the data within the limits of your hardware. (Just be glad you don't have a ZX81 with only 1K of RAM...) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ Thanks, William Stephens ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] probelm pyhton shell doesnt open help please
"mustafa akkoc" wrote it gives this message socket error This used to happen in older versions of IDLE. What version of Python are you using? If possible upgrade to v2.5 or later. If not you probably need to tweak your firewall settings to open a particular port - but I can't recall which one! Or to allow IDLE to send/receive without hindrance. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem with an anagram program
Please next time, if possible, add the complete error message you get. In this case, it tells us that the error is in this line: if sig == wordList[i] You forgot the : at the end of this line (also, the next lines are not indented extra, as they should). On Mon, Mar 9, 2009 at 9:28 AM, jessica cruz wrote: > I just started learning python an I'm currently working on this program. The > purpose of this program is to read a string of letters from user input and > print out all the words which are anagrams of the input string. This is what > I have and when I try to run the program it says that there is an error > "invalid syntax" but I can't figure out where. > > > > > #this reads all of the words in the file into a list > infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') > wdcount = int(infile.readline()) #first item is count of all the words > word_list = infile.readlines() > wordList = [] > > # code that will be compared will be a histogram type code with frequency > # characters > def code(w): > hist = [] > chars = list(w) > chars.sort() > for letter in chars: > if not letter in hist: # when the letter is not already in hist, > hist.extend([letter, str(w.count(letter))]) # its added to hist > along with its freq. > else: > continue > coding = "".join(hist) # then they are joined as one string > return coding > > > > > # new list is made with words in word_list followed by its code > for word in word_list: > wordList.append(word) > wordList.append(code(word[:(len(word)-2)])) > > > while True: > word1 = raw_input('Enter word:') > word = word1.lower() > sig = code(word) > i = 1 > if sig in wordList: > print "Anagrams:" > while i <= len(wordList): # when the sig of the inputed word is in > the word list, > if sig == wordList[i] > print wordList[i-1] # the corresponding words are printed > i += 2 # then adds two because codes are every other entry > else: > print "No anagrams" > choice = raw_input("Continue? (yes/no)") > if choice == 'y' or choice == 'yes': > continue > else: > break -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] UNSUBSCRIPTABLE?
"WM." wrote Well, Mr. Wilkins takes the biscuit. He found where I did not enter a pair of parens.() But do you understand *why* you got the error and what it was telling you? Pyton's error message told you exactly what you had done wrong although you may not have quite understood it. But do you now see what the error message was telling you when it said: -- File "C:\Python26\TicTacToeD.py", line 150, in main DisplayBoard(board) File "C:\Python26\TicTacToeD.py", line 68, in DisplayBoard print "\n\t", board[1], "|", board[2], "|", board[3] TypeError: 'function' object is unsubscriptable -- Can you understand it clearly enough that when a similar error comes up in future you will know what to look for and where? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem with an anagram program
I just started learning python an I'm currently working on this program. The purpose of this program is to read a string of letters from user input and print out all the words which are anagrams of the input string. This is what I have and when I try to run the program it says that there is an error "invalid syntax" but I can't figure out where. #this reads all of the words in the file into a list infile = open('/afs/cats/courses/cmps012a-cm/pa1/wordList.txt') wdcount = int(infile.readline()) #first item is count of all the words word_list = infile.readlines() wordList = [] # code that will be compared will be a histogram type code with frequency # characters def code(w): hist = [] chars = list(w) chars.sort() for letter in chars: if not letter in hist: # when the letter is not already in hist, hist.extend([letter, str(w.count(letter))]) # its added to hist along with its freq. else: continue coding = "".join(hist) # then they are joined as one string return coding # new list is made with words in word_list followed by its code for word in word_list: wordList.append(word) wordList.append(code(word[:(len(word)-2)])) while True: word1 = raw_input('Enter word:') word = word1.lower() sig = code(word) i = 1 if sig in wordList: print "Anagrams:" while i <= len(wordList): # when the sig of the inputed word is in the word list, if sig == wordList[i] print wordList[i-1] # the corresponding words are printed i += 2 # then adds two because codes are every other entry else: print "No anagrams" choice = raw_input("Continue? (yes/no)") if choice == 'y' or choice == 'yes': continue else: break ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor