[Tutor] Algorithm
Hello, The problem that I am having is writing an algorithm for finding all the possible words from a given word. For example: python from "python" you can make the words pot, top, hop, not etc. There are few examples for making anagrams for a word, but only the whole word. I have tried unsuccessfully to modify some of these to suit my purpose. Also on the web there are numerous sites where you can type in a word and it will give you a list of all the words that could be made from it. How would I go about this in python? thanx, kreglet -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25107922.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
Alan, Thanks for the reply. This is not homework, it is a hobby. I am 44 years old. I was using Visual Basic, but recently decided to switch to Linux and have no intentions of going back to windows. Python seems like a good computer language. I read somewhere the the best way to learn it was to pick a project and start programming. Since one of my other hobbies is word games and Linux is severely lacking in this area I decided to write a game similar to Text Twist in windows for my first project. The game I am writing has a graphical front end using GTK and the code so far is long and in more than one file (to keep the gui code seperate). I will gladly email you the whole thing to you if you like. In my research, I looked at examples of permutations, lists, sets, and most recently dictionaries which I have the feeling is the solution. Permutation looked good, but I am an amateur programer and couldn't quite grasp the concepts from the examples I found. Dictionaries hold promise as it can be used to get a count of the letters in words. from operator import itemgetter def countletters(word): lettercount = {} for letter in word: lettercount[letter] =lettercount.get(letter,0) + 1 print sorted(lettercount.iteritems(), key=itemgetter(1)) countletters("batty") [('a', 1), ('y', 1), ('b', 1), ('t', 2)] countletters("bat") [('a', 1), ('b', 1), ('t', 1)] countletters("bats") [('a', 1), ('b', 1), ('s', 1), ('t', 1)] bat is in batty. bats is not. I have a list of words in wordlist.txt. I can write a loop the do the letter counts for each word, but I can't figure out how to compare them. thanx, kreglet Alan Gauld wrote: > > > "kreglet" wrote > >> The problem that I am having is writing an algorithm for finding all the >> possible words from a given word. For example: python > > This sounds a lot like a homework. > We don't give direct help on homeworks but will try to point you > in the right direction. It helps if you tell/show us what you've tried > and where you are stuck. > > How do you think it should work? > Can you think of a systematic approach using pen and paper? > Can you program that? > Does it work? What is wrong? > > Hint: start with a small word that you can check for correctness. > Also test for things like double letters, > eg see. - is ese the same as ese? (the e's are swapped, honest!...) > > > HTH, > > -- > Alan Gauld > 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 > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25109886.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
Wayne, The reason I used print sorted is that using just print throws a syntax error: print (lettercount.iteritems(), key=itemgetter(1)) ---> error print lettercount.iteritems(), key=itemgetter(1) ---> error print sorted(lettercount.iteritems(), key=itemgetter(1)) ---> works I don't know why. Seems to me that any of the above should work. mainword = countletters('batty') cmpword = countletters('bat') myfunc(cmpword, mainword) Generates error: Traceback (most recent call last): File "/home/kreglet/bin/test.py", line 23, in myfunc(cmpword, mainword) File "/home/kreglet/bin/test.py", line 13, in myfunc for letter in cmpword: TypeError: 'NoneType' object is not iterable mainword = countletters('batty') print mainword returns None cmpword = countletters('bat') print cmpword returns None Both mainword and cmpword are passed to the function but since the values of each are None the function doesn't work. Is this correct? thanx, kreglet Wayne-68 wrote: > > On Sun, Aug 23, 2009 at 10:01 PM, kreglet wrote: > > I would actually not bother sorting your return from countletters - keep > it > a dictionary. > > Then you can compare like this: > > mainword = countletters('batty') > cmpword = countletters('bat') > > def myfunc(cmpword, mainword): > for letter in cmpword: > if mainword.gets(letter): > if cmpword[letter] >mainword[letter]: > return False > else: > return False > > I think that should work. First you're looping over each letter in > cmpword. > Because mainword is also a dictionary the order isn't terribly important. > Then you check if the letter is in mainword. If it's not, obviously > cmpword > isn't in mainword, so return False. If the letter is, compare the counts. > If > cmpword has more letters than mainword, it's not in the word so again > return > False. > > HTH, > Wayne > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25118434.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
Hello Mac, Thanks for the tip. I was aware of an and considered using it. I decided not to use it unless I have no other choice. Although it does exactly what I am after: a) I don't want to use any dependencies other than Python's built in modules b) You hit it right in the nose when you said: "doing things by yourself is more exciting and fun (and above all you have the pleasure to learn something new)" If I did use it I will have learned nothing. The whole purpose of starting this project was so I could learn python. I do so very much enjoy learning new things. The rest of the game is going well. So for I've figured out how to: 1. Create the gui 2. Pick a word from a list 3. Scramble the letters 4. Display them in a drawing area 5. Allow user to click the letters to make a word 6. Check the guessed word against a list of words 7. If matched guessed word is added to a treeview (list box) I am confidant that i can create functions for: 1. Scoring points 2. Advancing to next round 3. Saving the game 4. Polish the gui, etc The only thing I am having problems with (so far) is this algorithm which would let the player know how many words are left to guess. When I am finished this project, I plan to post it somewhere so that others can learn from it too. Peace, kreglet Mac Ryan wrote: > > > Of course doing things by yourself is more exciting and fun (and above > all you have the pleasure to learn something new), but if you finally > should decide to invoke an external utility (e.g.: for performance > issues), then you might be interested in using "an": it's very fast and > in the repositories of most linux distro. It has plenty of options. > Example usage: > > an -m4 -w python [search only for single words in the dictionary with a > minimum length of 4 letters] returns: > hypo > phony > pony > python > tony > typo > > Good luck with your project, > Mac. > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25119206.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
Wayne, > def myfunc(cmpword, mainword): > for letter in cmpword: > if mainword.gets(letter): > if cmpword[letter] >mainword[letter]: > return False > else: > return False I tried your function and couldn't get it to work. It threw an error in the line "if mainword.gets(letter):" saying that "gets" was not an attribute of dictionary. I tried it with "if mainword.get(letter):" -- no s but that would't work either. I've been playing with this most of the day and this is what i came up with: from operator import itemgetter class letters: def __init__(self): self.lettercount={} self.inlist=False self.inword=False self.mainword="" self.cmpword="" lc=letters() def countletters(word): lc.lettercount = {} for letter in word: lc.lettercount[letter] =lc.lettercount.get(letter,0) + 1 print sorted(lc.lettercount.iteritems(), key=itemgetter(1)) lc.mainword="batty" lc.cmpword="batyy" countletters(lc.mainword) mainword = lc.lettercount countletters(lc.cmpword) cmpword = lc.lettercount lst=[] for key in cmpword.keys(): for ky in mainword.keys(): if key<>ky: pass else: lst.append(key) for key in cmpword.keys(): if key not in lst: lc.inlist=False break else: lc.inlist=True # At this point the program stops if a letter is in cmpword that is not in mainword # What I try to do next is compare the values of the dictionary keys( this is where I'm getting confused) # get keys/values from cmpword # compare the values of the keys from mainword that match the keys from cmpword # if there is a key in mainword that is not in cmpword, ignore it # if a key is the same in both compare the values #if the value of a key that is in cmpword is greater the the value of the corresponding key in mainword then cmpword would not be in mainword -- cmpkeys=[] cmpvals=[] if lc.inlist==True: for key, val in cmpword.items(): cmpkeys.append(key) cmpvals.append(val) for a in range(len(cmpkeys)): for ky, vl in mainword.items(): if cmpkeys[a]==ky: #? if cmpvals[a]>vl: # lc.inword=False else: lc.inword=True print cmpkeys[a], cmpvals[a], ky, vl print if lc.inword==True: print lc.cmpword + " is IN: " + lc.mainword else: print lc.cmpword + " is Not in: " + lc.mainword Lol, it aint pretty, and it almost works. If you change the letters in lc.cmpword you'll see what I mean. There's got to be another way :) cheers, kreglet Wayne-68 wrote: > > > > That's correct - your function countletters returns None, so you're > assigning cmpword to None. And since None is not an iterable type, it > throws > an error. Try returning a value like I mentioned above and see how that > works. > > HTH, > Wayne > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25124979.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
Wayne, I appreciate your patience with me. I still can't get this to work: from operator import itemgetter class testwords: def __init__(self): self.lettercount={} self.inword=False self.mainword="" self.cmpword="" def countletters(word): lc.lettercount = {} for letter in word: lc.lettercount[letter] =lc.lettercount.get(letter,0) + 1 print sorted(lc.lettercount.iteritems(), key=itemgetter(1)) def comparewords(cmpword, mainword): for letter in cmpword: if mainword.get(letter): print letter, cmpword[letter], mainword[letter] if cmpword[letter] >mainword[letter]: lc.inword=False else: if cmpword[letter] <=mainword[letter]: lc.inword=True lc=testwords() lc.mainword="batty" lc.cmpword="bat" countletters(lc.mainword) mainword = lc.lettercount countletters(lc.cmpword) cmpword = lc.lettercount comparewords(cmpword, mainword) if lc.inword==True: print lc.cmpword + " IS in: " + lc.mainword if lc.inword==False: print lc.cmpword + " IS NOT in: " + lc.mainword This is confusing me: lc.mainword="batty" lc.cmpword="bat" [('a', 1), ('y', 1), ('b', 1), ('t', 2)] [('a', 1), ('b', 1), ('t', 1)] a 1 1 b 1 1 t 1 2 bat IS in: batty lc.mainword="batty" lc.cmpword="byyt" [('a', 1), ('y', 1), ('b', 1), ('t', 2)] [('b', 1), ('t', 1), ('y', 2)] y 2 1 b 1 1 t 1 2 byyt IS in: batty if I put : if cmpword[letter] <=mainword[letter]: lc.inword=True on the same level as the else statement: lc.mainword="batty" lc.cmpword="bat" [('a', 1), ('y', 1), ('b', 1), ('t', 2)] [('a', 1), ('b', 1), ('t', 1)] a 1 1 b 1 1 t 1 2 bat IS Not in: batty Neither is: byyt Isn't what comes after the else statment to catch if a letter is in the cmpword that is not in the mainword? lc.mainword="batty" lc.cmpword="bst" KeyError: 's' Wayne-68 wrote: > > On Mon, Aug 24, 2009 at 8:58 PM, kreglet wrote: > >> >> Wayne, >> >> > def myfunc(cmpword, mainword): >> > for letter in cmpword: >> > if mainword.gets(letter): >> > if cmpword[letter] >mainword[letter]: >> > return False >> > else: >> > return False >> >> I tried your function and couldn't get it to work. It threw an error in >> the >> line "if mainword.gets(letter):" saying that "gets" was not an attribute >> of >> dictionary. I tried it with "if mainword.get(letter):" -- no s but that >> would't work either. > > > sorry, 'get' is what I meant. You also need to add "return True" on the > same > level as the else. > > In [5]: word1 = {'d':1, 'o':1, 'g':1} > > In [6]: word2 = {'g':1, 'o':1} > > In [7]: in_word(word2, word1) > Out[7]: True > > In [24]: word2 = {'b':1, 'a':1, 'r':1} > > In [25]: in_word(word2, word1) > Out[25]: False > > HTH, > Wayne > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25140474.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
Hello Kent, Yes I would like to see your implementation. It seems to work but I get error at the end. concat=''.join mainword="python" cmpword="pot" # sort the letters in the target word; for example 'python' becomes 'hnopty' tmplst=[] for letters in mainword: tmplst.append(letters) tmplst.sort() mainword=concat(tmplst) # sort the letters in the word you want to test, for example 'pot' becomes 'opt' tmplst=[] for letters in cmpword: tmplst.append(letters) tmplst.sort() cmpword=concat(tmplst) inword=False # walk through test letters looking for them in the target list. print cmpword, mainword for letter in range(len(cmpword)): #Test for let in range(len(mainword)):#Target print cmpword[letter], mainword[let], # if it matches the current target letter, go to the next letter in each list if cmpword[letter]==mainword[let]: print "Match: " let +=1 letter +=1 # if it is less than the current target letter, go to the next target letter if cmpword[letter]mainword[let]: print "No Match:" inword=False inword=True if inword==True: print cmpword + " is IN: " + mainword else: print cmpword + " is NOT in: " + mainrowd opt hnopty o h No Match: o n No Match: o o Match: p p Match: t t Match: Traceback (most recent call last): File "/home/kreglet/bin/knt.py", line 45, in if cmpword[letter] > > Another way to do this: > - sort the letters in the target word; for example 'python' becomes > 'hnopty' > - sort the letters in the word you want to test, for example 'pot' becomes > 'opt' > - walk through test letters looking for them in the target list. For > each test letter, > - if it matches the current target letter, go to the next letter in each > list > - if it is less than the current target letter, go to the next target > letter > - if the test letter is greater than the target letter, or you run > out of target letters, there is no match > - if you get to the end of the test letters, you have a match > > The code for this is pretty simple and doesn't require much in the way > of data, just the two lists of letters. If you like I can share my > implementation. > > Kent > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25142030.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Algorithm
Wayne, Kent, Alan, and Mac Thank you for all the help and suggestions . Wayne and Kent, Both your solutions work great. The extra comments you gave on the code that I tried will help reduce the line count and make the code more readable in the rest of the project. Apparently, I still have a lot to learn. I really appreciate the time you took to help and teach me. Thanx, kreglet -- View this message in context: http://www.nabble.com/Algorithm-tp25107922p25145813.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Wordscramble.py
This is my first Python project. I am doing this to help me learn the language. I was wondering if someone could give me some advice as I have a lot of questions. 1. I would like to have someone look over the code and tell me how to improve it. I am sure that a lot of it can be done better than the way that I have it written. Is anyone that would be willing to do this? 2. Although it works as is I would like some advice on improving it. ie. Making it look better, play better, etc. 3. I switched from Windows to Linux about 2 months ago. I read that Python is a cross platform language. What would need to be done to make this program run in windows too? 4. Once it is finished, I would like to make it installable for people other than programmers. How? These are a few of the things that I would like to accomplish. The code can be found at pastebin.com: http://pastebin.com/m1ab9a734 Wordscramble.py http://pastebin.com/d2686ec4scrmod.py http://pastebin.com/m4f611e0c wordlist.py ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] NameError
I keep getting the following error and don't uderstand why: Traceback (most recent call last): File "/home/kreglet/bin/test.py", line 15, in btnStatclick btnStat.set_label("Pressed") NameError: global name 'btnStat' is not defined #!/usr/bin/env python import gtk import sys class NewAppWindow(gtk.Window): def btnStatclick(self, widget, data=None): #print status if self.status == True: btnStat.set_label("Not Pressed") self.status =False print self.status elif self.status == False: btnStat.set_label("Pressed") self.status =True print self.status def endapp(widget, data=None): sys.exit() def __init__(self): super(NewAppWindow, self).__init__() self.set_title("New App") self.set_size_request(1024, 768) self.set_keep_above(True) self.set_position(gtk.WIN_POS_CENTER) self.set_modal(True) self.status=False fixed = gtk.Layout() btnClose = gtk.Button() btnClose.set_use_stock(True) btnClose.set_label("gtk-close") btnClose.show() btnStat = gtk.Button("Status") fixed.put(btnStat, 650, 10) btnStat.connect("clicked", self.btnStatclick) fixed.put(btnClose, 650, 50) btnClose.connect("clicked", self.endapp) self.add(fixed) self.connect("destroy", gtk.main_quit) self.show_all() NewAppWindow() gtk.main() -- View this message in context: http://www.nabble.com/NameError-tp25530479p25530479.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Dialogs
I am having a problem with GtkDialogs. Ref: http://faq.pygtk.org/index.py?req=show&file=faq10.011.htp http://faq.pygtk.org/index.py?req=show&file=faq10.011.htp I want to add a treeview to the dialog. The first time btnDialog is pressed the dialog shows with the treeview in it. If I press btnDialog a second time the app closes and I get a "Segmentation fault" error. Without adding the treeview, the dialog works as expected. Do you have to destroy the widgets added to a dialog when you destroy the dialog? If so how? #!/usr/bin/env python import pygtk import gtk btnDialog = gtk.Button("Dialog") # list of items to display plist = gtk.ListStore(int, str) plist.append( (0, "Item 1",) ) plist.append( (1, "Item 2",) ) plist.append( (2, "Item 3",) ) # the Treeview treeview = gtk.TreeView() model = treeview.get_selection() model.set_mode(gtk.SELECTION_SINGLE) r = gtk.CellRendererText() treeview.insert_column_with_attributes(-1, "Items", r, text=1) treeview.set_model(plist) class NewWindow(gtk.Window): def btnDialogClick(self, widget): dialog = gtk.Dialog('Choose Item', self, # the window that spawned this dialog gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, ("Play Now", 77, gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) dialog.vbox.pack_start(gtk.Label('Do you want to play a game?')) dialog.vbox.pack_start(treeview) dialog.show_all() result = dialog.run() if result == 77: print "Play Button Clicked" elif result == gtk.RESPONSE_CLOSE: print "Close Button Clicked" dialog.destroy() # def __init__(self): super(NewWindow, self).__init__() self.set_title("test") self.set_size_request(1024, 768) self.set_keep_above(True) self.set_position(gtk.WIN_POS_CENTER) self.set_modal(True) fixed = gtk.Layout() fixed.put(btnDialog, 400, 5) btnDialog.connect("clicked", self.btnDialogClick) self.add(fixed) self.connect("destroy", gtk.main_quit) self.show_all() NewWindow() gtk.main() -- View this message in context: http://www.nabble.com/Dialogs-tp25879937p25879937.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor