[Tutor] recursive glob -- recursive dir walk
Hello, A foolow-up ;-) from previous question about glob.glob(). I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. I'd like to know if there are standard tools to do that. And your comments on the 2 approaches below. Thank you, denis -1- I first wrote the following recurseDirGlob() tool func. import os, glob def dirGlob(dir, pattern): ''' File names matching pattern in directory dir. ''' fullPattern = os.path.join(dir,pattern) return glob.glob(fullPattern) def recurseDirGlob(topdir=None, pattern=*.*, nest=False, verbose=False): ''' ''' allFilenames = list() # current dir if verbose: print *** %s %topdir if topdir is None: topdir = os.getcwd() filenames = dirGlob(topdir, pattern) if verbose: for filename in [os.path.basename(d) for d in filenames]: print%s %filename allFilenames.extend(filenames) # possible sub dirs names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] dirs = [n for n in names if os.path.isdir(n)] if verbose: print -- %s % [os.path.basename(d) for d in dirs] if len(dirs) 0: for dir in dirs: filenames = recurseDirGlob(dir, pattern, nest, verbose) if nest: allFilenames.append(filenames) else: allFilenames.extend(filenames) # final result return allFilenames Example with the following dir structure ; the version with nest=True will recursively nest files from subdirs. d0 d01 d02 d020 2 .txt files and 1 with a different pattern, in each dir recurseDirGlob(/home/spir/prog/d0, *.txt, verbose=True) -- *** /home/spir/prog/d0 t01.txt t02.txt -- ['d01', 'd02'] *** /home/spir/prog/d0/d01 t011.txt t012.txt -- [] *** /home/spir/prog/d0/d02 t021.txt t022.txt -- ['d020'] *** /home/spir/prog/d0/d02/d020 t0201.txt t0202.txt -- [] ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] recurseDirGlob(/home/spir/prog/d0, *.txt) -- ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] recurseDirGlob(/home/spir/prog/d0, *.txt, nest=True) -- ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', ['/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt'], ['/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', ['/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt']]] -2- Another approach was to build a general 'dirWalk' tool func, similar to os.path.walk: def dirWalk(topdir=None, func=None, args=[], nest=False, verbose=False): ''' ''' allResults = list() # current dir if verbose: print *** %s %topdir if topdir is None: topdir = os.getcwd() results = func(topdir, *args) if verbose: print %s % results allResults.extend(results) # possible sub dirs names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] dirs = [n for n in names if os.path.isdir(n)] if verbose: print -- %s % [os.path.basename(d) for d in dirs] if len(dirs) 0: for dir in dirs: results = dirWalk(dir, func, args, nest, verbose) if nest: allResults.append(results) else: allResults.extend(results) # final allResults return allResults Example uses to bring the same results, calling dirGlob, would be: dirWalk(/home/spir/prog/d0, dirGlob, args=[*.txt], verbose=True) -- dirWalk(/home/spir/prog/d0, dirGlob, args=[*.txt]) dirWalk(/home/spir/prog/d0, dirGlob, args=[*.txt],
[Tutor] XML: changing value of elements
Hi all, I have a rather complex XML file and I need to change some values inside this file. So far I have been using minidom, but I can't find the thing I am looking for. My code so far: from xml.dom import minidom xmlFile = 'signal1.xml' xmlDocument = minidom.parse(xmlFile) SignalsNode = xmlDocument.firstChild signalNode = SignalsNode.childNodes[1] signalNode.removeAttribute(name) signalNode.setAttribute(name, Test_Name) signalNode.getAttribute(name) descElem = signalNode.childNodes[1] I know how to manipulate the value of the attributes, but I can't seem to change the values of eg: Description Snippet from my XML file: ?xml version=1.0 encoding=UTF-8 ? file:///C:\Users\Public\XML%20parse\signal1.xml## - Signals file:///C:\Users\Public\XML%20parse\signal1.xml## - Signal model=Model name=Model_X type=Flyer DescriptionSome description/Description SpecName Model_X /SpecName Reporting category=POW name= / file:///C:\Users\Public\XML%20parse\signal1.xml## - Trigger type=open Severitynormal/Severity MessageModel X 1/Message /Trigger file:///C:\Users\Public\XML%20parse\signal1.xml## - Trigger type=close Severityminor/Severity Message Model X 2/Message /Trigger /Signal /Signals Any suggestions on how to change some of the values of the elements? Thanks Johan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] gui further explained
On Tue, Jun 9, 2009 at 10:31 PM, Essah Mitges e_mit...@hotmail.com wrote: i don't know if its what i am searching that is wrong but what i am trying to do is link my game i made in pygame to my pygame menu the menu has 4 button classes on it one foe instruction one to quit one for high scores and one to start the game the 3 other buttons work all but the one to start the game this is basicly the menu i want people to see first the main menu So why don't you put your menu in your game? Consider the following: # Lamegame.py - probably the lamest game ever! print Welcome to Lame Game! raw_input(Please type something and press enter: ) print You win! So there's a game. Now let's add a menu: # lamegameimproved.py - the lamest game, now with a menu! import sys print Welcome to Lame Game! print \nMenu:\n print (Q)uit print (P)lay choice = raw_input(Your Choice? (P or Q): ) if choice.lower() == 'q': sys.exit(0) elif choice.lower() == 'p': # add original code here See? Quite simple. Even with pygame it shouldn't be a whole lot more complex than that. And that's really the most simple example I could think of and it's really not very good. For instance you could put the original code into a game function and then call it if the choice was P. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Help running a simple python script for one time operation (noob)
On Tue, Jun 9, 2009 at 11:57 PM, Melinda Roberts mindi...@mac.com wrote: Hi - I would like to export a large amount of data from ExpressionEngine to Wordpress, and have had lots of trouble finding something that isn't miles over my head. I did find these three scripts, which seem to be perfect for this purpose, but I don't know how to go about implementing them. It's a three-step process: 1. Configure and run Databases.cfg 2. Run ExpressionEngineExport.py 3. Run WordPressImport.py. I have a mac, am all set with access to my dbs on my host, all I need is to be pointed in the right direction. Anyone? It looks like it should be straightforward. I don't have the sqlobject library installed though, so it complains to me. Traceback (most recent call last): File C:\Documents and Settings\Wayne\My Documents\Downloads\ExpressionEngineE xport.py, line 4, in module from sqlobject import * ImportError: No module named sqlobject What that means is that I need to install sqlobject from http://www.sqlobject.org/ Python should be installed on your mac by default. It appears that you've already got the Databases.cfg file configured, so you should just be able to run the other two files in the same directory as your .cfg file and everything should be fine. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] recursive glob -- recursive dir walk
2009/6/10 spir denis.s...@free.fr: A foolow-up ;-) from previous question about glob.glob(). Hopefully no misunderstanding this time :-) I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. Is it really derecated? It is still in the 3.0 docs with no mention of this.. I'd like to know if there are standard tools to do that. And your comments on the 2 approaches below. Well, this is what I came up with which I am sure someone can improve on. patern = '*.txt' topdir = 'C:\\GTK\\' textfiles = [f[0] for f in [glob.glob(os.path.join(d[0], patern)) for d in os.walk(topdir)] if f] textfiles ['C:\\GTK\\license.txt'] Greets Sander -1- I first wrote the following recurseDirGlob() tool func. import os, glob def dirGlob(dir, pattern): ''' File names matching pattern in directory dir. ''' fullPattern = os.path.join(dir,pattern) return glob.glob(fullPattern) def recurseDirGlob(topdir=None, pattern=*.*, nest=False, verbose=False): ''' ''' allFilenames = list() # current dir if verbose: print *** %s %topdir if topdir is None: topdir = os.getcwd() filenames = dirGlob(topdir, pattern) if verbose: for filename in [os.path.basename(d) for d in filenames]: print %s %filename allFilenames.extend(filenames) # possible sub dirs names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] dirs = [n for n in names if os.path.isdir(n)] if verbose: print -- %s % [os.path.basename(d) for d in dirs] if len(dirs) 0: for dir in dirs: filenames = recurseDirGlob(dir, pattern, nest, verbose) if nest: allFilenames.append(filenames) else: allFilenames.extend(filenames) # final result return allFilenames Example with the following dir structure ; the version with nest=True will recursively nest files from subdirs. d0 d01 d02 d020 2 .txt files and 1 with a different pattern, in each dir recurseDirGlob(/home/spir/prog/d0, *.txt, verbose=True) -- *** /home/spir/prog/d0 t01.txt t02.txt -- ['d01', 'd02'] *** /home/spir/prog/d0/d01 t011.txt t012.txt -- [] *** /home/spir/prog/d0/d02 t021.txt t022.txt -- ['d020'] *** /home/spir/prog/d0/d02/d020 t0201.txt t0202.txt -- [] ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] recurseDirGlob(/home/spir/prog/d0, *.txt) -- ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', '/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt', '/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', '/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt'] recurseDirGlob(/home/spir/prog/d0, *.txt, nest=True) -- ['/home/spir/prog/d0/t01.txt', '/home/spir/prog/d0/t02.txt', ['/home/spir/prog/d0/d01/t011.txt', '/home/spir/prog/d0/d01/t012.txt'], ['/home/spir/prog/d0/d02/t021.txt', '/home/spir/prog/d0/d02/t022.txt', ['/home/spir/prog/d0/d02/d020/t0201.txt', '/home/spir/prog/d0/d02/d020/t0202.txt']]] -2- Another approach was to build a general 'dirWalk' tool func, similar to os.path.walk: def dirWalk(topdir=None, func=None, args=[], nest=False, verbose=False): ''' ''' allResults = list() # current dir if verbose: print *** %s %topdir if topdir is None: topdir = os.getcwd() results = func(topdir, *args) if verbose: print %s % results allResults.extend(results) # possible sub dirs names = [os.path.join(topdir, dir) for dir in os.listdir(topdir)] dirs = [n for n in names if os.path.isdir(n)] if verbose: print -- %s % [os.path.basename(d) for d in dirs] if len(dirs) 0: for dir in dirs: results = dirWalk(dir, func, args, nest, verbose) if nest:
Re: [Tutor] recursive glob -- recursive dir walk
On Wed, Jun 10, 2009 at 2:28 AM, spirdenis.s...@free.fr wrote: Hello, A foolow-up ;-) from previous question about glob.glob(). I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. I'd like to know if there are standard tools to do that. And your comments on the 2 approaches below. I would use os.walk(), with fnmatch.fnmatch() to do the pattern matching, and write the function as a generator (using yield). It would look something like this (untested): import os, fnmatch def findFiles(topDir, pattern): for dirpath, dirnames, filenames in os.walk(topDir): for filename in filenames: if fnmatch.fnmatch(filename, pattern): yield os.path.join(dirpath, filename) To get a list of matches you would call list(findFiles(topDir, pattern)) but if you just want to iterate over the paths you don't need the list. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] recursive glob -- recursive dir walk
spir wrote: Hello, A foolow-up ;-) from previous question about glob.glob(). I need to 'glob' files recursively from a top dir (parameter). Tried to use os.walk, but the structure of its return value is really unhandy for such a use (strange, because it seems to me this precise use is typical). On the other hand, os.path.walk seemed to meet my needs, but it is deprecated. I often use Fredrik Lundh's implementation, when I need a recursive 'glob'. And even though it was contributed some time ago, it appears to be 3.x compatible. http://mail.python.org/pipermail/python-list/2001-February/069987.html HTH, Marty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] gui further explained
does anyone know how to make a parallel or serial interface with respective software, i would prefer parallel because it is easy to utilise ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] gui further explained
Jacob Mansfield wrote: does anyone know how to make a parallel or serial interface with respective software, i would prefer parallel because it is easy to utilise Both the serial and the parallel interface seem to be covered by pyserial http://pyserial.wiki.sourceforge.net and http://pyserial.wiki.sourceforge.net/pyParallel . With these libraries you can program the ports from Python. Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] GUI recommendations/tutorials?
I think I'm ready to start working with some simple graphic output. Currently, I've got the basics of a Python program that calculates full tours of a honeycomb structure, going through each cell exactly once. The output from the program shows the paths as coordinates of each cell; what I'd like to do is create a simple window that would show the tour in graphical format, and using keystrokes to go through all of the tours that have been collected. I'm already accounting for eliminating duplicates by rotational symmetry by restricting the starting point to the cells in the northernmost row of hexes, but the ending point to be any of the edge hexes. I'm trying to identify duplicates by reflexive symmetries as well, but I'd like to get the visualization component up first. My problem is that I have no GUI experience outside of Visual Studio-style drag-and-drop IDEs. Which Python GUI system would you recommend for neophytes that would allow line drawing and a simple graphic load of a honeycomb structure in a JPG, for example, as a background? Tony R. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] GUI recommendations/tutorials?
Have you looked at PyGame yet? http://www.pygame.org/ On Wed, Jun 10, 2009 at 12:05 PM, taseriantaser...@gmail.com wrote: I think I'm ready to start working with some simple graphic output. Currently, I've got the basics of a Python program that calculates full tours of a honeycomb structure, going through each cell exactly once. The output from the program shows the paths as coordinates of each cell; what I'd like to do is create a simple window that would show the tour in graphical format, and using keystrokes to go through all of the tours that have been collected. I'm already accounting for eliminating duplicates by rotational symmetry by restricting the starting point to the cells in the northernmost row of hexes, but the ending point to be any of the edge hexes. I'm trying to identify duplicates by reflexive symmetries as well, but I'd like to get the visualization component up first. My problem is that I have no GUI experience outside of Visual Studio-style drag-and-drop IDEs. Which Python GUI system would you recommend for neophytes that would allow line drawing and a simple graphic load of a honeycomb structure in a JPG, for example, as a background? Tony R. ___ Tutor maillist - tu...@python.org http://mail.python.org/mailman/listinfo/tutor -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is nntp news reader address for this mailing list?
testing again ayyaz wrote: Testing Zia mkhawar...@hotmail.com wrote in message news:h0mqv0$b0...@ger.gmane.org... Thanks It works now. http://www.parglena.co.uk/outlookexpress.htm -Zia Emile van Sebille em...@fenx.com wrote in message news:h0mpjl$7b...@ger.gmane.org... On 6/9/2009 3:38 PM Mohammad Khawar Zia said... Hello All, I am new to this mailing list. I am trying to setup outlook Which version? Older ones don't do news right and you'll need to be on outlook express if you must use something called outlook. Try Thunderbird. to read the posts on this mailing list. What is the nntp address for thsi mailing list? The news server is nntp://news.gmane.org/ Then subscribe to the lists you're interested in. Emile nntp://news.gmane.org/gmane.comp.python.tutor doesn't work. Thanks, --Zia ___ 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 maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ 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] GUI recommendations/tutorials?
On Wed, Jun 10, 2009 at 11:05 AM, taserian taser...@gmail.com wrote: I think I'm ready to start working with some simple graphic output. Currently, I've got the basics of a Python program that calculates full tours of a honeycomb structure, going through each cell exactly once. The output from the program shows the paths as coordinates of each cell; what I'd like to do is create a simple window that would show the tour in graphical format, and using keystrokes to go through all of the tours that have been collected. I'm already accounting for eliminating duplicates by rotational symmetry by restricting the starting point to the cells in the northernmost row of hexes, but the ending point to be any of the edge hexes. I'm trying to identify duplicates by reflexive symmetries as well, but I'd like to get the visualization component up first. My problem is that I have no GUI experience outside of Visual Studio-style drag-and-drop IDEs. Which Python GUI system would you recommend for neophytes that would allow line drawing and a simple graphic load of a honeycomb structure in a JPG, for example, as a background? I don't *think* the turtle module allows loading a jpg as a background, but definitely allows you to draw a line. Tkinter's canvas PyGTK's DrawingArea Pygame pyglet matplotlib and even just using the PIL (Python Image(ing?) Library) could all accomplish parts if not all of your goals. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about class
Vincent Davis wrote: Thanks again for the help, A little followup. For my applicant class I have a few initial values that need to be set but I what to choose the value (actually the calculation to set the value) for each applicant (instance?) Here is the start of my Applicant Class class Applicant(object): quality is refers to the quality of the Applicant observe refers to the accuracy of which they assess the quality of the school def __init__(self, quality = 0, observe = 0): self. quality = quality self. observe = observe def Quality(self, mean, sd): print self, self.quality = normalvariate(mean, sd) print -- %s % self def Observe(self, mean, sd): print self, self. observe = normalvariate(mean, sd) print -- %s % self The problem with that approach is that repeated calls to Quality and Observe would change the value of self.quality and self.observe and it will be therefore unnecessary (and dangerous) to call self.Quality/Observe again in the future Usually I'd go with something like this: class Applicant(object): def __init__(self, quality, observe): self.quality = quality self.observe = observe def norm_quality(self, mean, sd): return normalvariate(mean, sd, self.quality) def norm_observe(self, mean, sd): return normalvariate(mean, sd, self.observe) Additionally-- although it is a matter of style --instead of passing mean and sd to norm_quality, I'd use functools.partial with normalvariate, mean, and sd. Then since they now don't take parameters they can then be easily turned into property using decorator. Or I could I guess do it this way, Is this better? I will only be setting the quality and observe values once for each instance. class Applicant(object): quality is refers to the quality of the Applicant observe refers to the accuracy of which they assess the quality of the school def __init__(self, mquality = 0, sdquality = 0, mobserve = 0, sdobserve = 0): self. quality = normalvariate(mquality, sdquality) self. observe = normalvariate(mobserve, sdobserve) That approach is fine as well, however it wouldn't be much different than using a tuple. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] vpython compatibility
On Wed, Jun 10, 2009 at 1:52 PM, robertorobert...@gmail.com wrote: and last question: may python 3.0 and 2.6 be installed on the same pc ? Yes, no problem. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] vpython compatibility
On Sun, Jun 7, 2009 at 8:05 PM, Emile van Sebilleem...@fenx.com wrote: On 6/7/2009 10:48 AM roberto said... hello i have a short question: is vpython usable in conjunction with python 3.0 ? This is likely better answered by the vpython crowd -- I've not used or previously hear of vpython, but they're rather explicit on their download pages here http://vpython.org/contents/download_windows.html and here http://vpython.org/contents/download_linux.html that they recommend python 2.5 or 2.6. and last question: may python 3.0 and 2.6 be installed on the same pc ? thank you again -- roberto ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Parse Text File
Hi Guys, I have the following text [08 Jun 2009] DSA-1813-1 evolution-data-server - several vulnerabilities {CVE-2009-0547 CVE-2009-0582 CVE-2009-0587} [etch] - evolution-data-server 1.6.3-5etch2 [lenny] - evolution-data-server 2.22.3-1.1+lenny1 [04 Jun 2009] DSA-1812-1 apr-util - several vulnerabilities {CVE-2009-0023 CVE-2009-1955} [etch] - apr-util 1.2.7+dfsg-2+etch2 [lenny] - apr-util 1.2.12+dfsg-8+lenny2 ... (and a whole lot more) I would like to parse this so I can get it into a format I can work with. I don't know anything about parsers, and my brief google has made me think im not sure I wan't to know about them quite yet! :) (It looks very complex) For previous fixed string things, i would normally split each line and address each element, but this is not the case as there could be multiple [lenny] or even other entries. I would like to parse from the date to the next date and treat that all as one element (if that makes sense) Does anyone have any suggestions - should I be learning a parser for doing this? Or is there perhaps an easier way. Tia! Stefan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Need help solving this problem
I have been teaching myself Python using a book. The chapter I am on currently, covers branching, while loops and program planning. I am stuck on on of the challenges at the end of this chapter, and I was hoping to get some help with this. Here it is: Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. I look forward to your reply that will help me understand these structures better. Sincerely, Raj ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help solving this problem
hi! This is how I would do it, but I'm still learning this too, so I'm very much open for suggestions. Cheers!! Albert-Jan import random def draw (): return random.sample([head, tail], 1) def toss (): heads, tails = 0, 0 for flip in range(100): if draw() == [head]: heads += 1 else: tails += 1 return heads, tails for attempt in range(20): print attempt:, attempt+1, heads:, toss()[0], tails:, toss()[1] --- On Wed, 6/10/09, Raj Medhekar cosmicsan...@yahoo.com wrote: From: Raj Medhekar cosmicsan...@yahoo.com Subject: [Tutor] Need help solving this problem To: Python Tutor tutor@python.org Date: Wednesday, June 10, 2009, 10:08 PM I have been teaching myself Python using a book. The chapter I am on currently, covers branching, while loops and program planning. I am stuck on on of the challenges at the end of this chapter, and I was hoping to get some help with this. Here it is: Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. I look forward to your reply that will help me understand these structures better. Sincerely, Raj -Inline Attachment Follows- ___ 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] Need help solving this problem
What you are looking at is a simulation whereby a coin having 2 outcomes (heads or tails) is flipped exactly 100 times. You need to tell how many times the coin falls heads up and how many times the coin falls tails up. First become familiar with the random module. Assign a value of 1 for heads and a value of 2 for tails. Then you are going to use a structure of the random module which will return only two possible outcomes. Either a one or a two. You are going to loop (look at range(1,101) or range(0,100). (Side question; why 101 or 0 to 100?; look closely at the meaning of the range arguments). Simply count the number of ones and the number of two's in the 100 flips then print the results. Good luck. Robert On Wed, 2009-06-10 at 13:08 -0700, Raj Medhekar wrote: I have been teaching myself Python using a book. The chapter I am on currently, covers branching, while loops and program planning. I am stuck on on of the challenges at the end of this chapter, and I was hoping to get some help with this. Here it is: Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. I look forward to your reply that will help me understand these structures better. Sincerely, Raj ___ 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] Parse Text File
On Wed, Jun 10, 2009 at 12:44 PM, Stefan Lesicnikste...@lsd.co.za wrote: Hi Guys, I have the following text [08 Jun 2009] DSA-1813-1 evolution-data-server - several vulnerabilities {CVE-2009-0547 CVE-2009-0582 CVE-2009-0587} [etch] - evolution-data-server 1.6.3-5etch2 [lenny] - evolution-data-server 2.22.3-1.1+lenny1 [04 Jun 2009] DSA-1812-1 apr-util - several vulnerabilities {CVE-2009-0023 CVE-2009-1955} [etch] - apr-util 1.2.7+dfsg-2+etch2 [lenny] - apr-util 1.2.12+dfsg-8+lenny2 ... (and a whole lot more) I would like to parse this so I can get it into a format I can work with. I don't know anything about parsers, and my brief google has made me think im not sure I wan't to know about them quite yet! :) (It looks very complex) For previous fixed string things, i would normally split each line and address each element, but this is not the case as there could be multiple [lenny] or even other entries. I would like to parse from the date to the next date and treat that all as one element (if that makes sense) Does anyone have any suggestions - should I be learning a parser for doing this? Or is there perhaps an easier way. Tia! Stefan Hello, maybe if you would show a sample on how you would like the ouput to look like it could help us give more suggestions. Regards, Eduardo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help solving this problem
Hi Raj, I'm another learner, I used the following: def toss(n): heads = 0 for i in range(n): heads += random.randint(0,1) return heads, n-heads print %d heads, %d tails % toss(100) Best of luck in your python endeavors! 2009/6/10 Raj Medhekar cosmicsan...@yahoo.com: I have been teaching myself Python using a book. The chapter I am on currently, covers branching, while loops and program planning. I am stuck on on of the challenges at the end of this chapter, and I was hoping to get some help with this. Here it is: Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. I look forward to your reply that will help me understand these structures better. Sincerely, Raj ___ Tutor maillist - tu...@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python and serial port
Ranjeeth P T ranjeeth_gecm...@yahoo.com wrote I am new to python i want to communicate i.e send and receive b/n an arm device and pc via a serial port, and Jacob Mansfield cyberja...@googlemail.com wrote does anyone know how to make a parallel or serial interface with respective software, i would prefer parallel because it is easy to utilise It never fails to amaze me how often a subject can be untouched on this list for months then come up twice in the same day from two different places. Bizarre, Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] gui
thx lol fixed part of the problem To: tutor@python.org From: lie.1...@gmail.com Date: Wed, 10 Jun 2009 13:24:48 +1000 Subject: Re: [Tutor] gui Essah Mitges wrote: 1. Traceback (most recent call last): 2. File C:\Users\John Doe\Desktop\D-Day\back.py, line 47, in 3. main() 4. File C:\Users\John Doe\Desktop\D-Day\back.py, line 37, in main 5. elif sbut.clicked(k.pos): 6. File C:\Users\John Doe\Desktop\D-day\but.py, line 200, in clicked 7. subprocess.Popen([D-Day, Destruction.py]) 8. File C:\Python26\lib\subprocess.py, line 595, in __init__ 9. errread, errwrite) 10. File C:\Python26\lib\subprocess.py, line 804, in _execute_child 11. startupinfo) 12. WindowsError: [Error 2] The system cannot find the file specified The error in readable form Readable doesn't mean it have to be colored and line numbered, although this is more readable than the previous one -- at least on a newsreader that supports HTML -- it's better to keep messages in plain text (i.e. not only unformatted text but change the newsreader's settings to pure, plain text) All right to the problem, the problem is not related to pygame at all; it's in your subprocess.Popen() call. The traceback says that subprocess.Popen cannot find the executable/script that would be run. A quick look at the traceback: subprocess.Popen([D-Day, Destruction.py]) That line is executing an executable/script named D-Day and pass an argument Destruction.py to it. Probably not something you wanted to do. What you want to do is something like: subprocess.Popen([D-Day\Destruction.py]) or perhaps: subprocess.Popen([python, D-Day\Destruction.py]) depending on whether the file association is setup correctly and whether the shell's search path is set to search python's install directory. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _ Internet explorer 8 lets you browse the web faster. http://go.microsoft.com/?linkid=9655582 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] GUI recommendations/tutorials?
taserian taser...@gmail.com wrote My problem is that I have no GUI experience outside of Visual Studio-style drag-and-drop IDEs. Which Python GUI system would you recommend for neophytes that would allow line drawing and a simple graphic load of a honeycomb structure in a JPG, for example, as a background? The two most common Python GUI frameworks are Tkinter (in the standard library) and wxPython - an add on. Both have a canvas widget that will cater to your requirements fairly easily. Another approach might be to investigate pygame since it excells at graphics. There are a couple of other options too but I suspect a simple canvas widget is nearly all you need and Tkinter or wxPython will both procvidfe that. There are several tutorials (and at least 1 book) for either option. The GUI programming topic on my tutorial will give you the very bare bones and show an example in both frameworks for comparison. -- 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
Re: [Tutor] Need help solving this problem
Raj Medhekar wrote: I have been teaching myself Python using a book. The chapter I am on currently, covers branching, while loops and program planning. I am stuck on on of the challenges at the end of this chapter, and I was hoping to get some help with this. Here it is: Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. I look forward to your reply that will help me understand these structures better. Sincerely, Raj ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor I am learning also, I came up with; #!/usr/bin/python import random random = random.Random() choice = ['heads', 'tails'] head_wins = 0 tail_wins = 0 def coin_flip(): flip = random.choice(choice) global head_wins global tail_wins if flip == 'heads': head_wins += 1 elif flip == 'tails': tail_wins += 1 def number_flips(): for i in range(100): coin_flip() number_flips() print 'Head Total Wins =', head_wins print 'Tail Total Wins =', tail_wins -- Powered by Gentoo GNU/Linux http://linuxcrazy.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need help solving this problem
Raj Medhekar cosmicsan...@yahoo.com wrote Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. You also need to understand the concept of variables as data stores. And you will probably need to use a mechanism to generate random values. The random module will help or you can simply read the time and strip off the last two digits - that will be good enough for your purposes! Otherwise take a look at my tutorial for the various topics Raw Materials - variables and data Loops Branches File handling - for a very brief intro to reading the time 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
Re: [Tutor] file/subprocess error
On Wed, Jun 10, 2009 at 4:00 PM, Essah Mitges e_mit...@hotmail.com wrote: So no one is confused about the error i screenshot it I am not sure of the problemWhen I run the game outside the menu it works fine but when I call it as a child window it start then the modules attached cannnot load the games images which couse this error is there a subprocess command to fix thisTried python.org btw The last error specifically tells you what it is and what is wrong: pygame.error: Couldn't open data\up-1-.png it can't find that file. Are you sure it exists? HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess/files help
On Wed, Jun 10, 2009 at 4:21 PM, Essah Mitges e_mit...@hotmail.com wrote: The problem I am have now is that once my game is initiated from the menu file the modules that are with cannot import the imagesthe folder looks like thisWODDSdataAll images and sound for gamegamelib ObjectsUtilities___init___WODDS.py Png error file attachedAny one know the code in subprocesses to fix this The problem has nothing to do with subprocess (and in the future please combine your questions into one email). As I mentioned before it's specifically looking for a file data/up-1.png which either doesn't exist or permissions are wrong. Remember, relative paths are not absolute. On *nix, /home/user/file/image.jpg is an absolute reference. No matter where you execute a program it will be able to find it. On Windows you would see something like C:\Documents and Settings\Users\MyGuy\MyFile\image.jpg A relative path would be, as the name suggests, relative. files/image.jpg will access a different location on the disk depending on where you are. Take a look at this that specifically deals with web programming but is applicable. http://www.communitymx.com/content/article.cfm?cid=230ad HTH ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] subprocess/files help
game runs fine out of the WODDS.py it when I start it from the menu lies the problemup-1.png is the first pic file used in the program so I'm guessing that all of the imported files from data have a problem if i took away up-1 up-2 would start a problem then side-1 and so on From: sri...@gmail.com Date: Wed, 10 Jun 2009 17:16:43 -0500 Subject: Re: [Tutor] subprocess/files help To: e_mit...@hotmail.com CC: tutor@python.org On Wed, Jun 10, 2009 at 4:21 PM, Essah Mitges wrote: The problem I am have now is that once my game is initiated from the menu file the modules that are with cannot import the imagesthe folder looks like thisWODDS data All images and sound for game gamelib Objects Utilities ___init___ WODDS.py Png error file attachedAny one know the code in subprocesses to fix this The problem has nothing to do with subprocess (and in the future please combine your questions into one email). As I mentioned before it's specifically looking for a file data/up-1.png which either doesn't exist or permissions are wrong. Remember, relative paths are not absolute. On *nix, /home/user/file/image.jpg is an absolute reference. No matter where you execute a program it will be able to find it. On Windows you would see something like C:\Documents and Settings\Users\MyGuy\MyFile\image.jpg A relative path would be, as the name suggests, relative. files/image.jpg will access a different location on the disk depending on where you are. Take a look at this that specifically deals with web programming but is applicable. http://www.communitymx.com/content/article.cfm?cid=230ad HTH _ Internet explorer 8 lets you browse the web faster. http://go.microsoft.com/?linkid=9655582 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file/subprocess error
Essah Mitges e_mit...@hotmail.com wrote So no one is confused about the error i screenshot it Thanks. I am not sure of the problem It says it can't find the file. Does a file C:\Users\John Doe\Desktop\WODDS\WODDS\gamelib\data\up-1.png actually exist? And is it readable by the user running the program? When I run the game outside the menu it works fine Are you running it from the same directory? but when I call it as a child window it start then the modules attached cannnot load the games images which couse this error is there a subprocess command to fix this No, you need to set up the correct environment for the game to run before calling subprocess. However as I and others have pointed out this is almost certainly the wrong way to approach your problem, even if you can get it to work! You would be better putting the game code into a function in Utilities.py and then importing that into your menu module. You can then call the game function using import Utilities # menu code here Utilities.startGame() And so that you can still ru n it as Utilities.py add a clause at the end of IUtilities.py like if __name__ == __main__: startGame() 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
Re: [Tutor] Need help solving this problem
Raj Medhekar wrote: I have been teaching myself Python using a book. The chapter I am on currently, covers branching, while loops and program planning. I am stuck on on of the challenges at the end of this chapter, and I was hoping to get some help with this. Here it is: Write a program that flips a coin 100 times and the tells you the number of heads and tails. I have tried to think about several ways to go about doing this but I have hit a wall. Even though I understand the general concept of branching and looping, I have been having trouble writing a program with these. I look forward to your reply that will help me understand these structures better. Sincerely, Raj ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor A very simple solution import random # you need to import this module to generate random # numbers heads = 0; #init number of heads; tails = 0; #init number of tails; cnt = 0 # variable to store number of coin tosses while cnt100: # we want this loop to 100 times toss = random.randrange(0,2,1) # this line will randomly choose # between 0 and 1 if toss == 0: tails += 1 # if the random generator gives 0, then we increase # count of tail by one else: heads += 1 # if the random generator gives 1, then we increase # count of head by one cnt += 1 # increase count of coin toss by one print Number of heads, heads # print the number of heads print Number of tails, tails # print the number of tails raw_input(\nPress enter to exit) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] file/subprocess error
But will it work I run 3 module for this game utilites is just 1 To: tutor@python.org From: alan.ga...@btinternet.com Date: Wed, 10 Jun 2009 23:57:35 +0100 Subject: Re: [Tutor] file/subprocess error Essah Mitges wrote So no one is confused about the error i screenshot it Thanks. I am not sure of the problem It says it can't find the file. Does a file C:\Users\John Doe\Desktop\WODDS\WODDS\gamelib\data\up-1.png actually exist? And is it readable by the user running the program? When I run the game outside the menu it works fine Are you running it from the same directory? but when I call it as a child window it start then the modules attached cannnot load the games images which couse this error is there a subprocess command to fix this No, you need to set up the correct environment for the game to run before calling subprocess. However as I and others have pointed out this is almost certainly the wrong way to approach your problem, even if you can get it to work! You would be better putting the game code into a function in Utilities.py and then importing that into your menu module. You can then call the game function using import Utilities # menu code here Utilities.startGame() And so that you can still ru n it as Utilities.py add a clause at the end of IUtilities.py like if __name__ == __main__: startGame() 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 _ Create a cool, new character for your Windows Live™ Messenger. http://go.microsoft.com/?linkid=9656621 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Syntax Error First Example
Hi, Just opened the book Python Programming, Second Edition by Michael Dawson and have my first question. Instead of the usual Hello World as the first example he asked to type this: print Game Over raw input(\n\nPress the enter key to exit.) First, I am suppose to put this in the script mode vs the IDLE mode correct? He failed to mention where.. Also, I get a syntax error at input? Since its my first day/hour I don't know how to debug and its typed in exactly as he wrote it... Finally, I'm running Python 2.6 on Vista. It loaded but the book did not mention Vista it only went up to XP. Is that ok? Any help would be appreciated. -- Randy Trahan Owner, BullDog Computer Services, LLC 478-396-2516 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Syntax Error First Example
Randy Trahan wrote: Hi, Just opened the book Python Programming, Second Edition by Michael Dawson and have my first question. Instead of the usual Hello World as the first example he asked to type this: print Game Over raw input(\n\nPress the enter key to exit.) Try raw_input(\n\nPress the enter key to exit.) First, I am suppose to put this in the script mode vs the IDLE mode correct? He failed to mention where.. Also, I get a syntax error at input? Since its my first day/hour I don't know how to debug and its typed in exactly as he wrote it... Finally, I'm running Python 2.6 on Vista. It loaded but the book did not mention Vista it only went up to XP. Is that ok? Any help would be appreciated. -- Randy Trahan Owner, BullDog Computer Services, LLC 478-396-2516 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Syntax Error First Example
On Wed, Jun 10, 2009 at 9:12 PM, bob gailer bgai...@gmail.com wrote: Randy Trahan wrote: snip First, I am suppose to put this in the script mode vs the IDLE mode correct? He failed to mention where.. It really doesn't matter - although presumably he meant you to write a script instead of in the shell/interactive interpreter (the prompt starting ) Also, I get a syntax error at input? Since its my first day/hour I don't know how to debug and its typed in exactly as he wrote it... Finally, I'm running Python 2.6 on Vista. It loaded but the book did not mention Vista it only went up to XP. Is that ok? Python works(ed?) fine on my computer when I ran Vista. As long as you keep to the 2.XX series of Python you shouldn't have too much trouble picking up python - it's really only if you start switching to Python 3 that you'll have a problem - specifically a lot of statements have turned into functions... but that's a discussion for a different day :) HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor