Re: [Tutor] my first project: a multiplication trainer
"Guba" <[EMAIL PROTECTED]> wrote > I want to create a simple multiplication trainer which quizzes me on > the > multiplication table. All multiplication combinations should be > asked > once, without repetition. > > Here my pseudo code: > I would very much appreciate if you could comment on/criticise my > pseudo > code. In particular: is my approach correct, or would it be more > sensible to first generate (or supply?) all possible questions and > then > select the ready questions randomly? Personally I'd go for the second approach as being much simpler. Once you have a list tthere are tools to get random selections from that or, even easier, to shuffle them into random order before selection. That will make the code much easier to write I think. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: my first project: a multiplication trainer
Forgot to Reply All... -- Forwarded message -- From: Marc Tompkins <[EMAIL PROTECTED]> Date: Sat, Mar 15, 2008 at 2:13 AM Subject: Re: [Tutor] my first project: a multiplication trainer To: Guba <[EMAIL PROTECTED]> On Fri, Mar 14, 2008 at 9:43 PM, Guba <[EMAIL PROTECTED]> wrote: > I want to create a simple multiplication trainer which quizzes me on the > multiplication table. All multiplication combinations should be asked > once, without repetition. > ... I would very much appreciate if you could comment on/criticise my pseudo > code. In particular: is my approach correct, or would it be more > sensible to first generate (or supply?) all possible questions and then > select the ready questions randomly? > Your pseudo code doesn't guarantee that all questions will be asked. I think the only way to guarantee that is to generate the list of possibles first. Myself, I have a horrible time writing pseudocode without slipping into real-code syntax, so please bear with me: import random# need this for the randrange() function possibleQuestions = [(x,y) for x in range(1,10) for y in range(1,10)] # list comprehension - creates a list of tuples from (1,1) through (9,9) while len(possibleQuestions) > 0: question = possibleQuestions.pop(random.randrange (len(possibleQuestions))) # pop() returns the given item and deletes it from list (do the rest of your stuff here) Hope that helps. -- www.fsrtechnologies.com -- www.fsrtechnologies.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] my first project: a multiplication trainer
The basic approach I use in these sorts of problems is to generate the choices, remove them from a list as they are asked, and then stop when this list is empty. If you don't need the list of questions afterwards, this will work: from random import choice questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] false_answers = [] while questions: q = choice(questions) del questions[questions.index(q)] # stuff If you'd like to keep the original question list, make a proxy list, and choose from that: questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] false_answers = [] choices = range(len(questions)) while choices: proxyq = choice(choics) del choices[choices.index(proxyq)] q = questions[proxyq] # stuff Cheers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] my first project: a multiplication trainer
Chris Fuller wrote: > The basic approach I use in these sorts of problems is to generate the > choices, remove them from a list as they are asked, and then stop when this > list is empty. > > > If you don't need the list of questions afterwards, this will work: > > from random import choice > > questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] > false_answers = [] > > while questions: >q = choice(questions) >del questions[questions.index(q)] > ># stuff > > > If you'd like to keep the original question list, make a proxy list, and > choose from that: > > questions = [ [i,j] for i in range(1,10) for j in range(1,10) ] > false_answers = [] > > choices = range(len(questions)) > > while choices: >proxyq = choice(choics) >del choices[choices.index(proxyq)] > >q = questions[proxyq] > ># stuff > Considering the fact that choices[x] == x, shouldn't it be : del choices[proxyq] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] my first project: a multiplication trainer
Guba wrote: > Hello everybody, > > I want to create a simple multiplication trainer which quizzes me on the > multiplication table. All multiplication combinations should be asked > once, without repetition. I would - create the list of questions - random.shuffle the list - iterate over the questions in the list with a for loop Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: my first project: a multiplication trainer
Marc Tompkins wrote: > Myself, I have a horrible time writing pseudocode without slipping into > real-code syntax Me too - often Python is more concise, precise and expressive than English for expressing an algorithm. > while len(possibleQuestions) > 0: could be simply while possibleQuestions: Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] my first project: a multiplication trainer
Ricardo Aráoz wrote: > Considering the fact that choices[x] == x, Only until the first delete (that is not at the end). > shouldn't it be : > del choices[proxyq] No. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] my first project: a multiplication trainer
> Considering the fact that choices[x] == x, shouldn't it be : > del choices[proxyq] choices = [9,2,1,3,6,4,7,8,5,0] for idx, x in enumerate(choices): print idx == x False False False True False False False False False False Not always. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] login
I am trying to get the cookies from the site when I login, though html.info(). The problem is that when I check the source ( html.read() ) it shows that it does not recognize me as logged in. Also, if I chech html.info(), the cookies that I am suppose to receive, if I logged in successfully, are not there. What am I doing wrong?import urllibimport urllib2opener = urllib2.build_opener()opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12'), ('Referer', 'http://www.site.org/index.php') ]values = urllib.urlencode({'user_name': 'MyUsername', 'user_pass': 'MyPass^^', 'login' : 'Login'})req = urllib2.Request('http://www.site.org/index.php', values)html = opener.open(req)print html.info()print html.read()html.close() Looking for last minute shopping deals? Find them fast with Yahoo! Search. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] my first project: a multiplication trainer
Kent Johnson wrote: > Ricardo Aráoz wrote: >> Considering the fact that choices[x] == x, > > Only until the first delete (that is not at the end). > >> shouldn't it be : >> del choices[proxyq] > > No. > > Kent > Ooops! Missed that one, sorry. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] login
SwartMumba snake wrote: > I am trying to get the cookies from the site when I login, though > html.info(). The problem is that when I check the source ( html.read() ) > it shows that it does not recognize me as logged in. Also, if I chech > html.info(), the cookies that I am suppose to receive, if I logged in > successfully, are not there. What am I doing wrong? urllib2 does not support cookies by default, you have to configure it with a CookieJar: import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) Then use this opener as below. I think you will have to look at the CookieJar to see the cookies. Kent > opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT > 6.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12'), > ('Referer', 'http://www.site.org/index.php') > ] > > values = urllib.urlencode({'user_name': 'MyUsername', 'user_pass': > 'MyPass^^', 'login' : 'Login'}) > req = urllib2.Request('http://www.site.org/index.php', values) > > html = opener.open(req) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] login
Using the cookie jar is not going to solve my problem. I don't want to use the cookie jar. I just want to send the right request so that I will be sent back the right header, which will contain the information that I want. Apparently I am not sending the right request because the header that I am receieving does not have the "Set-Cookie"s that I want. i.e. I am being recognized as not logged in (non member etc).--- On Sat, 3/15/08, Kent Johnson <[EMAIL PROTECTED]> wrote: From: Kent Johnson <[EMAIL PROTECTED]> Subject: Re: [Tutor] login To: [EMAIL PROTECTED] Cc: Tutor@python.org Date: Saturday, March 15, 2008, 11:44 AM SwartMumba snake wrote: > I am trying to get the cookies from the site when I login, though > html.info(). The problem is that when I check the source ( html.read() ) > it shows that it does not recognize me as logged in. Also, if I chech > html.info(), the cookies that I am suppose to receive, if I logged in > successfully, are not there. What am I doing wrong? urllib2 does not support cookies by default, you have to configure it with a CookieJar: import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) Then use this opener as below. I think you will have to look at the CookieJar to see the cookies. Kent > opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT > 6.0; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12'), > ('Referer', 'http://www.site.org/index.php') > ] > > values = urllib.urlencode({'user_name': 'MyUsername', 'user_pass': > 'MyPass^^', 'login' : 'Login'}) > req = urllib2.Request('http://www.site.org/index.php', values) > > html = opener.open(req) Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hypotenuse
bob gailer wrote: > Robert Childers wrote: >> I have rewritten my "hypotenuse" program as follows:>>> #This program >> calculates the width and diagonal of a golden rectangle > print "Calculate the width and diagonal of a golden rectangle." >> Calculate the width and diagonal of a golden rectangle. > height = input ("Input height:") >> Input height:1 > width = height*1.618 > print "Width:", width >> Width: 1.618 > import math > hyp_squared = height**2 + width**2 > hypotenuse = math.sqrt(hyp_squared) > print "Diagonal:", hypotenuse >> Diagonal: 1.90208412012 >> >> When I save the program then try to run the module I get an error >> message that it is invalid. > > Please ALWAYS post the code and the traceback. Otherwise we have no way > to easily help you. > > But I will take a guess that you saved the contents of the interactive > session and tried to run that. That will not work, as the interactive > session is full of >>> and results of print statements. > > So I suggest you edit the module to see if this is the case; if it is > then remove all the junk so you just have pure Python. Run that. If you > still get errors post the code and traceback. > Yes like Bob says you most likly saved the interactive session. What you should do is open IDLE as usual, and *before* you start typing you program, you should open a "new wind" from the file menu. This should open a blank sheet, into which you can type your program, just as you did before (but without the >>>). When you have done that, save the file and *remember* to add ".py" to the filename (without the quotes), then press the F5 key to run the program. Happy programming. BR Ole Jensen ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] login
SwartMumba snake wrote: > Using the cookie jar is not going to solve my problem. I don't want to > use the cookie jar. I just want to send the right request so that I will > be sent back the right header, which will contain the information that I > want. Apparently I am not sending the right request because the header > that I am receieving does not have the "Set-Cookie"s that I want. i.e. I > am being recognized as not logged in (non member etc). How do you normally log on with a browser? There are two common methods - basic authentication - this is where the browser pops up a window where you enter your user name and password. This type of authentication is part of the HTTP protocol. It is supported in urllib2 with the HTTPBasicAuthHandler. - forms-based auth - this is where the web site puts up a form. In this case you have to post your credentials to the form. In either case, if you want to make subsequent requests to the site with urllib2, as an authenticated user, you should use the CookieJar as I showed you. The cookie jar remembers the cookie and subsequent requests with the same opener will send the cookie for you. You don't have to be concerned with the headers at all. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parsing DICOMRT file
Haven't had a chance to look at this in a while. On Wed, Dec 12, 2007 at 6:57 PM, John Fouhy <[EMAIL PROTECTED]> wrote: > On 13/12/2007, Bryan Fodness <[EMAIL PROTECTED]> wrote: > > I am new to doing anything like this. I have looked at > > http://www.leadtools.com/SDK/Medical/DICOM/ltdc1.htm and am > > not sure how to proceed. > > I haven't much experience here, but this is how I'd proceed, I think: > > 1. Start by reading the file. It's binary data (I guess) so there's > no point in reading lines.: > rawData = open('file.dcm', 'rb').read() > > 2. Write a function to parse the preamble: > > def parsePreamble(data): >preamble = data[:128] >dicm = data[128:132] > ># you might need to read up on encodings and things to make sure > this test is valid >if dicm == 'DICM': > return preamble, 132 >else: > raise NotAPreambleException This satisfies the if statement. > > > 3. Write functions to parse data elements. The functions are going to > try to parse a data element starting at a particular position, and if > successful, return the position of the end of the element. > > def parseDataelement(data, start): ># do stuff -- the web page you linked didn't have enough information > here >return element, pos I would like to extract 10-20 values from the file. Starting at byte 132, the data elements are specified in the Explicit VR little endian transfer syntax with a group number of 0002. The data element (0002, 0010) contains the Transfer Syntax UID, which specifies how the data elements following the file meta information are encoded. For this one, it is 1.2.840.10008.1.2 which is equal to LittleEndianImplicit. where there is the 2-byte group number, a 2-byte element number, a 4-byte value length (VL) field, and a value field containing VL bytes. Could someone help me get started. I did an xml dump with another program and got, PHOTON as an output example. > > > 4. Parse the whole thing; > > def parseDICOM(data): >elements = [] >try: > preamble, next = parsePreamble(data) >except NotAPreambleException: > preamble, next = None, 0 > >while True: > element, next = parseDataElement(data, next) > elements.append(element) > # you will need some way of breaking out of this loop, either by > checking the structure of > # element for an end condition, or by parseDataElement raising > an exception. > >return elements # and maybe preamble too if you want it > > HTH! > -- "The game of science can accurately be described as a never-ending insult to human intelligence." - João Magueijo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] signal trapping in a class instance
Hi all, I have a series of class instances saved in an array. I need the instances to respond to a SIGKILL by writing to a file and sys.exit()-ing. Am I right in codeing it as below ? ... does the sys.exit() kill the instance or the instance & the instance holding array definition above it ? Cheers Dave def signal_kill(self, signum, frame): """ On SIGKILL update journal_snap with a special #$86400 'no snapshot' string """ now_secs = time.strftime('%H') * 60 * 60 now_secs = time.strftime('%M') * 60 + now_secs now_secs = time.strftime('%S') + now_secs update_journal(self, time.strftime('%Y%m%d'), self.feed, now_secs, 86400) sys.exit() -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] signal trapping in a class instance
SIGKILL is not trappable. You probably want SIGTERM. Furthermore, this signal will be sent to the process, not some thread or class instance within a process. Maybe you need some other mechanism? Is the signal going to be from the same python process? If so, just call it directly. Otherwise, there are a great deal of other interprocess communications options. Sockets are probably the most cross platform nd widely understood. Check out the UDPServer class in the standard library. You'd need to write a client script to send the commands, but this is trivial once you have the server set up. Cheers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] signal trapping in a class instance
I read your post again, and it looks as though you might want to use the atexit module. Another idea would be to trap the SIGTERM signal and to keep a registry of instances, and then to invoke a cleanup method of each instance. Another important note: trapping signals will have no effect if your process terminates itself. Cheers ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] noob python cgi
Hi, I'm writing a webpage as a learning exercise. My first objective is to allow myself to upload files to directories in /images/, and have cgi scripts automatically generate the pages that will allow users to navigate through the images. I have a very basic prototype that does what I want, at least for a website served by Apache on my laptop (not web-accessible). Any comments or feedback on the sanity of this approach, or ways to improve it generally would be appreciated! I understand what I've done, but I have no idea what other approaches there might be. I'd like to avoid a complicated CMS at this point, as I want to learn about the basics of serving up webpages. Three files follow. First, the html index page, followed by the gallery picker, followed by the thumbnail displayer. Thanks! Tyler index: My home page Home Only one thing to do - visit the http://localhost/tycgi-bin/gallery.py";>galleries. gallery picker: #! /usr/bin/python import cgitb; cgitb.enable() import cgi, os print """Content-type: text/html Galleries Select a gallery: """ for gal in os.listdir("../images/"): print '%s' % gal print """ """ thumbviewer: #! /usr/bin/python import cgitb; cgitb.enable() import cgi, os form = cgi.FieldStorage() gal = form["gallery"].value print """Content-type: text/html """ print '%s' % gal print""" %s gallery:""" % gal for file in os.listdir("".join(("../images/", gal))): print 'http://localhost/~tyler/images/%s/%s";>' % (gal, file) print "" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] noob python cgi
Tyler Smith wrote: > Hi, > [snip explanation] > Three files follow. First, the html index page, followed by the > gallery picker, followed by the thumbnail displayer. > > Thanks! > > Tyler > [snip code] > In the future please include your code as attachments, to avoid e-mail programs mangling the code, unless it's just a few lines. Thanks, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Working with Python Objects
Alan/Greg I've combined your code fragments and added a function call too, to determine how 'a' is passed between objects and classes: def addNumbers(i, j): k = i + j return k class A: def oneA(self): z = 2 self.a = self.a * z class B: def oneB(self): inA = A() # instance of class A y = 5 b = y * inA.a c = addNumbers(y, b) Is this correct? Dinesh class A: constantA = 9 def OneOfA: a = class B: variableB = "quick brown fox" def OneOfB: b = c = b * a# the 'a' from def OneOfA in class A -- > Question: > 1) how do I access the 'a' from function (method) OneOfA in > class A so that it can be used by functions (methods) in class B? You don't and shouldn't try to. In this case because the attriute only exists inside the method, it is local, so dies when the method completes. So first of all you need to make it part of the class A. We do that by tagging it as an attribute of self, which should be the fitrst attribute of every method. But one of the concepts of OOP is to think in terms of the objects not the attributes inside them So your question should probably be: How do I access objects of class A inside methods of class B? The answer is by passing an instance into the method as a parameter. You can then manipulate the instance of A by sending messages to it. In Python you can access the instance values of an object by sending a message with the same name as the attribute - in other OOP languages you would need to provide an accessor method. But it is very important conceptually that you try to get away from thinking about accessing attributes of another object inside methods. Access the objects. Metthods should only be manipulating the attributes of their own class. To do otherwise is to break the reusability of your classes. So re writing your pseudo code: class A: constantA = 9 def OneOfA(self): # add self as first parameter self.a =# use 'self' to tag 'a' as an attribute class B: variableB = "quick brown fox" def OneOfB(self, anA):# add self and the instance of A b = c = b * anA.a# the 'a' from the instance anA This way OneOfB() only works with attributes local to it or defined as instance variables or passed in as arguments. Which is as it should be! Real OOP purists don't like direct attribute access but in Python its an accepted idiom and frankly there is little value in writing an accessor method that simply returns the value if you can access it directly. The thing you really should try to avoid though is modifying the attributes directly from another class. Normally you can write a more meaningful method that will do that for you. -- Alan Gauld Author of the Learn to Program web site Temorarily at: http://uk.geocities.com/[EMAIL PROTECTED]/ Normally: http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pydoc introspecting info via OptionParser?
On Fri, Mar 14, 2008 at 10:43:08AM -0700, Neal McBurnett wrote: > I'm trying to do nice clean documentation for a python script I run > from the command-line, and I'd like pydoc or a similar program to > document it well. But I don't want to duplicate option information by > putting it both in my docstring and in optparse. > > I would think that pydoc might notice an OptionParser instance at the > module level and show the options defined there, but it doesn't seem > to. Would it be hard to add to pydoc? Do any other documentation > programs do that? For now I've instead put this quasi-template-tag in my docstring in an appropriate place: %InsertOptionParserUsage% and added this code to the module to incorporate the usage into the docstring after it is defined: # incorporate OptionParser usage documentation in our docstring __doc__ = __doc__.replace("%InsertOptionParserUsage%\n", parser.format_help()) That gets me pretty close. The biggest problem is that when pydoc prints it, the usage statement starts with "Usage: pydoc [options]" rather than "Usage: myprogram [options]". I could set the OptionParser "prog" option to override that, but I prefer that in real life the program provide usage referencing sys.argv[0] rather than hard-coding it, in case it gets deployed under a different name. Comments? Neal McBurnett http://mcburnett.org/neal/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [tutor] PyGame tutorials
Hello all, I have learnt python and wxPython. Now i want to learn making games using pygame engine. Can anyone tellme from where i can learn pygame and start making basic games using this module. Which version i should download and is there any user group like this one for pyGame ?? thanks, -- Varsha Purohit ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor