[Tutor] Anagram creator
Hi everyone, I'm having trouble with an anagram generating program that I am writing in Python. My output is not what it should be and I think the reason has something to do with my helper functions creating a reference to a dictionary each time it is called rather than a new clone dictionary. Here is my main function, with explanation afterward: def anagramsHelper(phrase,dictionary,anagramsofar):if isSolved(phrase): #returns true if the dictonary for the phrase is empty print anagramsofar return True for word in dictionary: if wordCanBeMade(word, phrase): anagramsofar=anagramsofar+ +word phraseclone=removeLetters(word, phrase) anagramsHelper(phraseclone,dictionary,anagramsofar) Initially it takes a dictionary representing a word or phrase (eg {'a':2,'d':1, 'e':2}), a dictionary in the form of a list of words, and anagramsofar which is initially passed as . Next, isSolved returns true if the dictionary is empty, meaning that all letters in the phrase have been used up. Otherwise, for each word in the dictionary, the program tests whether the word can be made from letters in the phrase. If it can, the word is appended to phrasesofar. removeLetters then removes the letters that were used to make the word. I saved the new phrase as phraseclone as an attempt to troubleshoot; originally I just used the original phrase variable. Next, the function is recursively called with the letters removed from the phrase. The end result is that when the phrase dictionary is empty, anagramsofar is printed. This should generate all anagrams of a given phrase using a given dictionary of words. So, for instance, I might call (from my main function): dictionary=importDictionary() #A list of 10,000 strings, representing words in the dictionary anagramsHelper(george bush,dictionary,) wordCanBeMade returns a boolean T or F, and I've posted the code for removeLetters below. My code is not working as expected, and after a good deal of debugging it seems that during the recursive calls, when I remove letters from the dictionary they stay removed, even though I'm trying to create a new dictionary with each call (so that removed letters are not remembered). As a result, anagramsofar gets longer with every call and isSolved returns True every time, since all keys are removed after the first few calls. Here is the function for removeLetters: def removeLetters(word, phrase): phraseclone=phrase.copy() for letter in word: phraseclone[letter]=phraseclone[letter]-1 return phraseclone I'm trying to create a copy of phrase with each function call and then return the copy to prevent the program remembering the removed keys...but it's not working. Does anyone see what I'm doing wrong? I can post the entire program if needed; I just wanted to keep things somewhat concise. Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Lib Files
Hello everyone, I discovered yesterday that the Python package has a number of built in example scripts in the /lib directory. Perhaps this is common knowledge but I did not know about it. I can't seem to find any kind of guide to the files, though. Is there a readme somewhere that someone can point me to, or perhaps documentation for the files online? I cant find anything on the python.org site. This is for version 2.5. Thanks very much, Ben ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Working with lists
Hi everyone, I seem to use this pattern alot when writing functions and I'm wondering if there is a more efficient method. It comes up whenever I want to work with more than one item in a list; for instance, say I want to add each consecutive number in alist and output the new list. Ideally, I'd be able to write: for num in list1: newlist.append(num+nextnum) This doesn't work, though because there's no way to access nextnum unless I implement a count variable like this: count=1 for num in list1: newlist.append(num+list1[count]) count+=1 Instead, it usually ends up easier to write: for index in range (len(list1)-1): newlist.append((list1[index]+list1[index+1])) It's not a big deal to have to write the additional code, but problems arise when I use this structure in the context of more complex functions, when I am passing multiple lists of varying length, because it is easy to get confused with the index numbers and I can't do anything to the last value of the list, since I then get an indexerror because the function tries to call list[i+1]. Is there a simpler way to do a procedure like this? Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] List of lists help
Hello, I am completely baffled by this action and would appreciate any help. My problem is occurring within a class which is within a larger program; if I need to post the entire program let me know and I will. It's only about 250 lines so far. Anyways, I am using a list of lists to store data in a GUI game called goMoku. It is kind of like a connect five game, pretty simple. When a user clicks a certain square, this line is called to store the move: self.boardarray[row][col] = self.currentPlayer self.currentPlayer is either White or Black which are constants set to 1 and 2, so that when, say, the black player clicks on row 2 column 4, self.boardarray[2][4] will be set to 2. Instead, the program is setting multiple values within the list as 2. Here is an example output, when I click on (0,0): [[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. The board is 13X13 and position 0 for each list in the list of lists is being set to 2, while only position 0 in the first list should be changed to 2. To check for errors, I've surrounded the statement by print statements to see what's going on, like this: print self.boardarray print row,col,self.currentPlayer,self.boardarray[row][col] self.boardarray[row][col] = self.currentPlayer print self.boardarray My output is: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. 0 0 2 0 [[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. I do not understand what is going on. Everything is as expected except that the extra positions are being assigned as 2. Can anyone suggest what is going wrong? Thanks, Ben ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Intermediate/advanced concepts
Hi everyone, I've been teaching myself python for a few months and I'm becoming frustrated because I've kind of hit a wall in terms of learning new information. In an effort to continue to learn I've found some material on more intermediate/advanced topics like linked lists, nodes, trees, etc. However, it's kind of like reading a math textbook - the tutorials do a decent job of explaining the material but it's all kind of theoretical, and I'm not sure how I'd apply these concepts in real world applications, or incorporate them into my code. Does anyone have any suggestions for learning about real world application of more advanced concepts? Also, are there other concepts that I should focus on? Frankly, I'm a bit bored because I've hit this ceiling, and I'm not really sure where to go to next. Thanks, Ben ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Building RSS reader with Python
Hi everyone, I'm new to programming and am building a very basic rss reader for my first major project with python and GUI. As it is, I have it set up so that if I input an exact rss feed address (ex http://news.google.com/?output=rss) I can retrieve stories. Id like to make it so that I can enter a site (like http://news.google.com) and have it search for the address of rss feeds on the site, so that I don't have to know exact page addresses for the rss, since most sites don't have such a straightforward location for the RSS page. Is there a way to do this? Thanks, Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter troubles
Hi guys, I'm having trouble with weird activity with a Tkinter GUI I'm creating. I've stripped down the code somewhat to simplify the problem somewhat, and I've posted it below, with further explanation at the end of this message: from Tkinter import * import tkFileDialog,tkSimpleDialog WINDOWWIDTH=500 WINDOWHEIGHT=500 class App: def __init__ (self,master): self.window = Frame(master) self.window.pack() self.master= master #Create frame to contain all others self.display=Frame(self.window,width=WINDOWWIDTH,height=WINDOWHEIGHT, bg='black') self.display.pack() self.addMenu(self.master) #Create widgets self.createwidgets() def createwidgets(self): self.leftframe=Frame(self.display, width=WINDOWWIDTH/3,height=WINDOWHEIGHT, bg='white') self.rightframe=Frame(self.display, width=2*WINDOWWIDTH/3,height=WINDOWHEIGHT, bg='blue') self.leftframe.pack(side=left, expand=yes, fill=x) self.rightframe.pack(side=left, expand=yes, fill=x) def displayStories(self): self.lb = Text(self.leftframe) self.lb.pack() def addMenu(self,master): self.menu = Menu(self.window) master.config(menu=self.menu) self.feedmenu = Menu(self.menu) self.menu.add_cascade(label=RSS, menu=self.feedmenu) self.feedmenu.add_command(label=Load RSS, command=self.displayStories) root=Tk() app=App(root) root.mainloop() : Basically I'm trying to create 2 columns on the page so that (eventually) I will be able to have sepearte text boxes in each column. The code so far creates a leftframe and rightframe, with parent frame self.display . When I run the script this happens as expected. But next, I want to create a text box within self.leftframe which is done in function displayStories . self.lb is created with parent self.leftframe . When this is run, the text box shows up, but my layout goes to hell. I want the text box to be contained within self.leftframe, but when it is added self.leftframe disappears (or is completely filled by the text box), the dimensions that I had specified for self.leftframe and self.rightframe are forgotten about, and I can see self.display (black background) on the part of the screen in the left frame that is not filled by the text box. This makes a lot more sense if you run the simple script I've posted. I've tried adjusting various options, and also using the grid manager instead of pack, but I can't seem to figure out why this is happening. Can anyone help out? Thanks, Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Setting up server for CGI
Hi everyone, I am new to programming and have been programming with Python for about 2.5 months. After learning the basics of the language I am trying to teach myself CGI with Python. I've come across a few resources that teach CGI, but I am having much trouble setting up a server to view CGI scripts on my browser (Note: some of terminology may be wrong). I am running Windows XP with a Firefox browser. Here is what I've tried so far: I followed the instructions on a tutorial and created a C:\cgihome server, and then created the following file: C:\cgihome\server\cgihttpserver.py It contains the following code: [CODE] import CGIHTTPServer import BaseHTTPServer class Handler(CGIHTTPServer.CGIHTTPRequestHandler): cgi_directories = [/cgi] PORT = 8000 httpd = BaseHTTPServer.HTTPServer((, PORT), Handler) print serving at port, PORT httpd.serve_forever() [/CODE] This is supposed to set up a basic server on my system. When I run from the command line, it seems to be working and displays the message Serving at Port 8000. According to the tutorial I should then be able to run CGI scripts by saving them in C:/cgihome/cgi , and then opening in the browser (after running the server script on the command line). So for instance I wrote this script: [CODE] #!c:\Python25\python.exe print Content-Type: text/html print print \ html body h2Hello World!/h2 /body /html [/CODE] and saved it as C:\cgihome\cgi\cgitest.py . When I try opening it in my browser, though, I just get 404 error: File not found. This shows up both in the browser window and the command prompt window. When I try using a plain .html file saved in C:\cgihome instead, I get the same error. I can't get anything to run. I'm sure I'm doing something wrong, but I don't know what. I have also tried downloading the Apache server as well, but it is 10 times more complex than my simple server script, and geared towards Linux users who know what they are doing. Can someone please explain to me like I'm a child how to set up a basic web server that I can run CGI scripts on? Thanks very much. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Setting up server for CGI
I'm not sure what you mean, What directory do you run from?. I have the file saved as C:\cgihome\cgi\cgitest.py and I try running it by typing the following in the URL field: http://localhost:8000/cgi/cgitest.py . I tried changing the folder name to cgi-bin and get the same error. It says, Nothing matches the given URI, even though the file is saved in the directory specified. The Python program itself is saved in C:/Python25 but I don't think this makes a difference, especially since I can't run regular html files with my server. Thanks again. Quoting Kent Johnson [EMAIL PROTECTED]: On Thu, Oct 30, 2008 at 9:41 PM, [EMAIL PROTECTED] wrote: I followed the instructions on a tutorial and created a C:\cgihome server, and then created the following file: C:\cgihome\server\cgihttpserver.py It contains the following code: [CODE] import CGIHTTPServer import BaseHTTPServer class Handler(CGIHTTPServer.CGIHTTPRequestHandler): cgi_directories = [/cgi] PORT = 8000 httpd = BaseHTTPServer.HTTPServer((, PORT), Handler) print serving at port, PORT httpd.serve_forever() [/CODE] This is supposed to set up a basic server on my system. When I run from the command line, it seems to be working and displays the message Serving at Port 8000. What directory do you run from? It should be the cgihome directory. Alternately, rename your /cgi directory to /cgi-bin and from the command line in the cgihome directory, run python -m CGIHTTPServer We had a very recent thread about this that might help; see the various please help with simple python CGI script posts here: http://mail.python.org/pipermail/tutor/2008-October/thread.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Exhaustive Enumeration
This is from the MIT Opencourseware intro to computer science course, which I've been working my way through. I understand what needs to be done (I think), which is basically to test each possibility and return the list of states with the most electoral votes that can be paid for under the campaign budget. I am just at a loss as to how to do it, and I've been thinking about it all weekend. Here is the problem I am referring to. One assumption is that every $1 of money spent in a state translates into a popular vote. Many thanks for any suggestions. Also, the next part of the question asks to do the same thing using Branch and Bound, which I also anticipate having trouble with. If I haven't described things sufficiently, the complete problem is available at: http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/Assignments/index.htm , problem 5. Complete and test this function according to her specification below. Note that she was using exhaustive enumeration to compute the result. Your friend assured you that the function needs no more than 5 additional lines of code. # Problem 2: Exhaustive enumeration def finance_campaign_ee(budget, free_states): Takes a budget, in dollars, and a list of available states, as a list of dictionaries. Computes and returns the list of states that maximizes the total number of electoral votes such that these states can be acquired on the budget. Returns an empty list if no states can be acquired. cheap_states=[] for s in free_states: if s['pop'] = budget: cheap_states.append(s) # Base case if len(cheap_states)==0: res_list=[] # Recursive case else: curr_state=cheap_states[0] other_states=cheap_states[1:] inc_states=finance_campaign_ee( budget-curr_state['pop'], other_states) inc_states.append(curr_state) inc_evotes=total_evotes(inc_states) excl_states=finance_campaign_ee( budget, other_states ) excl_evotes=total_evotes(excl_states) # ... your code goes here ... res_list =return res_list ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Exhaustive Enumeration
I'm actually not enrolled in the course; MIT puts some of its course materials available online as a general resource. I am out of school and trying to teach myself python on my own. I'm very much a beginner, and since I'm not privy to the lectures or notes from this course I have to fill in things from other sources. Basically, with respect to this problem, I'm at a loss as to how to approach it. My first thought was to use some sort of nested for loop structure to iterate through each possible state combination, but I don't think this is possible, since a for loop would just test for, for instance, (state 1 and 2, state 1 and 3, state 1 and 4, etc.) and not (state 1 and 3, state 1 and 2 and 3, etc.). I could maybe make it work for a very small number of states, but if you are taking 10 states as arguments I don't see a way this could work. Also, the way the question is asked seems to imply that the new code will go after the existing code, and also that it will be only about five lines. I'm guessing that maybe some kind of recursion is required but I really don't know, and recursion is a new concept to me as well. Thanks! Quoting Robert Berman [EMAIL PROTECTED]: A very interesting problem. Given this is homework, I am not sure what it is you want. Do you want the solution coded and tested? Do you want this to include two or three algorithms optimized for speed as well as accuracy? I think the problem is well enough defined so that you do not need any clarification of what it is your professor wants from you. If you would like some help finding a solution set, perhaps you would consider submitting some of your own solutions and commentary as to where your ideas are breaking down. Then, probably, a number of people will jump in to help you. Robert [EMAIL PROTECTED] wrote: This is from the MIT Opencourseware intro to computer science course, which I've been working my way through. I understand what needs to be done (I think), which is basically to test each possibility and return the list of states with the most electoral votes that can be paid for under the campaign budget. I am just at a loss as to how to do it, and I've been thinking about it all weekend. Here is the problem I am referring to. One assumption is that every $1 of money spent in a state translates into a popular vote. Many thanks for any suggestions. Also, the next part of the question asks to do the same thing using Branch and Bound, which I also anticipate having trouble with. If I haven't described things sufficiently, the complete problem is available at: http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-00Fall-2007/Assignments/index.htm , problem 5. Complete and test this function according to her specification below. Note that she was using exhaustive enumeration to compute the result. Your friend assured you that the function needs no more than 5 additional lines of code. # Problem 2: Exhaustive enumeration def finance_campaign_ee(budget, free_states): Takes a budget, in dollars, and a list of available states, as a list of dictionaries. Computes and returns the list of states that maximizes the total number of electoral votes such that these states can be acquired on the budget. Returns an empty list if no states can be acquired. cheap_states=[] for s in free_states: if s['pop'] = budget: cheap_states.append(s) # Base case if len(cheap_states)==0: res_list=[] # Recursive case else: curr_state=cheap_states[0] other_states=cheap_states[1:] inc_states=finance_campaign_ee( budget-curr_state['pop'], other_states) inc_states.append(curr_state) inc_evotes=total_evotes(inc_states) excl_states=finance_campaign_ee( budget, other_states ) excl_evotes=total_evotes(excl_states) # ... your code goes here ... res_list =return res_list ___ 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] Practice exercise sources
Hi guys, I'm new to programming and have been learning Python as suggested by a friend as a good language to start with. I bought the Learning Python book from O'Reilly and I'm about 2/3 of the way through, and I've also read through 2 intro tutorials on the web. At this point, I understand the basics of lists, functions, objects, etc. and can code to solve simple problems. However, I'm finding that learning programming is like learning math: you can't learn simply reading the book - solving problems is what reinforces the material and helps you remember it, and teaches you to solve problems creatively. The book (although very comprehensive) doesn't have many problems, and the tutorials I've found only have basic exercises that illustrate the point they are making. I've read through some of the archives on this list and this is somewhat helpful as far as providing unique problems, but I guess what I'm looking for is a database/list of problems to solve, with answers that you can look at after you've had a go, so that you can see what the expert would have done. Kind of akin to the problems at the end of the chapter in a math textbook, with solutions in the back. Can anyone point me towards a good resource? Thanks very much, Ben ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Practice exercise sources
-> Re: [Tutor] Practice exercise sources tutor -- Thread -- -- Date -- <!-- google_ad_client = "pub-7266757337600734"; google_alternate_ad_url = "http://www.mail-archive.com/blank.png"; google_ad_width = 160; google_ad_height = 600; google_ad_format = "160x600_as"; google_ad_channel = "8427791634"; google_color_border = "FF"; google_color_bg = "FF"; google_color_link = "006792"; google_color_url = "006792"; google_color_text = "00"; //--> [Tutor] Practice exercise sources btkuhn Re: [Tutor] Practice exercise sources Alan Gauld Re: [Tutor] Practice exercise sources Kent Johnson Re: [Tutor] Practice exercise sources Samir Parikh Reply via email to