From emile at fenx.com Thu Dec 1 05:15:59 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 30 Nov 2011 20:15:59 -0800 Subject: [Tutor] pass tuples to user defined function(beginner) In-Reply-To: <4ED57C65.6040507@davea.name> References: <4ED45EC6.3030101@gmail.com> <4ED4CB2D.8060209@pearwood.info> <4ED4D7F8.5000507@pearwood.info> <4ED567CE.1070405@davea.name> <4ED56D7C.1020708@fenx.com> <4ED57C65.6040507@davea.name> Message-ID: On 11/29/2011 4:44 PM Dave Angel said... > Any chance you were a customer or vendor of Wang? That 80mb drive, > dumbed down, for prices around $20k, rings a bell. That was around 1980 as an ISV -- a Basic Four 610 -- we paid I think $50k? retailed at $70k. 8 user, 256k memory, two 35Mb drives that for $15k a piece you could get the tech to come out and clip the strap on the high order bit of the address space register which would double the usable space. Kinda like getting a discount on a caddy but they deliver the car with the back doors welded shut. Emile From steve at pearwood.info Thu Dec 1 01:49:39 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 01 Dec 2011 11:49:39 +1100 Subject: [Tutor] is there a better way to organise this code In-Reply-To: References: Message-ID: <4ED6CF23.8070408@pearwood.info> Norman Khine wrote: > hello, > > is there a better way to organise this code or optimise it. > http://pastie.org/2944797 Is that a question? Because I get a syntax error in my brain when I parse it without the question mark. Sorry to pick on you, but it astonishes me when people don't bother with basic English syntax, and yet try writing code where syntax is *much* more important. If they can't be bothered with writing correct English, that sends all the wrong signals about the quality of their code. You should write as if you were coding, otherwise people will assume you code like you write. Laziness is one of the cardinal virtues of the programmer, but it has to be the right sort of laziness. "Don't reinvent the wheel, use an existing library" is good laziness. "Leave out required syntax elements and hope someone else will fix them" is not. Before worrying about optimising the code, how about checking whether it works? (1) What is CSVFile? It appears to be a class, because you inherit from it, but it isn't defined anywhere and isn't a builtin. So your code fails on the very first line. (2) You have a class WorldSchema with no methods, and a top-level function get_world that *looks* like a method because it has an argument "self", but isn't. The indentation is wrong. See what I mean about syntax? Syntax is important. So is get_world a wrongly indented method, or a poorly written function? (3) Since get_world doesn't use "self" at all, perhaps it should be a top-level function of no arguments? Or perhaps a static method of WorldSchema? (4) You have a class called "getCountries", which seems to be a poor name for a class. In general, classes should be *things*, not *actions*. Also I recommend that you follow PEP 8 for naming conventions. (Google "PEP 8" if you don't know what I mean, and remember, it isn't compulsory, but it is recommended.) A better name might be CountryGetter. (5) The use of classes appears on first reading to be a Java-ism. In Java, everything must be a class Just Because The Powers Who Be Said So. In Python, we are allowed, and encouraged, to mix classes and functions. Use the right tool for the job. But without any idea of the broader context, I have no idea if classes are appropriate or not. (6) getCountries has a method called get_options. Based on the name, a reasonable reader would assume it returns some sort of list or dictionary of options, right? But according to the documentation, it actually returns a JSON "ser", whatever that is. Server? Service? Serialization (of what)? Something else? (7) Other problems: Enumerate, MSG and iana_root_zone are used but not defined anywhere. Documentation is lacking, so I don't understand what the code is intended to do. Another class with a poor name, "getRegions". There may be others, but I stopped reading around this point. -- Steven From d at davea.name Thu Dec 1 02:46:34 2011 From: d at davea.name (Dave Angel) Date: Wed, 30 Nov 2011 20:46:34 -0500 Subject: [Tutor] is there a better way to organise this code In-Reply-To: <4ED6CF23.8070408@pearwood.info> References: <4ED6CF23.8070408@pearwood.info> Message-ID: <4ED6DC7A.9080001@davea.name> On 11/30/2011 07:49 PM, Steven D'Aprano wrote: > Norman Khine wrote: >> hello, >> >> is there a better way to organise this code or optimise it. >> http://pastie.org/2944797 > > Is that a question? Because I get a syntax error in my brain when I > parse it without the question mark. > > Sorry to pick on you, but it astonishes me when people don't bother > with basic English syntax, and yet try writing code where syntax is > *much* more important. If they can't be bothered with writing correct > English, that sends all the wrong signals about the quality of their > code. > > You should write as if you were coding, otherwise people will assume > you code like you write. > > Laziness is one of the cardinal virtues of the programmer, but it has > to be the right sort of laziness. "Don't reinvent the wheel, use an > existing library" is good laziness. "Leave out required syntax > elements and hope someone else will fix them" is not. > > Before worrying about optimising the code, how about checking whether > it works? > > (1) What is CSVFile? It appears to be a class, because you inherit > from it, but it isn't defined anywhere and isn't a builtin. So your > code fails on the very first line. > > (2) You have a class WorldSchema with no methods, and a top-level > function get_world that *looks* like a method because it has an > argument "self", but isn't. The indentation is wrong. See what I mean > about syntax? Syntax is important. So is get_world a wrongly indented > method, or a poorly written function? > > (3) Since get_world doesn't use "self" at all, perhaps it should be a > top-level function of no arguments? Or perhaps a static method of > WorldSchema? > > (4) You have a class called "getCountries", which seems to be a poor > name for a class. In general, classes should be *things*, not > *actions*. Also I recommend that you follow PEP 8 for naming > conventions. (Google "PEP 8" if you don't know what I mean, and > remember, it isn't compulsory, but it is recommended.) A better name > might be CountryGetter. > > (5) The use of classes appears on first reading to be a Java-ism. In > Java, everything must be a class Just Because The Powers Who Be Said > So. In Python, we are allowed, and encouraged, to mix classes and > functions. Use the right tool for the job. But without any idea of the > broader context, I have no idea if classes are appropriate or not. > > (6) getCountries has a method called get_options. Based on the name, a > reasonable reader would assume it returns some sort of list or > dictionary of options, right? But according to the documentation, it > actually returns a JSON "ser", whatever that is. Server? Service? > Serialization (of what)? Something else? > > (7) Other problems: Enumerate, MSG and iana_root_zone are used but > not defined anywhere. Documentation is lacking, so I don't understand > what the code is intended to do. Another class with a poor name, > "getRegions". There may be others, but I stopped reading around this > point. > > I stopped looking at his pastie once the background turned black. I'd have had to copy it elsewhere to even read it. -- DaveA From pasokan at talentsprint.com Thu Dec 1 05:26:54 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Thu, 1 Dec 2011 09:56:54 +0530 Subject: [Tutor] plotting in python In-Reply-To: References: Message-ID: On Thu, Dec 1, 2011 at 2:38 AM, stm atoc wrote: > Hi there, > > I have a question regarding plotting with Python. > > I have the following python script: [SNIPPED] > plot(Conc[0],z) [SNIPPED] > -------So, What would you suggest? What is the output of print len(Conc[0]), len(z) You may insert that line above the plot and see Asokan Pichai From stm.at.oc at googlemail.com Thu Dec 1 09:01:45 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Thu, 1 Dec 2011 09:01:45 +0100 Subject: [Tutor] plotting in python In-Reply-To: References: Message-ID: The output of the print len(Conc[0]), len(z) is 100 3600. Now I changed Conc[0] to Conc[1], and the output is: 100 100 But still I need to see from Concentration from 0. On Thu, Dec 1, 2011 at 5:26 AM, Asokan Pichai wrote: > On Thu, Dec 1, 2011 at 2:38 AM, stm atoc wrote: >> Hi there, >> >> I have a question regarding plotting with Python. >> >> I have the following python script: > > [SNIPPED] >> plot(Conc[0],z) > > [SNIPPED] >> -------So, What would you suggest? > > What is the output of > print len(Conc[0]), len(z) > > You may insert that line above the plot and see > > Asokan Pichai From __peter__ at web.de Thu Dec 1 09:48:43 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 01 Dec 2011 09:48:43 +0100 Subject: [Tutor] Black pastie, was Re: is there a better way to organise this code References: <4ED6CF23.8070408@pearwood.info> <4ED6DC7A.9080001@davea.name> Message-ID: Dave Angel wrote: > I stopped looking at his pastie once the background turned black. I'd > have had to copy it elsewhere to even read it. There is a combobox in the top right corner of the black area where you can select a sane theme, e. g. "IDLE". From andreas.perstinger at gmx.net Thu Dec 1 10:44:14 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 01 Dec 2011 10:44:14 +0100 Subject: [Tutor] plotting in python In-Reply-To: References: Message-ID: <4ED74C6E.20008@gmx.net> [Please don't top-post. Put your answers below the text you cite.] On 2011-12-01 09:01, stm atoc wrote: > The output of the print len(Conc[0]), len(z) is 100 3600. > Now I changed Conc[0] to Conc[1], and the output is: 100 100 So, you've changed the line print len(Conc[0]), len(z) to print len(Conc[1]), len(z) and the only thing that changed in the output is the length of "z" which is calculated independently of "Conc" in your script? This would be very strange. Does your script run if you use "Conc[1]" (or some other indexes) instead of "Conc[0]" when you call the "plot"-function? If yes, it's very likely that you have the "wrong" data in "Conc[0]". But that's impossible to tell without your data file ("ourtest_out.list"). Bye, Andreas From andreas.perstinger at gmx.net Thu Dec 1 12:39:09 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 01 Dec 2011 12:39:09 +0100 Subject: [Tutor] plotting in python In-Reply-To: References: <4ED74C6E.20008@gmx.net> Message-ID: <4ED7675D.7020404@gmx.net> [Still top-posting :-( ] On 2011-12-01 11:13, stm atoc wrote: > Well, I did also change the line in the python script to this: > > plot(Conc[0],z,'r-',label='initial') > plot(Conc[1],z,'b-',label='after 20s') > > to see both Conc[0] and [1]. And did it work? > I will send the output data attaches to this email ("ourtest_out.list"). > > I wonder if this way is fine. I'm not sure about the policy regarding attachements on this list but I think it would have been better to provide a link than attach it. Anyways, I've reduced your original script, did a test run and it works as expected (at least it shows a plot): import numpy import matplotlib.pyplot as pyplot with open("ourtest_out.list", "r") as f: z = numpy.array([float(v) for v in f.readline().split()[1:]]) a = numpy.loadtxt("ourtest_out.list", skiprows=3) N = 100 Conc = a[1:, N+1:] print len(Conc[0]) == len(z) pyplot.figure() pyplot.plot(Conc[0], z) pyplot.show() Do you still get an error? Bye, Andreas From stm.at.oc at googlemail.com Thu Dec 1 13:11:23 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Thu, 1 Dec 2011 13:11:23 +0100 Subject: [Tutor] plotting in python In-Reply-To: <4ED7675D.7020404@gmx.net> References: <4ED74C6E.20008@gmx.net> <4ED7675D.7020404@gmx.net> Message-ID: For previous script that I have written, I had trouble having one plot for all data at the same time and I could see two line for Conc[0] and Conc[1] separately. Now, even I modified Conc = a[1:, N+1:] to Conc = a[0:, N+1:], still one plot is created...which is pretty good and no error! Thank you so much, Sue On Thu, Dec 1, 2011 at 12:39 PM, Andreas Perstinger wrote: > [Still top-posting :-( ] > > > On 2011-12-01 11:13, stm atoc wrote: >> >> Well, I did also change the line in the python script to this: >> >> plot(Conc[0],z,'r-',label='initial') >> plot(Conc[1],z,'b-',label='after 20s') >> >> to see both Conc[0] and [1]. > > > And did it work? > > >> I will send the output data attaches to this email ?("ourtest_out.list"). >> >> I wonder if this way is fine. > > > I'm not sure about the policy regarding attachements on this list but I > think it would have been better to provide a link than attach it. > > Anyways, I've reduced your original script, did a test run and it works as > expected (at least it shows a plot): > > import numpy > import matplotlib.pyplot as pyplot > > with open("ourtest_out.list", "r") as f: > ? ?z = numpy.array([float(v) for v in f.readline().split()[1:]]) > > a = numpy.loadtxt("ourtest_out.list", skiprows=3) > N = 100 > Conc = a[1:, N+1:] > > print len(Conc[0]) == len(z) > > pyplot.figure() > pyplot.plot(Conc[0], z) > pyplot.show() > > Do you still get an error? > > Bye, Andreas From robert.sjoblom at gmail.com Thu Dec 1 14:15:02 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 1 Dec 2011 14:15:02 +0100 Subject: [Tutor] Prime Factorization Tool Message-ID: So I've recently started poking at the Project Euler site, because I feel that I need to practice writing code. For those of you interested in solving the problems on your own I advice you to not read this, as it will spoil the solution. Problem 3 is this: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? I came up with this pseudocode: #pseudocode: # divide by x until non-prime is found: # if not remainder: # check if it's prime or not: # if not prime: exit loop # if not prime: store in variable # increment x by 1 Here are the functions I came up with: def isprime(n): if n == 1: return False for x in range(2, n): if n % x == 0: return False else: return True def factorization(n): factor = 0 x = 2 while True: if n % x == 0: if isprime(x): factor = x else: return factor x += 1 This, however, feels horribly inefficient. Is there a better way to do it? I think most of my problems stem from my weak mathematical skills, to be honest. This wasn't too bad, but even for problems 1 and 2 I've relied on brute forcing the answer instead of looking for a mathematical solution. -- best regards, Robert S. From stm.at.oc at googlemail.com Thu Dec 1 14:30:15 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Thu, 1 Dec 2011 14:30:15 +0100 Subject: [Tutor] New plot over the old graph Message-ID: Hi there, I would like to make a new plot with new data over the old one (with old/first data) in the same condition (shape, dimensions....) for comparison and analysis data. With your help, I have a good script from the previous discussion: ********** from pylab import * import numpy import matplotlib.pyplot as pyplot import matplotlib.mlab as mlab with open("ourtest_out.list", "r") as f: z = numpy.array([float(v) for v in f.readline().split()[1:]]) a = numpy.loadtxt("ourtest_out.list", skiprows=3) N = 100 Conc = a[0:, N+1:] print len(Conc[0]) == len(z) figure() pyplot.plot(Conc[0],z,'r-',label='initial') pyplot.plot(Conc[1],z,'b-',label='after 20s') show() ********* I have tried to make subplot for this case as follows: pyplot.subplot(111) pyplot.plot(Conc[0],z,'r-',label='initial') pyplot.plot(Conc[1],z,'b-',label='after 20s') However, I am not sure how to add new data over this to make a graph including both new and old data simultaneously. I do appreciate for any advice. Thank you, Sue From pc.vries at tip.nl Thu Dec 1 15:08:51 2011 From: pc.vries at tip.nl (Paul de Vries) Date: Thu, 1 Dec 2011 15:08:51 +0100 Subject: [Tutor] twisted web client authentication? Message-ID: Hi Made something that connects to a httpserver and parses the xml stream it sends. The webserver it has to connect to uses digest authentication. The problem is I don't have a clue how to use digest auth with twisted.web.client. Couln't find any code examples for this. Can somebody help me with this? ( I'm not a python programmer so please be gentle) thanks in advance the code I put together: from twisted.internet import reactor from twisted.internet.defer import Deferred from twisted.internet.protocol import Protocol from twisted.web.client import Agent from twisted.web.http_headers import Headers from StringIO import StringIO from elementtree import ElementTree class BeginPrint(Protocol): def __init__(self, finished): self.finished = finished self.dataStream = StringIO() def dataReceived(self, bytes): display = bytes #print 'some data received:' #print display context = ElementTree.iterparse(StringIO(bytes), events = ("start", "end")) context = iter(context) event, root = context.next() for event, elem in context: if elem.tag == "Tag": print "Tag " root.clear() def connectionLost(self, reason): print 'finished receiving', reason.getErrorMessage() agent = Agent(reactor) d = agent.request('GET', 'http:someadress', Headers({'User-Agent': ['Twisted web client']}), None) def cbResponse(response): print 'Response version: ', response.version finished = Deferred() response.deliverBody(BeginPrint(finished)) return finished d.addCallback(cbResponse) reactor.run() From waynejwerner at gmail.com Thu Dec 1 15:11:23 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 1 Dec 2011 08:11:23 -0600 Subject: [Tutor] Prime Factorization Tool In-Reply-To: References: Message-ID: On Thu, Dec 1, 2011 at 7:15 AM, Robert Sjoblom wrote: > So I've recently started poking at the Project Euler site, because I > feel that I need to practice writing code. For those of you interested > in solving the problems on your own I advice you to not read this, as > it will spoil the solution. > > Problem 3 is this: > The prime factors of 13195 are 5, 7, 13 and 29. > > What is the largest prime factor of the number 600851475143 ? > > I came up with this pseudocode: > #pseudocode: > # divide by x until non-prime is found: > # if not remainder: > # check if it's prime or not: > # if not prime: exit loop > # if not prime: store in variable > # increment x by 1 > > Here are the functions I came up with: > > def isprime(n): > if n == 1: > return False > for x in range(2, n): > if n % x == 0: > return False > else: > return True > > def factorization(n): > factor = 0 > x = 2 > while True: > if n % x == 0: > if isprime(x): > factor = x > else: > return factor > x += 1 > > This, however, feels horribly inefficient. Is there a better way to do > it? I think most of my problems stem from my weak mathematical skills, > to be honest. This wasn't too bad, but even for problems 1 and 2 I've > relied on brute forcing the answer instead of looking for a > mathematical solution. Well, there are really only a couple of optimizations that you could make. That's the nice (bad?) thing about primes - you really only *can* brute force a solution. That's why nice things like encryption exist. The less obvious optimization is in reference to primes - you don't actually have to check all the way up to N. Or even N/2. You only have to check numbers up to the square root of N. This explanation may not be mathematically sound, but basically the reason this works is the definition of prime: N is divisible only by N and 1. If you divide a number by 2 then then the result will be the largest factor (e.g. 100/2 = 50). But as you start increasing the divisor then obviously the result has to decrease. The point at which these numbers are equivalent? The square root, of course. That will easily decrease the running time of your program because now instead of dividing N numbers you're dividing sqrt(N) numbers. The other optimization that you can do is in the factorization loop - you're checking all factors from 2 to N. The easiest fix here is the fact that you *know* that no even number can be a prime factor for the simple reason that it's divisible by 2. So start your loop at 3 and increment by 2 and you've just cut out half the numbers. But wait, there's more! What is the largest possible factor of a number? I'll let you think about it for a moment... Got it? Hey, no peeking! Well, I guess you can peek. N/2 is the largest possible factor. Any number larger than N/2 is somewhere between N/2 and N/1, and since there's no whole number between 2 and 1 you know that the largest number you need to check for a factor is N/2, or in the case of 100/2 = 50. So for 100, instead of checking if 100 numbers are prime, now you're only checking: 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 49 *much* fewer numbers. And for each N in that list you're only checking up to the sqrt(N). Now you've vastly improved your running time. Now, I'm not sure what the time complexity of these two operations is, but go ahead and put this line in your isprime: if n == 11: print("Checked 11... again") Can you think of a way to compute the primes you need to check only once? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Dec 1 15:45:47 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 1 Dec 2011 09:45:47 -0500 Subject: [Tutor] is there a better way to organise this code In-Reply-To: <4ED6DC7A.9080001@davea.name> References: <4ED6CF23.8070408@pearwood.info> <4ED6DC7A.9080001@davea.name> Message-ID: On Wed, Nov 30, 2011 at 8:46 PM, Dave Angel wrote: > On 11/30/2011 07:49 PM, Steven D'Aprano wrote: > >> Norman Khine wrote: >> >>> hello, >>> >>> is there a better way to organise this code or optimise it. >>> http://pastie.org/2944797 >>> >> >> Is that a question? Because I get a syntax error in my brain when I parse >> it without the question mark. >> >> Sorry to pick on you, but it astonishes me when people don't bother with >> basic English syntax, and yet try writing code where syntax is *much* more >> important. If they can't be bothered with writing correct English, that >> sends all the wrong signals about the quality of their code. >> >> You should write as if you were coding, otherwise people will assume you >> code like you write. >> >> Laziness is one of the cardinal virtues of the programmer, but it has to >> be the right sort of laziness. "Don't reinvent the wheel, use an existing >> library" is good laziness. "Leave out required syntax elements and hope >> someone else will fix them" is not. >> >> Before worrying about optimising the code, how about checking whether it >> works? >> >> (1) What is CSVFile? It appears to be a class, because you inherit from >> it, but it isn't defined anywhere and isn't a builtin. So your code fails >> on the very first line. >> >> (2) You have a class WorldSchema with no methods, and a top-level >> function get_world that *looks* like a method because it has an argument >> "self", but isn't. The indentation is wrong. See what I mean about syntax? >> Syntax is important. So is get_world a wrongly indented method, or a poorly >> written function? >> >> (3) Since get_world doesn't use "self" at all, perhaps it should be a >> top-level function of no arguments? Or perhaps a static method of >> WorldSchema? >> >> (4) You have a class called "getCountries", which seems to be a poor name >> for a class. In general, classes should be *things*, not *actions*. Also I >> recommend that you follow PEP 8 for naming conventions. (Google "PEP 8" if >> you don't know what I mean, and remember, it isn't compulsory, but it is >> recommended.) A better name might be CountryGetter. >> >> (5) The use of classes appears on first reading to be a Java-ism. In >> Java, everything must be a class Just Because The Powers Who Be Said So. In >> Python, we are allowed, and encouraged, to mix classes and functions. Use >> the right tool for the job. But without any idea of the broader context, I >> have no idea if classes are appropriate or not. >> >> (6) getCountries has a method called get_options. Based on the name, a >> reasonable reader would assume it returns some sort of list or dictionary >> of options, right? But according to the documentation, it actually returns >> a JSON "ser", whatever that is. Server? Service? Serialization (of what)? >> Something else? >> >> (7) Other problems: Enumerate, MSG and iana_root_zone are used but not >> defined anywhere. Documentation is lacking, so I don't understand what the >> code is intended to do. Another class with a poor name, "getRegions". There >> may be others, but I stopped reading around this point. >> >> >> I stopped looking at his pastie once the background turned black. I'd > have had to copy it elsewhere to even read it. > > > -- > > DaveA > > > There is a button in the upper right corner of the paste bin that lets you switch the hideous black background to something more pleasant. :) -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.hall5447 at gmail.com Thu Dec 1 16:33:18 2011 From: michael.hall5447 at gmail.com (Michael Hall) Date: Thu, 1 Dec 2011 07:33:18 -0800 Subject: [Tutor] Need help adding a funcation Message-ID: Here is the code I have written. # Create main function. def main(): a = input('Please Enter a Number: ') # Ask user for input. number = int(a) x = 1 sum_of = 0 while number > x: if number % x == 0: sum_of = sum_of + x x += 1 if sum_of == number: print(number,'is a Perfect Number') elif sum_of < number: print(number,'is a Non-perfect Number') main() Here is the problem I am having. The program works perfect but I need to add the following: # a) write a function, getDivisors(), that returns a list of all # of the positive divisors of a given number. for example - # result = getDivisors(24) # print(result) # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" # b) write a program that uses your function to determine which # numbers between 1 and 10,000 are perfect. (answer: 6, 28, 496 # and 8128 are perfect!) I know that mystring needs to be added. I need help Thank you in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Dec 1 16:51:01 2011 From: d at davea.name (Dave Angel) Date: Thu, 01 Dec 2011 10:51:01 -0500 Subject: [Tutor] Need help adding a funcation In-Reply-To: References: Message-ID: <4ED7A265.3030102@davea.name> On 12/01/2011 10:33 AM, Michael Hall wrote: > Here is the code I have written. > > # Create main function. > def main(): > a = input('Please Enter a Number: ') # Ask user for input. > number = int(a) > x = 1 > sum_of = 0 > while number> x: > if number % x == 0: > sum_of = sum_of + x > x += 1 > if sum_of == number: > print(number,'is a Perfect Number') > elif sum_of< number: > print(number,'is a Non-perfect Number') > > main() > > Here is the problem I am having. The program works perfect but I need to > add the following: > > # a) write a function, getDivisors(), that returns a list of all > # of the positive divisors of a given number. for example - > # result = getDivisors(24) > # print(result) > # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" > # b) write a program that uses your function to determine which > # numbers between 1 and 10,000 are perfect. (answer: 6, 28, 496 > # and 8128 are perfect!) > > I know that mystring needs to be added. I need help > Thank you in advance > I don't see any 'mystring' in the source or in the assignment; why would you think you need it? It asks you to write a function called getDivisors(). You have all the pieces in your present code, but it's all inline. Probably your professor wants you to learn to code in small functions, so your code is more likely to be reusable. So what part of the function description is unclear? And is it unclear because you don' t understand one of the math terms, or because you don't know how to code it? She wants a function that takes a single argument (number), and returns a list def getDivisors(number): do some stuff return mylist You'll probably want to write another one that adds up the elements of a list (or you could find it in the stdlib). Then your main should be pretty straightforward. -- DaveA From andreas.perstinger at gmx.net Thu Dec 1 18:25:30 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 01 Dec 2011 18:25:30 +0100 Subject: [Tutor] New plot over the old graph In-Reply-To: References: Message-ID: <4ED7B88A.8040002@gmx.net> On 2011-12-01 14:30, stm atoc wrote: > With your help, I have a good script from the previous discussion: > > ********** > from pylab import * Have you used MATLAB before and are used to its syntax? In general "star imports" (from xxx import *) are a bad practice and IMHO should be avoided. > import numpy > import matplotlib.pyplot as pyplot > import matplotlib.mlab as mlab These imports are unnecessary if you use the first line because "pylab" imports everything from "numpy" and "matplotlib" into a single namespace. So either use just the first line (not recommended) or the following line (recommended). See also http://matplotlib.sourceforge.net/faq/usage_faq.html#matplotlib-pylab-and-pyplot-how-are-they-related and http://matplotlib.sourceforge.net/faq/usage_faq.html#coding-styles BTW: Why do you import "mlab" when you don't use it? > with open("ourtest_out.list", "r") as f: > z = numpy.array([float(v) for v in f.readline().split()[1:]]) > > a = numpy.loadtxt("ourtest_out.list", skiprows=3) > N = 100 > Conc = a[0:, N+1:] > print len(Conc[0]) == len(z) This line was just for testing. You can delete it without any consequences. > figure() > > pyplot.plot(Conc[0],z,'r-',label='initial') > pyplot.plot(Conc[1],z,'b-',label='after 20s') > > show() Isn't that what you want? You are plotting all your data in one graph. There is a straight red line on the left side and a falling blue line from left to right. > ********* > > I have tried to make subplot for this case as follows: > > pyplot.subplot(111) > pyplot.plot(Conc[0],z,'r-',label='initial') > pyplot.plot(Conc[1],z,'b-',label='after 20s') Here you are creating a subplot with 1 plot each row and 1 plot each column, in other words you do the same as above (creating just 1 plot). If you want to have for example 4 plots in the same window with 2 each row and 2 each column you have to use pyplot.subplot(221) After plotting all the data in this first "axes" you have to switch to the next one: pyplot.subplot(222) Have you already read the matplotlib-tutorial: http://matplotlib.sourceforge.net/users/pyplot_tutorial.html > However, I am not sure how to add new data over this to make a graph > including both new and old data simultaneously. As I've said before: You are already plotting all data in one graph. Don't you get two different lines? Bye, Andreas From stm.at.oc at googlemail.com Thu Dec 1 19:20:28 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Thu, 1 Dec 2011 19:20:28 +0100 Subject: [Tutor] New plot over the old graph In-Reply-To: <4ED7B88A.8040002@gmx.net> References: <4ED7B88A.8040002@gmx.net> Message-ID: Thanks for all information/websites and advice. Yes the graph is exactly like the one you mentioned. Also, I would like to have them in one not two, but I think since the dimension of the x and y are not same, I have no choice. What I like to do now is comparing 2 (later 3 or more) different sets of data, e.g. comparison among Conc[1] with sets.... I have changed the script like this: with open("ourtest_out.list", "r") as f: z = numpy.array([float(v) for v in f.readline().split()[1:]]) a1 = numpy.loadtxt("ourtest_out1.list", skiprows=3) a2 = numpy.loadtxt("ourtest_out2.list", skiprows=3) a3 = numpy.loadtxt("ourtest_out3.list", skiprows=3) N = 100 Conc1 = a1[0:, N+1:] #base case Conc2 = a2[0:, N+1:] # Ydw=0.1 Conc3 = a3[0:, N+1:] # nuh=0.01 lw = 2.0 #linewidth dpi = 96 figure(figsize=(10,6),dpi=dpi) pyplot.subplot(111) pyplot.plot(Conc1[1], z) pyplot.plot(Conc2[1], z) pyplot.plot(Conc3[1], z) pyplot.xlim(0,1) plt.xlabel('Conc') plt.ylabel('z') pyplot.grid(True) show() savefig('Conc.png') close() This can give me the comparison in one graph, I suppose. Now, first I like to know if this is a fine/logical script. otherwise I would like to know about probably a better way to write it with less lines! and second, when I do plot, each grid between x or y axis, has a thickness of 0.2. what I like do is to change it to 0.1 grid . So, I couldn't find it through matplotlib website (at least with my searching. Would it be possible helping me about? I am new at python and a beginner and I do have learn while I work with it... Thanks in advance, Sue On Thu, Dec 1, 2011 at 6:25 PM, Andreas Perstinger wrote: > On 2011-12-01 14:30, stm atoc wrote: >> >> With your help, I have a good script from the previous discussion: >> >> ********** >> from pylab import * > > > Have you used MATLAB before and are used to its syntax? In general "star > imports" (from xxx import *) are a bad practice and IMHO should be avoided. > > >> import numpy >> import matplotlib.pyplot as pyplot >> import matplotlib.mlab as mlab > > > These imports are unnecessary if you use the first line because "pylab" > imports everything from "numpy" and "matplotlib" into a single namespace. So > either use just the first line (not recommended) or the following line > (recommended). > > See also > http://matplotlib.sourceforge.net/faq/usage_faq.html#matplotlib-pylab-and-pyplot-how-are-they-related > and > http://matplotlib.sourceforge.net/faq/usage_faq.html#coding-styles > > BTW: Why do you import "mlab" when you don't use it? > > >> with open("ourtest_out.list", "r") as f: >> ? ?z = numpy.array([float(v) for v in f.readline().split()[1:]]) >> >> a = numpy.loadtxt("ourtest_out.list", skiprows=3) >> N = 100 >> Conc = a[0:, N+1:] >> print len(Conc[0]) == len(z) > > > This line was just for testing. You can delete it without any consequences. > > > >> figure() >> >> pyplot.plot(Conc[0],z,'r-',label='initial') >> pyplot.plot(Conc[1],z,'b-',label='after 20s') >> >> show() > > > Isn't that what you want? You are plotting all your data in one graph. There > is a straight red line on the left side and a falling blue line from left to > right. > > >> ********* >> >> I have tried to make subplot for this case as follows: >> >> pyplot.subplot(111) >> pyplot.plot(Conc[0],z,'r-',label='initial') >> pyplot.plot(Conc[1],z,'b-',label='after 20s') > > > Here you are creating a subplot with 1 plot each row and 1 plot each column, > in other words you do the same as above (creating just 1 plot). If you want > to have for example 4 plots in the same window with 2 each row and 2 each > column you have to use > > pyplot.subplot(221) > > After plotting all the data in this first "axes" you have to switch to the > next one: > > pyplot.subplot(222) > > Have you already read the matplotlib-tutorial: > http://matplotlib.sourceforge.net/users/pyplot_tutorial.html > > >> However, I am not sure how to add new data over this to make a graph >> including both new and old data simultaneously. > > > As I've said before: You are already plotting all data in one graph. > Don't you get two different lines? > > Bye, Andreas > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From d at davea.name Thu Dec 1 19:57:23 2011 From: d at davea.name (Dave Angel) Date: Thu, 01 Dec 2011 13:57:23 -0500 Subject: [Tutor] Need help adding a funcation In-Reply-To: References: <4ED7A265.3030102@davea.name> Message-ID: <4ED7CE13.2030405@davea.name> (You forgot to post your response on the list, instead posting it privately to me. Please use Reply-All, or whatever the equivalent is on your email app) On 12/01/2011 11:49 AM, Michael Hall wrote: > On Thu, Dec 1, 2011 at 7:51 AM, Dave Angel wrote: > >> On 12/01/2011 10:33 AM, Michael Hall wrote: >> >>> Here is the code I have written. >>> >>> # Create main function. >>> def main(): >>> a = input('Please Enter a Number: ') # Ask user for input. >>> number = int(a) >>> x = 1 >>> sum_of = 0 >>> while number> x: >>> if number % x == 0: >>> sum_of = sum_of + x >>> x += 1 >>> if sum_of == number: >>> print(number,'is a Perfect Number') >>> elif sum_of< number: >>> print(number,'is a Non-perfect Number') >>> >>> main() >>> >>> Here is the problem I am having. The program works perfect but I need to >>> add the following: >>> >>> # a) write a function, getDivisors(), that returns a list of all >>> # of the positive divisors of a given number. for example - >>> # result = getDivisors(24) >>> # print(result) >>> # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" >>> # b) write a program that uses your function to determine which >>> # numbers between 1 and 10,000 are perfect. (answer: 6, 28, 496 >>> # and 8128 are perfect!) >>> >>> I know that mystring needs to be added. I need help >>> Thank you in advance >>> >>> I don't see any 'mystring' in the source or in the assignment; why >> would you think you need it? >> >> It asks you to write a function called getDivisors(). You have all the >> pieces in your present code, but it's all inline. Probably your professor >> wants you to learn to code in small functions, so your code is more likely >> to be reusable. >> >> So what part of the function description is unclear? And is it unclear >> because you don' t understand one of the math terms, or because you don't >> know how to code it? She wants a function that takes a single argument >> (number), and returns a list >> >> def getDivisors(number): >> do some stuff >> return mylist >> >> You'll probably want to write another one that adds up the elements of a >> list (or you could find it in the stdlib). Then your main should be pretty >> straightforward. >> >> >> >> -- >> >> Dave A >> >> The truth is I am unsure how to code it. Here is my guess: > > def main(): > a = input('Please Enter a Number: ') # Ask user for input. > number = int(a) > x = 1 > sum_of = 0 > while number> x: > if number % x == 0: > sum_of = sum_of + x > x += 1 > if sum_of == number: > print(number,'is a Perfect Number') > elif sum_of< number: > print(number,'is a Non-perfect Number') > def getDivisors(number): > while count != num: > if (num % count) != 0: > mylist.append(count) > count +=1 > else: > count +=1 > print(mylist) > > > main() > > > YES, I DO NOT UNDERSTAND HOW OR WHERE TO PUT THE CODE. > THANK YOU FOR YOUR HELP. > You want a separate function, so don't try to put it in the middle of the present one. Put the def *after* the print(mylist) line. All you can take from the older function is ideas. Since you wrote it, you must know how to write the new one. The task is much simpler, and is a subset of the task the first one did. You're going to need some form of loop. Figure out what the limits are and see if you can figure out some way to do a for loop between those limits. The work of the loop body will be done by the same if number % x == 0: that you had before, but you do something different than what you did before. Your job is to build a list. Note to others: Don't confuse the issue with efficiency, nor with some library code. This is a homework assignment, and it has to be done with concepts the OP already has been taught. -- DaveA From norman at khine.net Thu Dec 1 20:36:42 2011 From: norman at khine.net (Norman Khine) Date: Thu, 1 Dec 2011 19:36:42 +0000 Subject: [Tutor] is there a better way to organise this code In-Reply-To: <4ED6CF23.8070408@pearwood.info> References: <4ED6CF23.8070408@pearwood.info> Message-ID: hi On Thu, Dec 1, 2011 at 12:49 AM, Steven D'Aprano wrote: > Norman Khine wrote: >> >> hello, >> >> is there a better way to organise this code or optimise it. >> http://pastie.org/2944797 > > > Is that a question? Because I get a syntax error in my brain when I parse it > without the question mark. sorry it was suppose to be a question. > > Sorry to pick on you, but it astonishes me when people don't bother with > basic English syntax, and yet try writing code where syntax is *much* more > important. If they can't be bothered with writing correct English, that > sends all the wrong signals about the quality of their code. > > You should write as if you were coding, otherwise people will assume you > code like you write. point taken. > > Laziness is one of the cardinal virtues of the programmer, but it has to be > the right sort of laziness. "Don't reinvent the wheel, use an existing > library" is good laziness. "Leave out required syntax elements and hope > someone else will fix them" is not. > > Before worrying about optimising the code, how about checking whether it > works? i am using the itools library http://www.hforge.org/itools/docs/csv and the code does work. > > (1) What is CSVFile? It appears to be a class, because you inherit from it, > but it isn't defined anywhere and isn't a builtin. So your code fails on the > very first line. > > (2) You have a class WorldSchema with no methods, and a top-level function > get_world that *looks* like a method because it has an argument "self", but > isn't. The indentation is wrong. See what I mean about syntax? Syntax is > important. So is get_world a wrongly indented method, or a poorly written > function? > > (3) Since get_world doesn't use "self" at all, perhaps it should be a > top-level function of no arguments? Or perhaps a static method of > WorldSchema? this is where i was uncertain as to how best approach it. > > (4) You have a class called "getCountries", which seems to be a poor name > for a class. In general, classes should be *things*, not *actions*. Also I > recommend that you follow PEP 8 for naming conventions. (Google "PEP 8" if > you don't know what I mean, and remember, it isn't compulsory, but it is > recommended.) A better name might be CountryGetter. ok, will do. > > (5) The use of classes appears on first reading to be a Java-ism. In Java, > everything must be a class Just Because The Powers Who Be Said So. In > Python, we are allowed, and encouraged, to mix classes and functions. Use > the right tool for the job. But without any idea of the broader context, I > have no idea if classes are appropriate or not. the broader context is that i would like to reuse CountryGetter, RegionGetter and CountyGetter within a multi-select widget that will be called from different forms. > > (6) getCountries has a method called get_options. Based on the name, a > reasonable reader would assume it returns some sort of list or dictionary of > options, right? But according to the documentation, it actually returns a > JSON "ser", whatever that is. Server? Service? Serialization (of what)? > Something else? yes it is a JSON serialization > > (7) Other problems: ?Enumerate, MSG and iana_root_zone are used but not > defined anywhere. Documentation is lacking, so I don't understand what the > code is intended to do. Another class with a poor name, "getRegions". There > may be others, but I stopped reading around this point. again sorry about this, i will try to be more explicit next time. as mentioned above, i was interested in knowing whether or not i needed to call the get_world() which loads the CSV file every time each getCountries, getRegion and getCounty classes are called and if there was a more efficient way to do this? thanks > > > > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From michael.hall5447 at gmail.com Thu Dec 1 20:55:56 2011 From: michael.hall5447 at gmail.com (Michael Hall) Date: Thu, 1 Dec 2011 11:55:56 -0800 Subject: [Tutor] Need help adding a funcation In-Reply-To: <4ED7CE13.2030405@davea.name> References: <4ED7A265.3030102@davea.name> <4ED7CE13.2030405@davea.name> Message-ID: The OP has been taught but is still having an issue and all I am doing is asking for help. Here is what I have so far # 1) a perfect number is a positive integer that is equal to the # sum of its proper positive divisors,excluding the number itself. # for example, 6 is a perfect number because it is evenly divisible # by 1, 2 and 3 - all of it's divisors - and the sum 1 + 2 + 3 = 6. # a) write a function, getDivisors(), that returns a list of all # of the positive divisors of a given number. for example - # result = getDivisors(24) # print(result) # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" def main(): x = 1 num = int(input('Please Enter a Number: ')) getDivisors(num) def getDivisors(num): sum = 0 x = 1 #my_list[] = num for num in range(1, num, 1): if num % x == 0: print(num) sum += num print('The sum is ', sum) if sum == num: print(num, 'is a perfect number') else: print(num, 'is not a perfect number') main() On Thu, Dec 1, 2011 at 10:57 AM, Dave Angel wrote: > (You forgot to post your response on the list, instead posting it > privately to me. Please use Reply-All, or whatever the equivalent is on > your email app) > > > On 12/01/2011 11:49 AM, Michael Hall wrote: > >> On Thu, Dec 1, 2011 at 7:51 AM, Dave Angel wrote: >> >> On 12/01/2011 10:33 AM, Michael Hall wrote: >>> >>> Here is the code I have written. >>>> >>>> # Create main function. >>>> def main(): >>>> a = input('Please Enter a Number: ') # Ask user for input. >>>> number = int(a) >>>> x = 1 >>>> sum_of = 0 >>>> while number> x: >>>> if number % x == 0: >>>> sum_of = sum_of + x >>>> x += 1 >>>> if sum_of == number: >>>> print(number,'is a Perfect Number') >>>> elif sum_of< number: >>>> print(number,'is a Non-perfect Number') >>>> >>>> main() >>>> >>>> Here is the problem I am having. The program works perfect but I need to >>>> add the following: >>>> >>>> # a) write a function, getDivisors(), that returns a list of all >>>> # of the positive divisors of a given number. for example - >>>> # result = getDivisors(24) >>>> # print(result) >>>> # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" >>>> # b) write a program that uses your function to determine which >>>> # numbers between 1 and 10,000 are perfect. (answer: 6, 28, 496 >>>> # and 8128 are perfect!) >>>> >>>> I know that mystring needs to be added. I need help >>>> Thank you in advance >>>> >>>> I don't see any 'mystring' in the source or in the assignment; why >>>> >>> would you think you need it? >>> >>> It asks you to write a function called getDivisors(). You have all the >>> pieces in your present code, but it's all inline. Probably your >>> professor >>> wants you to learn to code in small functions, so your code is more >>> likely >>> to be reusable. >>> >>> So what part of the function description is unclear? And is it unclear >>> because you don' t understand one of the math terms, or because you don't >>> know how to code it? She wants a function that takes a single argument >>> (number), and returns a list >>> >>> def getDivisors(number): >>> do some stuff >>> return mylist >>> >>> You'll probably want to write another one that adds up the elements of a >>> list (or you could find it in the stdlib). Then your main should be >>> pretty >>> straightforward. >>> >>> >>> >>> -- >>> >>> Dave >>> >> > > A > >> >>> The truth is I am unsure how to code it. Here is my guess: >>> >> >> def main(): >> a = input('Please Enter a Number: ') # Ask user for input. >> number = int(a) >> x = 1 >> sum_of = 0 >> while number> x: >> if number % x == 0: >> sum_of = sum_of + x >> x += 1 >> if sum_of == number: >> print(number,'is a Perfect Number') >> elif sum_of< number: >> print(number,'is a Non-perfect Number') >> def getDivisors(number): >> while count != num: >> if (num % count) != 0: >> mylist.append(count) >> count +=1 >> else: >> count +=1 >> print(mylist) >> >> >> main() >> >> >> YES, I DO NOT UNDERSTAND HOW OR WHERE TO PUT THE CODE. >> THANK YOU FOR YOUR HELP. >> >> > You want a separate function, so don't try to put it in the middle of the > present one. Put the def *after* the print(mylist) line. > > All you can take from the older function is ideas. Since you wrote it, > you must know how to write the new one. The task is much simpler, and is a > subset of the task the first one did. > > You're going to need some form of loop. Figure out what the limits are > and see if you can figure out some way to do a for loop between those > limits. The work of the loop body will be done by the same > > if number % x == 0: > > that you had before, but you do something different than what you did > before. Your job is to build a list. > > Note to others: Don't confuse the issue with efficiency, nor with some > library code. This is a homework assignment, and it has to be done with > concepts the OP already has been taught. > > -- > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Dec 1 21:17:09 2011 From: d at davea.name (Dave Angel) Date: Thu, 01 Dec 2011 15:17:09 -0500 Subject: [Tutor] Need help adding a funcation In-Reply-To: References: <4ED7A265.3030102@davea.name> <4ED7CE13.2030405@davea.name> Message-ID: <4ED7E0C5.9030307@davea.name> (You top-posted, so I'm deleting all the out-of-order stuff. in these forums, you should put your response after whatever you quote.) On 12/01/2011 02:55 PM, Michael Hall wrote: > The OP has been taught but is still having an issue and all I am doing is > asking for help. Here is what I have so far > > # 1) a perfect number is a positive integer that is equal to the > # sum of its proper positive divisors,excluding the number itself. > # for example, 6 is a perfect number because it is evenly divisible > # by 1, 2 and 3 - all of it's divisors - and the sum 1 + 2 + 3 = 6. > # a) write a function, getDivisors(), that returns a list of all > # of the positive divisors of a given number. for example - > # result = getDivisors(24) > # print(result) > # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" > > def main(): > x = 1 > > num = int(input('Please Enter a Number: ')) > getDivisors(num) You'll want to store the return value of getDivisors, since you have more work to do there. > > def getDivisors(num): > sum = 0 > x = 1 > #my_list[] = num That's close. To create an empty list, simply do my_list = [] > for num in range(1, num, 1): > > if num % x == 0: > print(num) > sum += num Why are you summing it? That was in another function. In this one, you're trying to build a list. Any ideas how to do that at this point in the function? > > print('The sum is ', sum) > if sum == num: > print(num, 'is a perfect number') > else: > print(num, 'is not a perfect number') None of these lines belong in your function. All it's supposed to do is get the divisors, not to study them in any way. > > main() -- DaveA From andreas.perstinger at gmx.net Thu Dec 1 22:01:06 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 01 Dec 2011 22:01:06 +0100 Subject: [Tutor] New plot over the old graph In-Reply-To: References: <4ED7B88A.8040002@gmx.net> Message-ID: <4ED7EB12.8050905@gmx.net> On 2011-12-01 19:20, stm atoc wrote: > Thanks for all information/websites and advice. Yes the graph is > exactly like the one you mentioned. Also, I would like to have them in > one not two, but I think since the dimension of the x and y are not > same, I have no choice. > > What I like to do now is comparing 2 (later 3 or more) different sets > of data, e.g. comparison among Conc[1] with sets.... > > I have changed the script like this: > > with open("ourtest_out.list", "r") as f: > z = numpy.array([float(v) for v in f.readline().split()[1:]]) > > a1 = numpy.loadtxt("ourtest_out1.list", skiprows=3) > a2 = numpy.loadtxt("ourtest_out2.list", skiprows=3) > a3 = numpy.loadtxt("ourtest_out3.list", skiprows=3) > > N = 100 > > Conc1 = a1[0:, N+1:] #base case > Conc2 = a2[0:, N+1:] # Ydw=0.1 > Conc3 = a3[0:, N+1:] # nuh=0.01 > lw = 2.0 #linewidth You aren't using "lw" so it doesn't make sense to define it. > dpi = 96 > figure(figsize=(10,6),dpi=dpi) I prefer to not clutter up the namespace with "star imports" (from pylabs import *) but it's your choice. > > pyplot.subplot(111) If you just use one graph/figure this call is unnecessary. > pyplot.plot(Conc1[1], z) > pyplot.plot(Conc2[1], z) > pyplot.plot(Conc3[1], z) > pyplot.xlim(0,1) > > plt.xlabel('Conc') > plt.ylabel('z') I assume you've got these lines from the tutorial. But there they are using the following import: import matplotlib.pyplot as plt I've used import matplotlib.pyplot as pyplot so you have to decide which name you want to use (You can't mix both). In general, if you just use import matplotlib.pyplot you would have to use always the full name: matplotlib.pyplot.xlabel('Conc') But with the "as"-keyword you can choose, which name gets imported into the namespace. If you have problems understanding imports and namespaces look at Alan's tutorial: http://www.freenetpages.co.uk/hp/alan.gauld/tutfunc.htm (section "Using Modules") http://www.freenetpages.co.uk/hp/alan.gauld/tutname.htm (about Namespaces) > > pyplot.grid(True) > show() > savefig('Conc.png') You should call "savefig" before "show" because in non-interactive mode (calling the script from the commandline) "show" will block all figures until they are closed. So after "show" there won't be any figures left and "savefig" will write an empty figure to the file. > close() > > This can give me the comparison in one graph, I suppose. > Now, first I like to know if this is a fine/logical script. otherwise > I would like to know about probably a better way to write it with less > lines! You could write the whole script in a more object-oriented style where you create a figure-instance and then set the attributes you want instead of calling all the functions. But for the beginning it's ok. > and second, when I do plot, each grid between x or y axis, has a > thickness of 0.2. what I like do is to change it to 0.1 grid . So, I > couldn't find it through matplotlib website (at least with my > searching. Would it be possible helping me about? You set the scale with the "xticks"-function (or the corresponding "yticks"): http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks So in your case you could use pyplot.xticks(numpy.arange(0, 1.1, 0.1)) Bye, Andreas From michael.hall5447 at gmail.com Thu Dec 1 22:17:31 2011 From: michael.hall5447 at gmail.com (Michael Hall) Date: Thu, 1 Dec 2011 13:17:31 -0800 Subject: [Tutor] Need help adding a funcation In-Reply-To: <4ED7E0C5.9030307@davea.name> References: <4ED7A265.3030102@davea.name> <4ED7CE13.2030405@davea.name> <4ED7E0C5.9030307@davea.name> Message-ID: Can anyone else help with this question? On Thu, Dec 1, 2011 at 12:17 PM, Dave Angel wrote: > (You top-posted, so I'm deleting all the out-of-order stuff. in these > forums, you should put your response after whatever you quote.) > > > On 12/01/2011 02:55 PM, Michael Hall wrote: > >> The OP has been taught but is still having an issue and all I am doing is >> asking for help. Here is what I have so far >> >> # 1) a perfect number is a positive integer that is equal to the >> # sum of its proper positive divisors,excluding the number itself. >> # for example, 6 is a perfect number because it is evenly divisible >> # by 1, 2 and 3 - all of it's divisors - and the sum 1 + 2 + 3 = 6. >> # a) write a function, getDivisors(), that returns a list of all >> # of the positive divisors of a given number. for example - >> # result = getDivisors(24) >> # print(result) >> # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" >> >> def main(): >> x = 1 >> >> num = int(input('Please Enter a Number: ')) >> getDivisors(num) >> > > You'll want to store the return value of getDivisors, since you have more > work to do there. > > > >> def getDivisors(num): >> sum = 0 >> x = 1 >> #my_list[] = num >> > > That's close. To create an empty list, simply do > my_list = [] > > > for num in range(1, num, 1): >> >> if num % x == 0: >> print(num) >> sum += num >> > Why are you summing it? That was in another function. In this one, > you're trying to build a list. Any ideas how to do that at this point in > the function? > > >> print('The sum is ', sum) >> if sum == num: >> print(num, 'is a perfect number') >> else: >> print(num, 'is not a perfect number') >> > None of these lines belong in your function. All it's supposed to do is > get the divisors, not to study them in any way. > > >> main() >> > > > > -- > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stm.at.oc at googlemail.com Thu Dec 1 22:41:44 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Thu, 1 Dec 2011 22:41:44 +0100 Subject: [Tutor] New plot over the old graph In-Reply-To: <4ED7EB12.8050905@gmx.net> References: <4ED7B88A.8040002@gmx.net> <4ED7EB12.8050905@gmx.net> Message-ID: I appreciated for the accurate response. I used step by step and it is running now. Thank you very much for your advice and guidance, Sue On Thu, Dec 1, 2011 at 10:01 PM, Andreas Perstinger wrote: > On 2011-12-01 19:20, stm atoc wrote: >> >> Thanks for all information/websites and advice. Yes the graph is >> exactly like the one you mentioned. Also, I would like to have them in >> one not two, but I think since the dimension of the x and y are not >> same, I have no choice. >> >> ?What I like to do now is comparing 2 (later 3 or more) different sets >> of data, e.g. comparison among Conc[1] with sets.... >> >> I have changed the script like this: >> >> with open("ourtest_out.list", "r") as f: >> ? ?z = numpy.array([float(v) for v in f.readline().split()[1:]]) >> >> a1 = numpy.loadtxt("ourtest_out1.list", skiprows=3) >> a2 = numpy.loadtxt("ourtest_out2.list", skiprows=3) >> a3 = numpy.loadtxt("ourtest_out3.list", skiprows=3) >> >> N = 100 >> >> Conc1 = a1[0:, N+1:] #base case >> Conc2 = a2[0:, N+1:] # Ydw=0.1 >> Conc3 = a3[0:, N+1:] # nuh=0.01 >> lw = 2.0 #linewidth > > > You aren't using "lw" so it doesn't make sense to define it. > >> dpi = 96 >> figure(figsize=(10,6),dpi=dpi) > > > I prefer to not clutter up the namespace with "star imports" (from pylabs > import *) but it's your choice. > >> >> pyplot.subplot(111) > > > If you just use one graph/figure this call is unnecessary. > > >> pyplot.plot(Conc1[1], z) >> pyplot.plot(Conc2[1], z) >> pyplot.plot(Conc3[1], z) >> pyplot.xlim(0,1) >> >> plt.xlabel('Conc') >> plt.ylabel('z') > > > I assume you've got these lines from the tutorial. But there they are using > the following import: > > import matplotlib.pyplot as plt > > I've used > > import matplotlib.pyplot as pyplot > > so you have to decide which name you want to use (You can't mix both). > > In general, if you just use > > import matplotlib.pyplot > > you would have to use always the full name: > > matplotlib.pyplot.xlabel('Conc') > > But with the "as"-keyword you can choose, which name gets imported into the > namespace. > > If you have problems understanding imports and namespaces look at Alan's > tutorial: > http://www.freenetpages.co.uk/hp/alan.gauld/tutfunc.htm (section "Using > Modules") > http://www.freenetpages.co.uk/hp/alan.gauld/tutname.htm (about Namespaces) > > >> >> pyplot.grid(True) >> show() >> savefig('Conc.png') > > > You should call "savefig" before "show" because in non-interactive mode > (calling the script from the commandline) "show" will block all figures > until they are closed. So after "show" there won't be any figures left and > "savefig" will write an empty figure to the file. > > >> close() >> >> This can give me the comparison in one graph, I suppose. >> Now, first I like to know if this is a fine/logical script. otherwise >> I would like to know about probably a better way to write it with less >> lines! > > > You could write the whole script in a more object-oriented style where you > create a figure-instance and then set the attributes you want instead of > calling all the functions. But for the beginning it's ok. > > >> and second, when I do plot, each grid between x or y axis, has a >> thickness of 0.2. what I like do is to change it to 0.1 grid . So, I >> couldn't find it through matplotlib website (at least with my >> searching. Would it be possible helping me about? > > > You set the scale with the "xticks"-function (or the corresponding > "yticks"): > http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xticks > > So in your case you could use > > pyplot.xticks(numpy.arange(0, 1.1, 0.1)) > > > Bye, Andreas > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Thu Dec 1 23:35:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Dec 2011 09:35:07 +1100 Subject: [Tutor] Prime Factorization Tool In-Reply-To: References: Message-ID: <4ED8011B.80306@pearwood.info> Wayne Werner wrote: [...] > Well, there are really only a couple of optimizations that you could make. > That's the nice (bad?) thing about primes - you really only *can* brute > force a solution. That's why nice things like encryption exist. Brute force is a little strong, but not far from the mark. For really large primes, hundreds or thousands of digits long, it simply isn't computationally feasible to factorize numbers quickly. But for small numbers, there's a huge difference in speed between the most naive brute force methods and the more clever methods. I have a set of functions for generating prime numbers, which can be used to factorize larger numbers. I benchmarked them by seeing how many primes they could find in five minutes. Here are the results on my computer: Benchmarking primes calculated in 420 seconds... croft : 12856761 primes => 29944 per second sieve : 9380437 primes => 22334 per second wheel : 1206656 primes => 2873 per second trial_division: 646429 primes => 1539 per second turner : 27896 primes => 66 per second naive_primes : 11964 primes => 28 per second wheel2 : 24148 primes => 57 per second The fastest method, croft, is over 1000 times faster than the slowest. > The less obvious optimization is in reference to primes - you don't > actually have to check all the way up to N. Or even N/2. You only have to > check numbers up to the square root of N. Absolutely. This is perhaps the most important optimization you can apply for factorizing small numbers. If you check every number, *at least* 99.9% of the work you do is unnecessary. The difference between trying to factorize (say) 100034567 by checking every number, and by checking up to the square root, is significant: you literally avoid 99.99% of the work. [...] > That will easily decrease the running time of your program because now > instead of dividing N numbers you're dividing sqrt(N) numbers. [...] > N/2 is the largest possible factor. Any number larger than N/2 is somewhere > between N/2 and N/1, and since there's no whole number between 2 and 1 you > know that the largest number you need to check for a factor is N/2, or in > the case of 100/2 = 50. But since N/2 is larger than sqrt(N), you don't even need to go that high. The secret is that as you find each factor, you reduce the number you are testing. For example, to factorize 2166, divide by 2, then every odd number up to sqrt(2166)=46, stopping when the number reaches 1 (if it does). 2 goes into 2166, so 2 is a factor and leaving 1083 3 goes into 1083, so 3 is a factor and leaving 361 5 doesn't go into 361 7 doesn't go into 361 9 doesn't go into 361 ... 19 goes into 361 twice, so 19 is a repeated factor and we are done because the number is reduced to 1 and there are no more factors: 2166 = 2*3*19*19 exactly. -- Steven From robert.sjoblom at gmail.com Thu Dec 1 23:43:31 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 1 Dec 2011 23:43:31 +0100 Subject: [Tutor] Prime Factorization Tool In-Reply-To: References: Message-ID: > Well, there are really only a couple of?optimizations?that you could make. > That's the nice (bad?) thing about primes - you really only *can* brute > force a solution. That's why nice things like encryption exist. Yes, I know that; perhaps I was unclear but my issues with brute force are for solutions 1 and 2, not solution 3. For instance, problem 2 is: #By considering the terms in the Fibonacci sequence whose #values do not exceed four million, find the sum of the even-valued terms. And my solution is def fib(n = 4000000): a, b = 0, 1 while a < n: a, b = b, a + b if a%2 == 0: yield a Which is perfectly fine as a solution, but nowhere near as elegant as the mathematical solution. Anyway, I digress. > The less obvious optimization is in reference to primes - you don't actually > have to check all the way up to N. Or even N/2. You only have to check > numbers up to the square root of N. This explanation may not be > mathematically sound, but basically the reason this works is the definition > of prime: N is divisible only by N and 1. If you divide a number by 2 then > then the result will be the largest factor (e.g. 100/2 = 50). But as you > start increasing the divisor then obviously the result has to decrease. The > point at which these numbers are equivalent? The square root, of course. I was suspecting there was something like that; my thoughts were starting to move toward something along those lines. I suppose I'm just rusty. > Now, I'm not sure what the time complexity of these two operations is, but > go ahead and put this line in your isprime: > > if n == 11: print("Checked 11... again") > > Can you think of a way to compute the primes you need to check only once? First reaction: "whoa!". That is a lot of redundant calculations. I'm afraid I'm a bit stumped on this one; one solution that seems to work is sending the factor to isprime() along with n, and do the for loop like this: for x in range(factor, round(sqrt(n))): But I'm not sure that's actually a good idea or if it just happened to work in this particular case. As I said, it seems to work but it could just be a coincidence. Way I see it, I've already tested all the numbers up to the last factor and so I shouldn't need to test them again? However, your "if n == 11" line confuses me; after the changes I never once hit n == 11, which is weird? Anyway, this is my reworked functions, which are much faster than the original ones. I really need to learn how to use the timeit module to see the difference. from math import sqrt def isprime(n, factor): if n == 1: return False for x in range(2, round(sqrt(n))): if n % x == 0: return False else: return True def factorization(n): factor = 2 x = 3 while True: if n % x == 0: if isprime(x, factor): factor = x n = n // x if n == 1: return factor else: return factor x += 2 print(factorization(600851475143)) > > HTH, > Wayne -- best regards, Robert S. From robert.sjoblom at gmail.com Thu Dec 1 23:48:44 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 1 Dec 2011 23:48:44 +0100 Subject: [Tutor] Prime Factorization Tool In-Reply-To: References: Message-ID: > from math import sqrt > > def isprime(n, factor): > ? ?if n == 1: > ? ? ? ?return False > ? ?for x in range(2, round(sqrt(n))): Ooops, this should obviously read for x in range(factor, round(sqrt(n))): best regards, Robert S. From alan.gauld at btinternet.com Fri Dec 2 00:22:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Dec 2011 23:22:15 +0000 Subject: [Tutor] Need help adding a funcation In-Reply-To: References: <4ED7A265.3030102@davea.name> <4ED7CE13.2030405@davea.name> <4ED7E0C5.9030307@davea.name> Message-ID: On 01/12/11 21:17, Michael Hall wrote: > Can anyone else help with this question? Sure lots of us could help. But Dave's doing a good job leading you in the right direction. Is there something that you don't understand? If you ask about specific points we can give specific answers. Meantime I'll add a few extra comments to see if that helps... > def main(): > x = 1 > > num = int(input('Please Enter a Number: ')) > getDivisors(num) > > > You'll want to store the return value of getDivisors, since you have > more work to do there. What Dave means is that you are simply calling the function but not storing the result. So you calculate the divisors but then have no chance to use them. You need to store them in a variable someplace. Think about the input() function you use above. If you had just done int(input('Please Enter a Number: ')) You couldn't use the value that the user entered. You had to assign it to num to do that. It's the same with your function getDivisors() > def getDivisors(num): > sum = 0 > x = 1 > #my_list[] = num > > That's close. To create an empty list, simply do > my_list = [] self explanatory, I hope. > for num in range(1, num, 1): > > if num % x == 0: > print(num) > sum += num > > Why are you summing it? That was in another function. In this one, > you're trying to build a list. Any ideas how to do that at this > point in the function? So you need to store your results as a list not as a number. So instead of sum() what can you do to my_list to add a new element? If you aren't sure fire up the Python >>> prompt and try help(list) or just help([]) and see if you can see anything useful. > print('The sum is ', sum) > if sum == num: > print(num, 'is a perfect number') > else: > print(num, 'is not a perfect number') > > None of these lines belong in your function. All it's supposed to > do is get the divisors, not to study them in any way. This is a good principle to apply when writing functions. Separate out the display from the logic. That way you can use the results of the logic with any kind of user interface - GUI, Web, or command line, or even in a server process without a UI. But this takes us back to the advice to assign the result to a variable in main(). To do that you need to return a result. And in this case your result should be a list of numbers. then you can do any printing in the main function. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From charleshbecker at gmail.com Fri Dec 2 00:30:14 2011 From: charleshbecker at gmail.com (Charles Karl Becker) Date: Thu, 1 Dec 2011 16:30:14 -0700 Subject: [Tutor] Generating dynamic output Message-ID: Hi everyone, My CS mentor (not school credit, just a friend helping me with some blindspots and pointers, etc) has been having me write, and then extend, a Tic Tac Toe game. Currently I'm working on dynamically creating the board/output with varying sizes so the user can define the size of the board. The following code works, I'm using Python 3.2 on Windows 7, however I'm sure there is some way to optimize this that I'm just missing (particularly on the line generations, some way to not need to remove the last character). I probably over-commented, but wanted to make it easier to parse. So the main thing I'm looking for are pointers on how I could optimize/refactor this, and any resources on this and how to 'think' more in the right way for this type of thing. Also, please let me know what's good about it :P As you can see my understanding of list comprehensions has grown a lot since my initial post here. I'm sending this as plain text after the sig, if any indenting is lost please let me know and I can send the file Thanks! Charles def build_line(part): ''' dynamically builds and returns the static lines for use in the board ''' line = [part for x in range(board_size)] line = ''.join(line) line = line[:-1] return line # defines the board size board_size = 5 # these pieces are used in creating the two static lines part1 = ' |' part2 = '---|' # this creates a list of the line #s which will be dynamic (if 0 is the first) dynamic_list = [x for x in range(board_size)[1:board_size*board_size:4]] # generates the array used for controlling the board spaces/taken locations master = [[str(x+1), 0] for x in range(board_size**2)] # this section builds the two static lines line1 = build_line(part1) line2 = build_line(part2) # these are used for loop/flow control b = 0 # this is used to tell which line needs to be printed c = 0 # this controls the slicing to tell the board where to start 'temp_row' # this generates the board on the fly for row in range(board_size*4-1): if(b == 0 or b == 2): print(line1) elif(b == 3): print(line2) elif(b == 1): # since these rows are dynamic they are called 'temp_row' # and are reset each time a new one is made temp_row = '' for cell in master[c:c+board_size]: if(int(cell[0]) >= 100): temp_row += '{0}|'.format(cell[0]) if(int(cell[0]) >= 10): temp_row += '{0} |'.format(cell[0]) else: temp_row += ' {0} |'.format(cell[0]) c += board_size # this is how this variable determines where to start next time temp_row = temp_row[:-1] # need to get rid of extra '|' at end of line print(temp_row) # this is just some loop/flow control b += 1 if(b == 4): b = 0 From alan.gauld at btinternet.com Fri Dec 2 00:46:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Dec 2011 23:46:47 +0000 Subject: [Tutor] Generating dynamic output In-Reply-To: References: Message-ID: On 01/12/11 23:30, Charles Karl Becker wrote: > sending this as plain text after the sig, if any indenting is lost > please let me know and I can send the file Looks ok to me... a few comments below, the main block was hurting my hewad so I gave up for now. Its late... > def build_line(part): > ''' dynamically builds and returns the static lines for use in the board ''' > line = [part for x in range(board_size)] > line = ''.join(line) > line = line[:-1] > return line You should probably pass in board_size as an argument too. If you just want to build a string of repeated characters you can use multiplication line = part * board_size > # defines the board size > board_size = 5 > etc/... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Fri Dec 2 00:56:12 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Dec 2011 10:56:12 +1100 Subject: [Tutor] Prime Factorization Tool In-Reply-To: References: Message-ID: <4ED8141C.20705@pearwood.info> Robert Sjoblom wrote: > from math import sqrt > > def isprime(n, factor): > if n == 1: > return False > for x in range(2, round(sqrt(n))): > if n % x == 0: > return False > else: > return True factor is not used in the isprime function; get rid of it. A bug in your code: the stop value in the call to range is sometimes off by one. That means that you sometimes wrongly pick a composite number as prime. E.g. isprime(25) returns True, but 25 is 5*5 and therefore not prime. Remember that the "stop" value of the range function is not included in the range: range(2, 5) => [2, 3, 4] and so 5 is not tested. You need to include the sqrt. So you need to add 1 to the stop to ensure the sqrt is included: range(2, round(sqrt(n))+1) But this leads to a trivial inefficiency: sometimes you test one extra number. There's no need to round the square root up to the nearest value, e.g. square root of 115 is 10.723805294763608 which rounds up to 11. But there's no point in testing 11, since 11*11 = 121 > 115 and so 11 can't be a factor (assuming you have been reducing the number each time you find a smaller factor). Instead of using round, just use int(sqrt(n)) to drop the fractional part. range(2, int(sqrt(n))+1) A much more important inefficiency: you don't need to test by even numbers except for 2. If a number is divisible by 4, then it is also divisible by 2, and so even numbers will always be detected by the "divide by 2" step. Testing by dividing by 4, 6, 8, ... is pointless. So you can roughly double the speed of your function by skipping even numbers other than two. Remember that 2 itself is prime, but any other multiple of 2 is not. Take that test outside of the loop, and then loop over every second number starting with 3. Hint: the range function takes a step size: range(3, 25, 7) => [3, 10, 17, 24] -- Steven From robert.sjoblom at gmail.com Fri Dec 2 01:49:47 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Fri, 2 Dec 2011 01:49:47 +0100 Subject: [Tutor] Prime Factorization Tool In-Reply-To: <4ED8141C.20705@pearwood.info> References: <4ED8141C.20705@pearwood.info> Message-ID: > So you can roughly double the speed of your function by skipping even > numbers other than two. Remember that 2 itself is prime, but any other > multiple of 2 is not. Take that test outside of the loop, and then loop over > every second number starting with 3. > So, if I understood this right, my function should look like this then: def isprime(n): if n == 1: return False elif n == 2: return True for x in range(2, round(sqrt(n))+1): if n % x == 0: return False else: return True This works like expected, but I think my factorization function has a really bad problem somewhere. def factorization(n): factor = 2 x = 3 while True: if n % x == 0: if isprime(x): factor = x n = n // x if n == 1: return factor else: return factor x += 2 factorization(100) brings the program into an infinite loop. Same for 200, 300, 400. It works on 1000, so there's something that's not right in there. Going through the code, this is what happens: factorization() gets 100, it tests it against 3 and fails, and it tests it against 5 and it works. 5 gets sent to isprime() which confirms that it's a prime. Factor is set to 5. n is set to n // 5, which is 20. The loop goes again, but since x is now 7 it will never actually end. The reason why it ends when factorization(1000) runs is because it accidentally finds x = 25 and 5*25 = 200 (1000//5 = 200), thus ending the loop. I'm not sure how to fix that. Recursion? It obviously happens when the answer is something like 2*2*5*5. -- best regards, Robert S. From bgailer at gmail.com Fri Dec 2 02:17:55 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 01 Dec 2011 20:17:55 -0500 Subject: [Tutor] is there a better way to organise this code In-Reply-To: <4ED6DC7A.9080001@davea.name> References: <4ED6CF23.8070408@pearwood.info> <4ED6DC7A.9080001@davea.name> Message-ID: <4ED82743.1060904@gmail.com> On 11/30/2011 8:46 PM, Dave Angel wrote: > On 11/30/2011 07:49 PM, Steven D'Aprano wrote: >> Norman Khine wrote: >>> hello, >>> >>> is there a better way to organise this code or optimise it. >>> http://pastie.org/2944797 >> >> > I stopped looking at his pastie once the background turned black. I'd > have had to copy it elsewhere to even read it. Check out the drop-down box on the upper right. Choose Clean -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Fri Dec 2 04:19:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Dec 2011 14:19:53 +1100 Subject: [Tutor] Prime Factorization Tool In-Reply-To: References: <4ED8141C.20705@pearwood.info> Message-ID: <4ED843D9.9020406@pearwood.info> Robert Sjoblom wrote: >> So you can roughly double the speed of your function by skipping even >> numbers other than two. Remember that 2 itself is prime, but any other >> multiple of 2 is not. Take that test outside of the loop, and then loop over >> every second number starting with 3. >> > > So, if I understood this right, my function should look like this then: > def isprime(n): > if n == 1: > return False > elif n == 2: > return True > for x in range(2, round(sqrt(n))+1): > if n % x == 0: > return False > else: > return True Not quite; you're still starting the loop at 2, and testing every number. Firstly, you need to exclude all even numbers apart from two. elif n == 2: # the only even prime return True elif n%2 == 0: # even numbers have no remainder when divided by 2 return False Secondly, you should replace the loop testing every number starting at two: for x in range(2, round(sqrt(n))+1): ... with one that starts at three and only tests odd numbers: for x in range(3, int(sqrt(n))+1, 2): ... > This works like expected, but I think my factorization function has a > really bad problem somewhere. Let's start by doing a factorization by hand. Suppose we want to factorize 195942. It makes sense to start dividing by the smallest numbers we can, and move up. And remember to check for repeated factors. Is 2 a factor? Yes, because 195942 % 2 == 0. So our first factor is 2, and we're left with 195942/2 = 97971 still to be factorized. That is, we have partially factorized 195942 = 2 * 97971. Is 2 a factor of 97971? No, so we can move on to the next potential factor. Is 3 a factor of 97971? Yes, so we add 3 to our list of factors, and we have a partial factorization of 195942 = 2*3 * 32657. Is 3 a factor of 32657? No, so move on. There is no point in checking whether 4 is a factor, because if it were, we would have caught it earlier when we divided by 2. Same for 6, 8, 10, and all other even numbers. So we skip all even numbers apart from two. Is 5 a factor of 32657? No. Is 7 a factor of 32657? No. Is 9 a factor of 32657? No. Is 11 a factor of 32657? No. Is 13 a factor of 32657? No. Is 15 a factor of 32657? No. Is 17 a factor of 32657? Yes, so we add 17 to our list of factors, and we have a partial factorization of 195942 = 2*3*17 * 1921. Is 17 a factor of 1921? Yes, so we add 17 to the factors (it is a repeated factor), and have 195942 = 2*3*17*17 * 113. And we are done: 113 is a prime number, and 195942 = 2*3*17*17*113. The tricky part is the end. How do we know 113 is a prime number without dividing by all the possible factors? Well, we know it isn't divisible by 2, because if it were, we would have found those factors earlier when we divided by 2. And it isn't divisible by 3, for the same reason. And so on -- we know 113 isn't divisible by anything smaller than 17. So the smallest *potential* factor is 19: if there were a smaller factor, we would have already found it. But how do we know that 113 is prime without even testing? Why couldn't 19 be a factor? Because 19 is larger than sqrt(113), which is a little more than 10. Another way to say it, is that 19**2 > 113. Since 19 is the smallest potential factor, and 19*19 is too big, that tells us that 19 isn't a factor and therefore there are no more factors to test. So our first version looks like this: def factorize(n): factors = [] while n%2 == 0: factors.append(2) n = n/2 d = 3 while d**2 <= n: while n % d == 0: factors.append(d) n = n/d d = d+2 if n != 1: factors.append(n) return factors Notice that we don't use the isprime() function! Potential improvements: * As it stands, the function does the wrong thing for numbers less than two. Fix that problem. * We test for potential factors 9, 21, 27, ... which are multiples of 3, and therefore cannot be a factor. Is there a way to skip them? * Likewise for potential factors which are multiples of 5, 7, 11, etc. We really only want to test using prime numbers 2, 3, 5, 7, 11, 13, ... and skip all multiples. Is there a way to have the factorize() function only check with prime factors? What if you had a function called primes() which returned all the prime numbers as needed? How would you write primes()? * Can we use the isprime() function to speed this up? Or will it slow it down? Food for experimentation. -- Steven From chare at labr.net Fri Dec 2 03:52:09 2011 From: chare at labr.net (Chris Hare) Date: Thu, 1 Dec 2011 20:52:09 -0600 Subject: [Tutor] executing dynamic code with exec? Message-ID: I have this code chunk: tables = ["Farm", "Animals", "AnimalTypes","Users","Roles","Capabilities","Pedigrees","ChipMaker","Owner","Providers","RegistryL"] for x in tables: cmd = "self.cb" + x + "Read = IntVar()" exec cmd in locals(), globals() When the code is executed, I get the following error: File "z.py", line 4398 exec cmd in locals(), globals() SyntaxError: function 'showRoles' uses import * and bare exec, which are illegal because it contains a nested function with free variables What I am trying to do is create a set of variables based upon the table names in the table variables. I have similar code which dynamically creates check buttons and the associated grid. But I suspect those won't work either. What have I got wrong? Thanks! Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Dec 2 06:25:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Dec 2011 16:25:40 +1100 Subject: [Tutor] executing dynamic code with exec? In-Reply-To: References: Message-ID: <4ED86154.30801@pearwood.info> Chris Hare wrote: > What I am trying to do is create a set of variables based upon the table > names in the table variables. I have similar code which dynamically > creates check buttons and the associated grid. But I suspect those won't > work either. > > What have I got wrong? Everything! Seriously though, your basic approach is the wrong approach. Don't try to create dynamic variables like that. Suppose you succeed: varName = 'x' # read from a file, or something exec('%s = 1' % varName) # creates the variable x Great. Now you have a variable x. Later on, how do you use it? # much later on in your code... y = x + 1 But that won't work, because you don't know that it's called x! If you knew it was called x, you would have just written x = 1 early and not needed exec. Working with dynamic variable names is a pain and a nightmare. Don't do it. Even if you succeed, you are making a rod for your own back: maintaining such code is horrible. The right way to do this is almost always to use a data structure that maps names to values, in other words, a dict. varName = 'x' # read from a file, or something data = {varName: 1} # ... # much later y = data[varName] + 1 In this case, something like: names = ["Farm", "Animals", "AnimalTypes", "Users", "Roles", "Capabilities", "Pedigrees", "ChipMaker", "Owner", "Providers", "RegistryL" ] self.cbReadTable = {} for name in names: self.cbReadTable[name] = IntVar() And that's it. Instead of retrieving instance.cbFarmRead, use instance.cbReadTable['Farm']. If you absolutely must use instance attributes, perhaps because you think you're writing Javascript , then: for name in names: name = 'cb' + name 'Read' setattr(self, name, IntVar()) And best of all, you avoid the code injection security vulnerability where somebody manages to fool your code into using a list of table names like: names = ["Farm", "Animals", "AnimalTypes", "Users", "Roles", "Capabilities", "Pedigrees", "ChipMaker=1;import os;os.system('echo you are pwned rm-rf haha');", "Owner", "Providers", "RegistryL" ] Hope your backups are really good. http://xkcd.com/327/ -- Steven From michael.hall5447 at gmail.com Fri Dec 2 08:22:07 2011 From: michael.hall5447 at gmail.com (Michael Hall) Date: Thu, 1 Dec 2011 23:22:07 -0800 Subject: [Tutor] Need help adding a funcation In-Reply-To: References: <4ED7A265.3030102@davea.name> <4ED7CE13.2030405@davea.name> <4ED7E0C5.9030307@davea.name> Message-ID: I am still not understanding what it is I am being asked to do. What is the differance between my_list = [] an my_list[ ] because when I use my_list[] I get an error. Not sure what I am doing wrong. I am asking if you are given the following question how would you write the program. I have most of it. Here is what I know works # Create main function. def main(): a = input('Please Enter a Number: ') # Ask user for input. number = int(a) x = 1 sum_of = 0 getDivisors while number > x: if number % x == 0: sum_of = sum_of + x x += 1 if sum_of == number: print(number,'is a Perfect Number') elif sum_of < number: print(number,'is a Non-perfect Number') def getDivisors(num): sum = 0 x = 1 #my_list[] = num for num in range(1, num, 1): if num % x == 0: print(num) sum += num print('The sum is ', sum) if sum == num: print(num, 'is a perfect number') else: print(num, 'is not a perfect number') main() This is what the teacher is asking for: # 1) a perfect number is a positive integer that is equal to the # sum of its proper positive divisors,excluding the number itself. # for example, 6 is a perfect number because it is evenly divisible # by 1, 2 and 3 - all of it's divisors - and the sum 1 + 2 + 3 = 6. # a) write a function, getDivisors(), that returns a list of all # of the positive divisors of a given number. for example - # result = getDivisors(24) # print(result) # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" # b) write a program that uses your function to determine which # numbers between 1 and 10,000 are perfect. (answer: 6, 28, 496 # and 8128 are perfect!) I am asking for help writing it. I am new to programming. Lost alot of brain matter. On Thu, Dec 1, 2011 at 3:22 PM, Alan Gauld wrote: > On 01/12/11 21:17, Michael Hall wrote: > >> Can anyone else help with this question? >> > > Sure lots of us could help. But Dave's doing a good job > leading you in the right direction. > > Is there something that you don't understand? If you ask about specific > points we can give specific answers. Meantime I'll add a few extra comments > to see if that helps... > > > def main(): >> x = 1 >> >> num = int(input('Please Enter a Number: ')) >> getDivisors(num) >> >> >> You'll want to store the return value of getDivisors, since you have >> more work to do there. >> > > What Dave means is that you are simply calling the function but not > storing the result. So you calculate the divisors but then have no chance > to use them. You need to store them in a variable someplace. > Think about the input() function you use above. > > If you had just done > > > int(input('Please Enter a Number: ')) > > You couldn't use the value that the user entered. > You had to assign it to num to do that. It's the same > with your function getDivisors() > > > def getDivisors(num): >> sum = 0 >> x = 1 >> #my_list[] = num >> >> That's close. To create an empty list, simply do >> my_list = [] >> > > self explanatory, I hope. > > > > for num in range(1, num, 1): >> >> if num % x == 0: >> print(num) >> sum += num >> >> Why are you summing it? That was in another function. In this one, >> you're trying to build a list. Any ideas how to do that at this >> point in the function? >> > > So you need to store your results as a list not as a number. So instead of > sum() what can you do to my_list to add a new element? > If you aren't sure fire up the Python >>> prompt and try > help(list) or just help([]) and see if you can see anything useful. > > > print('The sum is ', sum) >> if sum == num: >> print(num, 'is a perfect number') >> else: >> print(num, 'is not a perfect number') >> >> None of these lines belong in your function. All it's supposed to >> do is get the divisors, not to study them in any way. >> > > This is a good principle to apply when writing functions. Separate out the > display from the logic. That way you can use the results of the logic with > any kind of user interface - GUI, Web, or command line, or even in a server > process without a UI. > > But this takes us back to the advice to assign the result to a variable in > main(). > > To do that you need to return a result. And in this case your result > should be a list of numbers. then you can do any printing in the main > function. > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Dec 2 10:17:45 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Dec 2011 20:17:45 +1100 Subject: [Tutor] Need help adding a funcation In-Reply-To: References: <4ED7A265.3030102@davea.name> <4ED7CE13.2030405@davea.name> <4ED7E0C5.9030307@davea.name> Message-ID: <4ED897B9.4060503@pearwood.info> Michael Hall wrote: > I am still not understanding what it is I am being asked to do. What is the > differance between my_list = [] an my_list[ ] because when I use my_list[] > I get an error. Not sure what I am doing wrong. In Python, square brackets [ ] are used for two related but different purposes. The first is for creating lists: L = [1, 2, 4, 8] creates a list containing four numbers and assigns it to the name L. When using square brackets to create a new list, you don't need anything inside the brackets. If you try it, you just get an empty list: x = [] # a list with no items x = [42] # a list with one item x = [42, 23] # a list with two items The second is for item access. If you want to refer to the entire list L, you just say "L": print L # prints the entire list [1, 2, 4, 8] But if you want to refer to only a single item of L, you need to use this syntax: print L[2] # prints "4" (Aside: why does it print 4? Remember that Python starts counting from 0, not 1, so the 0th item is 1, the 1st item is 2, the 2nd item is 4, and the 3rd item is 8. While it might seem a bit weird at first, it actually has some good advantages.) You can also refer to a portion of a list by taking a slice: print L[1:3] # prints [2, 4] It's called a slice, because you think of it as cutting slices *between* items, like this illustration: |1|2|4|8| The slice 1:3 cuts *before* the 1st and 3rd items. Using / instead of | for the places you cut: |1/2|4/8| so you get [2, 4] as the slice. When using [] for item access, there *must* be something inside the brackets: print L[2] # okay print L[] # not okay, which item did you want? L[2] = 42 # puts 42 into item 2 of the list L[] = 42 # an error Does that help you? > I am asking for help writing it. I am new to programming. Lost alot of > brain matter. If you have concrete questions, please ask. -- Steven From andreas.perstinger at gmx.net Fri Dec 2 10:55:16 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 02 Dec 2011 10:55:16 +0100 Subject: [Tutor] Need help adding a funcation In-Reply-To: References: <4ED7A265.3030102@davea.name> <4ED7CE13.2030405@davea.name> <4ED7E0C5.9030307@davea.name> Message-ID: <4ED8A084.7070109@gmx.net> On 2011-12-02 08:22, Michael Hall wrote: > I am still not understanding what it is I am being asked to do. Ok, forget about your working program and just concentrate on question 1a): > # a) write a function, getDivisors(), that returns a list of all > # of the positive divisors of a given number. for example - > # result = getDivisors(24) > # print(result) > # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" I suppose you know how functions and lists works, do you? You have to write a function named "getDivisors" which takes one argument (a number) and returns a list. Nothing more, nothing less. You started right with the line def getDivisors(num): but in all your attempts you have never returned a value. Do you know how a function can return something? In your case you have to return a list. Therefore you have to build this list inside the function. You don't need to print the values or calculate a sum, just add every divisor to the list. I'm sure you have learned already how lists works, haven't you? If you have problems understanding functions and lists, you should re-read these parts in your learning material or in the online tutorial: http://docs.python.org/py3k/tutorial/introduction.html#lists http://docs.python.org/py3k/tutorial/controlflow.html#defining-functions http://docs.python.org/py3k/tutorial/datastructures.html#more-on-lists > I am asking if you are given the following question how would you > write the program. Sorry, we won't write the program for you. You have to do it yourself. We will just try to give you some hints - if you carefully read the links I've mentioned you'll find an example which comes close to yours :-). Bye, Andreas From chare at labr.net Fri Dec 2 13:39:00 2011 From: chare at labr.net (Chris Hare) Date: Fri, 2 Dec 2011 06:39:00 -0600 Subject: [Tutor] executing dynamic code with exec? In-Reply-To: <4ED86154.30801@pearwood.info> References: <4ED86154.30801@pearwood.info> Message-ID: <47FC6C28-1D19-4A19-A8B3-2292D95B61DD@labr.net> Thanks Steve for your help (and the humor). I can see that it was a bad idea with your explanation. (I just didn't want to type all that extra code :-)) I am going to re-write it using your dict approach - that looks a lot cleaner Thanks! Chris Hare chare at labr.net http://www.labr.net On Dec 1, 2011, at 11:25 PM, Steven D'Aprano wrote: > Chris Hare wrote: > >> What I am trying to do is create a set of variables based upon the table >> names in the table variables. I have similar code which dynamically >> creates check buttons and the associated grid. But I suspect those won't >> work either. >> What have I got wrong? > > Everything! > > Seriously though, your basic approach is the wrong approach. Don't try to create dynamic variables like that. Suppose you succeed: > > varName = 'x' # read from a file, or something > exec('%s = 1' % varName) # creates the variable x > > Great. Now you have a variable x. Later on, how do you use it? > > # much later on in your code... > y = x + 1 > > But that won't work, because you don't know that it's called x! If you knew it was called x, you would have just written x = 1 early and not needed exec. > > Working with dynamic variable names is a pain and a nightmare. Don't do it. Even if you succeed, you are making a rod for your own back: maintaining such code is horrible. > > The right way to do this is almost always to use a data structure that maps names to values, in other words, a dict. > > varName = 'x' # read from a file, or something > data = {varName: 1} > # ... > # much later > y = data[varName] + 1 > > > In this case, something like: > > > names = ["Farm", "Animals", "AnimalTypes", "Users", "Roles", > "Capabilities", "Pedigrees", "ChipMaker", "Owner", "Providers", > "RegistryL" > ] > self.cbReadTable = {} > for name in names: > self.cbReadTable[name] = IntVar() > > > And that's it. Instead of retrieving instance.cbFarmRead, use instance.cbReadTable['Farm']. > > If you absolutely must use instance attributes, perhaps because you think you're writing Javascript , then: > > for name in names: > name = 'cb' + name 'Read' > setattr(self, name, IntVar()) > > > And best of all, you avoid the code injection security vulnerability where somebody manages to fool your code into using a list of table names like: > > names = ["Farm", "Animals", "AnimalTypes", "Users", "Roles", > "Capabilities", "Pedigrees", > "ChipMaker=1;import os;os.system('echo you are pwned rm-rf haha');", > "Owner", "Providers", "RegistryL" > ] > > > Hope your backups are really good. > > http://xkcd.com/327/ > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Fri Dec 2 14:49:21 2011 From: suryak at live.com (surya k) Date: Fri, 2 Dec 2011 19:19:21 +0530 Subject: [Tutor] unexpected list entry Message-ID: Hi, Just take a look at this small code.. I am just taking a string as input and assigning it as a list. But I am finding an unexpected entry in the list.. Why this is happening? I am using PyScripter IDE. code : #!/usr/bin/env python def main(): pass if __name__ == '__main__': main() print "Flames: " name1 = raw_input('enter name 1') ListName1 = list(name1) print name1 print ListName1 Output: Flames: foo [u'f', u'o', u'o'] Observe the last line.. it isn't showing [ 'f', 'o', 'o'] Why is that "u" coming in the middle from no where ?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Dec 2 15:08:15 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 Dec 2011 09:08:15 -0500 Subject: [Tutor] unexpected list entry In-Reply-To: References: Message-ID: <4ED8DBCF.1010902@gmail.com> On 12/2/2011 8:49 AM, surya k wrote: > Hi, > Just take a look at this small code.. I am just taking a string as > input and assigning it as a list. > But I am finding an unexpected entry in the list.. Why this is happening? > I am using PyScripter IDE. > code : > #!/usr/bin/env python > def main(): > pass > if __name__ == '__main__': > main() > print "Flames: " > name1 = raw_input('enter name 1') > ListName1 = list(name1) > print name1 > print ListName1 > Output: > Flames: > foo > *[u'f', u'o', u'o']* > Observe the last line.. it isn't showing [ 'f', 'o', 'o'] > Why is that "u" coming in the middle from no where ?? input is returning user entry as unicode. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.perstinger at gmx.net Fri Dec 2 15:08:46 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 02 Dec 2011 15:08:46 +0100 Subject: [Tutor] Generating dynamic output In-Reply-To: References: Message-ID: <4ED8DBEE.8000305@gmx.net> On 2011-12-02 00:30, Charles Karl Becker wrote: > So the main thing I'm looking for are pointers on how I could > optimize/refactor this, and any resources on this and how to 'think' > more in the right way for this type of thing. Also, please let me > know what's good about it :P > > def build_line(part): > ''' dynamically builds and returns the static lines for use in the board ''' > line = [part for x in range(board_size)] > line = ''.join(line) > line = line[:-1] > return line > > # defines the board size > board_size = 5 > > # these pieces are used in creating the two static lines > part1 = ' |' > part2 = '---|' > > # this creates a list of the line #s which will be dynamic (if 0 is the first) > dynamic_list = [x for x in range(board_size)[1:board_size*board_size:4]] I don't understand what you want to do with "dynamic_list". You are not using it and if you need a range from 1 to board_size with step 4 just use the range-function: dynamic_list = range(1, board_size, 4) But I've still no clue why you need this list. > # generates the array used for controlling the board spaces/taken locations > master = [[str(x+1), 0] for x in range(board_size**2)] I guess "master" is later used to save the content of each board cell, right? But why do you store the cell-number as a string? And what is the second value (0)? Wouldn't it be easier to have a structure like master = ["xxo", " xo", "xoo"] because then you can easily index every cell with master[row][col] ? > # this section builds the two static lines > line1 = build_line(part1) > line2 = build_line(part2) As Alan has already mentioned you can build the two lines without using an extra function. For example "line1" becomes line1 = " |" * (board_size - 1) > > # these are used for loop/flow control > b = 0 # this is used to tell which line needs to be printed > c = 0 # this controls the slicing to tell the board where to start 'temp_row' > # this generates the board on the fly > for row in range(board_size*4-1): > if(b == 0 or b == 2): > print(line1) > elif(b == 3): > print(line2) > elif(b == 1): > # since these rows are dynamic they are called 'temp_row' > # and are reset each time a new one is made > temp_row = '' > for cell in master[c:c+board_size]: > if(int(cell[0])>= 100): > temp_row += '{0}|'.format(cell[0]) > if(int(cell[0])>= 10): > temp_row += '{0} |'.format(cell[0]) > else: > temp_row += ' {0} |'.format(cell[0]) > c += board_size # this is how this variable determines where > to start next time > temp_row = temp_row[:-1] # need to get rid of extra '|' at end of line > print(temp_row) > # this is just some loop/flow control > b += 1 > if(b == 4): > b = 0 You can easily simplify your main drawing part: for row in board_size: content_line = master[row] # You have to build the line here print(line1) print(content_line) print(line1) if row < (board_size - 1): print(line2) So no need for "b" and "c" and and all the if-checks. Bye, Andreas From d at davea.name Fri Dec 2 15:13:54 2011 From: d at davea.name (Dave Angel) Date: Fri, 02 Dec 2011 09:13:54 -0500 Subject: [Tutor] unexpected list entry In-Reply-To: References: Message-ID: <4ED8DD22.3050908@davea.name> On 12/02/2011 08:49 AM, surya k wrote: > Hi, > > Just take a look at this small code.. I am just taking a string as input and assigning it as a list. > But I am finding an unexpected entry in the list.. Why this is happening? > > I am using PyScripter IDE. > > > code : > > > #!/usr/bin/env python > > def main(): > pass > > if __name__ == '__main__': > main() > > print "Flames: " > name1 = raw_input('enter name 1') > > ListName1 = list(name1) > print name1 > print ListName1 > > > Output: > > Flames: > foo > [u'f', u'o', u'o'] > > > Observe the last line.. it isn't showing [ 'f', 'o', 'o'] > Why is that "u" coming in the middle from no where ?? > The u"" notation just says it's a unicode string. No more confusing than the [] meaning it's a list. Neither is the content of the object, just showing you textually what the type is. You should also print repr(name1) to see if it is likewise a unicode string. I presume it's already unicode when returned by raw_input(). My puzzle is how you got unicode strings, if you've shown your entire program. In Python3, all strings are unicode, so it wouldn't bother to say so. Besides, your code has a syntax error in it, if it's supposed to be Python 3.x You probably need to identify your particular version of Python, and the platform (OS) you're running it on. But it could be affected by your IDE (Pyscripter), or by a site.py or other implicitly loaded module. You can check for the former by running the script from a command shell. -- DaveA From suryak at live.com Fri Dec 2 16:47:15 2011 From: suryak at live.com (surya k) Date: Fri, 2 Dec 2011 21:17:15 +0530 Subject: [Tutor] unexpected list entry In-Reply-To: <4ED8DD22.3050908@davea.name> References: <4ED8DD22.3050908@davea.name> Message-ID: Thanks for the information about unicode. Actually, I am using python 2.7 in Windows XP. IDE: PyScripter. So, I run the same code in IDLE (Python 2.7).. Its working. It isn't showing the list in unicode format! I've used PyScripter many times before and worked on lists.. but I never faced any problem like this -------------------------------------------------- From: "Dave Angel" Sent: Friday, December 02, 2011 7:43 PM To: "surya k" Cc: "Python Tutor" Subject: Re: [Tutor] unexpected list entry > On 12/02/2011 08:49 AM, surya k wrote: >> Hi, >> >> Just take a look at this small code.. I am just taking a string as input >> and assigning it as a list. >> But I am finding an unexpected entry in the list.. Why this is happening? >> >> I am using PyScripter IDE. >> >> >> code : >> >> >> #!/usr/bin/env python >> >> def main(): >> pass >> >> if __name__ == '__main__': >> main() >> >> print "Flames: " >> name1 = raw_input('enter name 1') >> >> ListName1 = list(name1) >> print name1 >> print ListName1 >> >> >> Output: >> >> Flames: >> foo >> [u'f', u'o', u'o'] >> >> >> Observe the last line.. it isn't showing [ 'f', 'o', 'o'] >> Why is that "u" coming in the middle from no where ?? >> > The u"" notation just says it's a unicode string. No more confusing than > the [] meaning it's a list. Neither is the content of the object, just > showing you textually what the type is. You should also print > repr(name1) to see if it is likewise a unicode string. I presume it's > already unicode when returned by raw_input(). > > My puzzle is how you got unicode strings, if you've shown your entire > program. In Python3, all strings are unicode, so it wouldn't bother to > say so. Besides, your code has a syntax error in it, if it's supposed to > be Python 3.x > > You probably need to identify your particular version of Python, and the > platform (OS) you're running it on. > > But it could be affected by your IDE (Pyscripter), or by a site.py or > other implicitly loaded module. > You can check for the former by running the script from a command shell. > > -- > > DaveA > > From suryak at live.com Fri Dec 2 16:52:22 2011 From: suryak at live.com (surya k) Date: Fri, 2 Dec 2011 21:22:22 +0530 Subject: [Tutor] unexpected list entry In-Reply-To: <4ED8DD22.3050908@davea.name> References: <4ED8DD22.3050908@davea.name> Message-ID: One more thing I want to mention.. I think there is a problem in the IDE itself. I have faced some problems with this IDE before... (Not with this) Could you please tell me a free python IDE (No Eclipse/ Netbeans) -------------------------------------------------- From: "Dave Angel" Sent: Friday, December 02, 2011 7:43 PM To: "surya k" Cc: "Python Tutor" Subject: Re: [Tutor] unexpected list entry > On 12/02/2011 08:49 AM, surya k wrote: >> Hi, >> >> Just take a look at this small code.. I am just taking a string as input >> and assigning it as a list. >> But I am finding an unexpected entry in the list.. Why this is happening? >> >> I am using PyScripter IDE. >> >> >> code : >> >> >> #!/usr/bin/env python >> >> def main(): >> pass >> >> if __name__ == '__main__': >> main() >> >> print "Flames: " >> name1 = raw_input('enter name 1') >> >> ListName1 = list(name1) >> print name1 >> print ListName1 >> >> >> Output: >> >> Flames: >> foo >> [u'f', u'o', u'o'] >> >> >> Observe the last line.. it isn't showing [ 'f', 'o', 'o'] >> Why is that "u" coming in the middle from no where ?? >> > The u"" notation just says it's a unicode string. No more confusing than > the [] meaning it's a list. Neither is the content of the object, just > showing you textually what the type is. You should also print > repr(name1) to see if it is likewise a unicode string. I presume it's > already unicode when returned by raw_input(). > > My puzzle is how you got unicode strings, if you've shown your entire > program. In Python3, all strings are unicode, so it wouldn't bother to > say so. Besides, your code has a syntax error in it, if it's supposed to > be Python 3.x > > You probably need to identify your particular version of Python, and the > platform (OS) you're running it on. > > But it could be affected by your IDE (Pyscripter), or by a site.py or > other implicitly loaded module. > You can check for the former by running the script from a command shell. > > -- > > DaveA > > From d at davea.name Fri Dec 2 17:06:27 2011 From: d at davea.name (Dave Angel) Date: Fri, 02 Dec 2011 11:06:27 -0500 Subject: [Tutor] unexpected list entry In-Reply-To: References: <4ED8DD22.3050908@davea.name> Message-ID: <4ED8F783.7090706@davea.name> (You top-posted. Put your remarks AFTER whatever you quote from earlier messages) On 12/02/2011 10:47 AM, surya k wrote: > Thanks for the information about unicode. > > Actually, I am using python 2.7 in Windows XP. > IDE: PyScripter. > > So, I run the same code in IDLE (Python 2.7).. Its working. It isn't > showing the list in unicode format! Nothing to do with list. Reread my remarks. The string is apparently unicode, presumably from the raw_input() call. The IDE must be changing the type of stdin to make it unicode. Did you try print repr(name1) ? I'll bet that's also a unicode string. And you tried it in another IDE, IDLE. But the key question is how it behaves in raw Windows, from a command prompt. The user of your code is unlikely to set up your particular IDE to run something you've written. As for an IDE, the only free one I use is emacs. I've heard good things about pywin (or something like that), a free IDE that comes with the free ActiveState python. The Active State python also includes some extensions specifically for Windows, and to make it easier to use Windows dll's and com objects. I used to use the ActiveState stuff when I used Windows. The following material is out of order, but I left it in anyway, for some context. > > I've used PyScripter many times before and worked on lists.. but I never > faced any problem like this > > -------------------------------------------------- > From: "Dave Angel" > Sent: Friday, December 02, 2011 7:43 PM > To: "surya k" > Cc: "Python Tutor" > Subject: Re: [Tutor] unexpected list entry > >> On 12/02/2011 08:49 AM, surya k wrote: >>> Hi, >>> >>> Just take a look at this small code.. I am just taking a string as >>> input and assigning it as a list. >>> But I am finding an unexpected entry in the list.. Why this is >>> happening? >>> >>> I am using PyScripter IDE. >>> >>> >>> code : >>> >>> >>> #!/usr/bin/env python >>> >>> def main(): >>> pass >>> >>> if __name__ == '__main__': >>> main() >>> >>> print "Flames: " >>> name1 = raw_input('enter name 1') >>> >>> ListName1 = list(name1) >>> print name1 >>> print ListName1 >>> >>> >>> Output: >>> >>> Flames: >>> foo >>> [u'f', u'o', u'o'] >>> >>> >>> Observe the last line.. it isn't showing [ 'f', 'o', 'o'] >>> Why is that "u" coming in the middle from no where ?? >>> >> The u"" notation just says it's a unicode string. No more confusing >> than the [] meaning it's a list. Neither is the content of the object, >> just showing you textually what the type is. You should also print >> repr(name1) to see if it is likewise a unicode string. I presume it's >> already unicode when returned by raw_input(). >> >> My puzzle is how you got unicode strings, if you've shown your entire >> program. In Python3, all strings are unicode, so it wouldn't bother to >> say so. Besides, your code has a syntax error in it, if it's supposed >> to be Python 3.x >> >> You probably need to identify your particular version of Python, and >> the platform (OS) you're running it on. >> >> But it could be affected by your IDE (Pyscripter), or by a site.py or >> other implicitly loaded module. >> You can check for the former by running the script from a command shell. >> >> -- >> >> DaveA >> >> > -- DaveA From wprins at gmail.com Fri Dec 2 17:21:43 2011 From: wprins at gmail.com (Walter Prins) Date: Fri, 2 Dec 2011 16:21:43 +0000 Subject: [Tutor] unexpected list entry In-Reply-To: References: <4ED8DD22.3050908@davea.name> Message-ID: Hi, On 2 December 2011 15:52, surya k wrote: > One more thing I want to mention.. > I think there is a problem in the IDE itself. I have faced some problems > with this IDE before... (Not with this) > It may be worth reporting those problems (what were they?), this is after all an open source project, whatever issues you've seen may just get fixed. http://code.google.com/p/pyscripter/issues/list Also, seeing as this unicode issue isn't neccesarily a bug as such from what I can tell, is it really wise to suddenly decide to switch IDE's on that basis (even if you had some other issues also?) Isn't this more a case that you need to understand what's actually happening rather than run to (by the sounds of things yet another) Python environment? Could you please tell me a free python IDE (No Eclipse/ Netbeans) > Well I quite like Eclipse (as far as big heavyweight IDE's go) but you say No Eclipse unfortunately. "SPE" (Stani's Python Editor) comes to mind, though I've not used it in a while. http://sourceforge.net/projects/spe/ But again, should you not rather get to the bottom of your current issue rather than have a little unicode string issue cause you to change IDE's? Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Fri Dec 2 17:48:33 2011 From: suryak at live.com (surya k) Date: Fri, 2 Dec 2011 22:18:33 +0530 Subject: [Tutor] unexpected list entry In-Reply-To: <4ED8F783.7090706@davea.name> References: <4ED8DD22.3050908@davea.name> <4ED8F783.7090706@davea.name> Message-ID: -------------------------------------------------- From: "Dave Angel" Sent: Friday, December 02, 2011 9:36 PM To: "surya k" Cc: "Python Tutor" Subject: Re: [Tutor] unexpected list entry > (You top-posted. Put your remarks AFTER whatever you quote from earlier > messages) > > On 12/02/2011 10:47 AM, surya k wrote: >> Thanks for the information about unicode. >> >> Actually, I am using python 2.7 in Windows XP. >> IDE: PyScripter. >> >> So, I run the same code in IDLE (Python 2.7).. Its working. It isn't >> showing the list in unicode format! > > Nothing to do with list. Reread my remarks. The string is apparently > unicode, presumably from the raw_input() call. The IDE must be changing > the type of stdin to make it unicode. > > Did you try print repr(name1) ? I'll bet that's also a unicode > string. > > And you tried it in another IDE, IDLE. But the key question is how it > behaves in raw Windows, from a command prompt. The user of your code is > unlikely to set up your particular IDE to run something you've written. > > As for an IDE, the only free one I use is emacs. I've heard good things > about pywin (or something like that), a free IDE that comes with the free > ActiveState python. The Active State python also includes some extensions > specifically for Windows, and to make it easier to use Windows dll's and > com objects. I used to use the ActiveState stuff when I used Windows. > > The following material is out of order, but I left it in anyway, for some > context. >> >> I've used PyScripter many times before and worked on lists.. but I never >> faced any problem like this >> >> -------------------------------------------------- >> From: "Dave Angel" >> Sent: Friday, December 02, 2011 7:43 PM >> To: "surya k" >> Cc: "Python Tutor" >> Subject: Re: [Tutor] unexpected list entry >> >>> On 12/02/2011 08:49 AM, surya k wrote: >>>> Hi, >>>> >>>> Just take a look at this small code.. I am just taking a string as >>>> input and assigning it as a list. >>>> But I am finding an unexpected entry in the list.. Why this is >>>> happening? >>>> >>>> I am using PyScripter IDE. >>>> >>>> >>>> code : >>>> >>>> >>>> #!/usr/bin/env python >>>> >>>> def main(): >>>> pass >>>> >>>> if __name__ == '__main__': >>>> main() >>>> >>>> print "Flames: " >>>> name1 = raw_input('enter name 1') >>>> >>>> ListName1 = list(name1) >>>> print name1 >>>> print ListName1 >>>> >>>> >>>> Output: >>>> >>>> Flames: >>>> foo >>>> [u'f', u'o', u'o'] >>>> >>>> >>>> Observe the last line.. it isn't showing [ 'f', 'o', 'o'] >>>> Why is that "u" coming in the middle from no where ?? >>>> >>> The u"" notation just says it's a unicode string. No more confusing >>> than the [] meaning it's a list. Neither is the content of the object, >>> just showing you textually what the type is. You should also print >>> repr(name1) to see if it is likewise a unicode string. I presume it's >>> already unicode when returned by raw_input(). >>> >>> My puzzle is how you got unicode strings, if you've shown your entire >>> program. In Python3, all strings are unicode, so it wouldn't bother to >>> say so. Besides, your code has a syntax error in it, if it's supposed >>> to be Python 3.x >>> >>> You probably need to identify your particular version of Python, and >>> the platform (OS) you're running it on. >>> >>> But it could be affected by your IDE (Pyscripter), or by a site.py or >>> other implicitly loaded module. >>> You can check for the former by running the script from a command shell. >>> >>> -- >>> >>> DaveA >>> >>> >> > > > -- > > DaveA > Dave, I am now puzzled.. I don't understand but the list is now not showing unicode. I just restarted the IDE and rewrote the code again! however, I tried print repr(name1), it didn't show me any unicode notation. From d at davea.name Fri Dec 2 19:07:35 2011 From: d at davea.name (Dave Angel) Date: Fri, 02 Dec 2011 13:07:35 -0500 Subject: [Tutor] unexpected list entry In-Reply-To: References: <4ED8DD22.3050908@davea.name> <4ED8F783.7090706@davea.name> Message-ID: <4ED913E7.1050208@davea.name> On 12/02/2011 11:48 AM, surya k wrote: > > > > Dave, I am now puzzled.. I > don't understand but the list is now not showing unicode. I just > restarted the IDE and rewrote the code again! > > however, I tried print repr(name1), it didn't show me any unicode notation. > > > Well, since the symptom went away, the test of the repr(name1) doesn't tell us anything one way or the other. i suspect there's a configurable setting in your IDE as to whether you want to use Unicode or not, for raw_input. The IDE is probably intercepting the standard readline code and supplying its own, perhaps in order to support some special keys that tell the IDE to do various things to your program. Anyway, one theory would be that this setting somehow got activated, but restarting the IDE changed it back to its default. Have you looked for a mailing list for that program? There is usually some form of interaction with most non-trivial open-source projects. -- DaveA From alan.gauld at btinternet.com Fri Dec 2 19:53:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 02 Dec 2011 18:53:01 +0000 Subject: [Tutor] unexpected list entry In-Reply-To: References: <4ED8DD22.3050908@davea.name> Message-ID: On 02/12/11 15:52, surya k wrote: > Could you please tell me a free python IDE (No Eclipse/ Netbeans) There are lots and IDEs are very personal choices. It depends what you want. Netbeans/eclipse are very heavyweight and have functionality overload. But lighweight IDEs like IDLE and Pythonwin might be too basic. There are others like SPE and emacs(great if you already know/use emacs!) and even the tools in wxPython... There are some web pages comparing the most popular ones, try a Google search. Alan G. From fomcl at yahoo.com Fri Dec 2 20:10:53 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 2 Dec 2011 11:10:53 -0800 (PST) Subject: [Tutor] xtended document properties (dsofile.dll) Message-ID: <1322853053.69038.YahooMailNeo@web110701.mail.gq1.yahoo.com> Hello, I'd like to read extended document properties using the OLE file property reader (dsofile.dll). I know it's also possible with pywin32, but we don't have that in our office. http://support.microsoft.com/kb/224351 http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8422 I'd like to extract the Last Author property from a whole bunch of xls files but I am failing in the earliest stages. Using the VB code below, can anybody give me some pointers for the Python code? import? cstypes, os os.chdir(os.path.abspath(".")) dso = ctypes.windll.dsofile print dso.DSOFile.OleDocumentProperties # Error! Her's the VB code I grabbed from the internet somewhere: ??????? Dimfilename AsString= "c:\test.doc" ??????? Dimdso AsDSOFile.OleDocumentProperties ??????? dso = NewDSOFile.OleDocumentProperties ??????? dso.Open(filename.Trim, True, ? ??????? DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess) ??????? Console.WriteLine(dso.SummaryProperties.Author) ??????? Console.WriteLine(dso.SummaryProperties.ByteCount) ??????? Console.WriteLine(dso.SummaryProperties.CharacterCount) ??? ????Console.WriteLine(dso.SummaryProperties.CharacterCountWithSpaces) ??????? Console.WriteLine(dso.SummaryProperties.Comments) ??????? Console.WriteLine(dso.SummaryProperties.Company) ??????? Console.WriteLine(dso.SummaryProperties.DateCreated) ??????? Console.WriteLine(dso.SummaryProperties.DateLastSaved) ??????? Console.WriteLine(dso.SummaryProperties.LastSavedBy) ??????? Console.WriteLine(dso.SummaryProperties.LineCount) ??????? Console.WriteLine(dso.SummaryProperties.PageCount) ??????? Console.WriteLine(dso.SummaryProperties.ParagraphCount) ??????? Console.WriteLine(dso.SummaryProperties.RevisionNumber) ??????? Console.WriteLine(dso.SummaryProperties.Subject) ??????? Console.WriteLine(dso.SummaryProperties.Title)??????? Console.WriteLine(dso.SummaryProperties.WordCount) Thank you in advance! Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.hall5447 at gmail.com Sat Dec 3 09:31:02 2011 From: michael.hall5447 at gmail.com (Michael Hall) Date: Sat, 3 Dec 2011 00:31:02 -0800 Subject: [Tutor] Question Message-ID: # 1) a perfect number is a positive integer that is equal to the # sum of its proper positive divisors,excluding the number itself. # for example, 6 is a perfect number because it is evenly divisible # by 1, 2 and 3 - all of it's divisors - and the sum 1 + 2 + 3 = 6. # a) write a function, getDivisors(), that returns a list of all # of the positive divisors of a given number. for example - # result = getDivisors(24) # print(result) # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" def main(): num = int(input('Please Enter a Number: ')) getDivisors(num) def getDivisors(num): my_list = [] sum = 0 for number in range(1, num, 10000): if num % number == 0: print([1, 2, 3]) sum += num print('The sum is ', sum) if sum == num: print(num, 'is a perfect number') else: print(num, 'is not a perfect number') main() Andreas and others "Thank you for your help. I am still having an issues. I went to the links and they were very helpful. Here is my problem. If you enter the number 6 the program is just what the teacher wants. My problem is if you enter any other number it is wrong. AGAIN, I AM NOT. I REPEAT I AM NOT ASKING YOU OR ANY OF YOU TO WRITE MY PROGRAM OR DO MY HOMEWORK. I am asking for a solution to the problem. The program has been written I just need help. Thank you in advance. On Fri, Dec 2, 2011 at 1:55 AM, Andreas Perstinger wrote: > On 2011-12-02 08:22, Michael Hall wrote: > >> I am still not understanding what it is I am being asked to do. >> > > Ok, forget about your working program and just concentrate on question > 1a): > > > > # a) write a function, getDivisors(), that returns a list of all > > # of the positive divisors of a given number. for example - > > # result = getDivisors(24) > > # print(result) > > # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" > > I suppose you know how functions and lists works, do you? > You have to write a function named "getDivisors" which takes one argument > (a number) and returns a list. Nothing more, nothing less. > > You started right with the line > > def getDivisors(num): > > but in all your attempts you have never returned a value. Do you know how > a function can return something? > > In your case you have to return a list. Therefore you have to build this > list inside the function. You don't need to print the values or calculate a > sum, just add every divisor to the list. I'm sure you have learned already > how lists works, haven't you? > > If you have problems understanding functions and lists, you should re-read > these parts in your learning material or in the online tutorial: > http://docs.python.org/py3k/**tutorial/introduction.html#**lists > http://docs.python.org/py3k/**tutorial/controlflow.html#** > defining-functions > http://docs.python.org/py3k/**tutorial/datastructures.html#**more-on-lists > > > I am asking if you are given the following question how would you >> write the program. >> > > Sorry, we won't write the program for you. You have to do it yourself. We > will just try to give you some hints - if you carefully read the links I've > mentioned you'll find an example which comes close to yours :-). > > Bye, Andreas > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Dec 3 10:29:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 03 Dec 2011 09:29:37 +0000 Subject: [Tutor] Question In-Reply-To: References: Message-ID: On 03/12/11 08:31, Michael Hall wrote: > # a) write a function, getDivisors(), that returns a list of all > # of the positive divisors of a given number. This is a very clear statement of what you need to do. > def getDivisors(num): > my_list = [] > sum = 0 > for number in range(1, num, 10000): > > if num % number == 0: > print([1, 2, 3]) > sum += num > > print('The sum is ', sum) > if sum == num: > print(num, 'is a perfect number') > else: > print(num, 'is not a perfect number') > problem. If you enter the number 6 the program is just what the teacher > wants. My problem is if you enter any other number it is wrong. Even for 6 it is NOT what the teacher wants. Your function PRINTS the answer the teacher asked for a function that RETURNS the answer. These are different things. Do you understand the difference? Also the reason it works for 6 is because you hard coded the answer for 6: > if num % number == 0: > print([1, 2, 3]) You only ever print [1,2,3]. You are not finding the divisors you are just printing [1,2,3]. Similarly the teacher did not ask you to test/report whether the number was perfect in the function, only to get the list of divisors. You need to strip the function back to the minimum to do what you were asked to do. def getDivisors(num): my_list = [] for x in range (1,num): # if is x a divisor of num # add x to my_list return my_list I've left the commented lines for you to complete. But that is ALL you need for part (a) of the assignment. You might need a main() function to test it, but it will simply print the result. Something like: def main(): print getDivisors(24) As it is you are trying to do way too much and making your function more complicated than it needs to be. You can tweak it to make it more efficient later, but for now stick to the simplest thing that can possibly work and solve the problem you were asked to solve. Once you have part (a) working part (b) of the assignment becomes easy. But get (a) working before attempting (b). At the moment you are mixing the two together and making it more difficult. And that is one of the lessons from the homework. In programming, if you split a task down into smaller chunks it becomes easier. If you try to solve everything in one place it is much harder. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Sat Dec 3 11:14:25 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 3 Dec 2011 10:14:25 +0000 Subject: [Tutor] Question In-Reply-To: References: Message-ID: Hello Michael, On 3 December 2011 08:31, Michael Hall wrote: > Andreas and others "Thank you for your help. I am still having an issues. > I went to the links and they were very helpful. Would you mind explaining exactly how they helped you? :) > Here is my problem. If you enter the number 6 the program is just what the > teacher wants. Well, to be pedantic no, it's not just what the teacher wants. The problem states: # a) write a function, getDivisors(), that returns a list of all # of the positive divisors of a given number. for example - # result = getDivisors(24) # print(result) # would yield: "[ 1, 2, 3, 4, 6, 8, 12]" As your solution stands, the function getDivisors(num) that you have posted does not return anything at all. So you've not actually solved part a) of this problem yet at all. In the solution of part a) you should have the above snippet of code somewhere in your program, and it should return the list as described when run. My problem is if you enter any other number it is wrong. It is wrong because you have the answer for 6 hardcoded inside of your getDivisors() function. In other words, the *only* list your function can return is [1,2,3] as that's what it returns explicitly. To belabor the point further: You never actually build the result list you want to return later in the function. Also, this problem is actually trying to work/solve the bigger problem of deciding whether a given number input by the user is actually a perfect number, rather than the first problem of writing a function to find the divisors of a given number. However, you simply cannot go and work on the bigger problem before you have a demonstrably working solution to part a), that is, a working getDivisors() function that actually returns a list of divisors for a given number, correctly, for arbitrary input. Do not pass go, do not collect $200 or ?200 before you've completed this task. ;) I would submit your real problem is not that the numer returned is wrong, the real problem is that you don't seem to understand the basic building blocks needed to solve this problem e.g: a) how to use function calls to return results b) working with Python lists (putting items into them, passing them around etc.) You absolutely must get a conceptual handle on calling functions and returning results and working with lists in order to be able to solve this. If I put the following requirement to you: "Write a function that returns the square of the number given to it" ... would you be able how to solve it? If not, what problems do you run into/what do you not understand? If I then put the following requirement to you: "Write a function that will return the square of every number in the list given to it (as a return list)" ... would you be able to solve it? If not, what problems do you run into/what do you not understand? I'd suggest trying the above questions and posting back your solution(s) to them to help us establish that you do understanding functions and lists. Finally, allow me to point out that you're top posting, that is, you're posting your responses to previous emails at the top. Please note that the convention on this list is to bottom-post, or at least to follow responses **below** relevant parts of emails inline, hence preserving the context in easy reading order for both the participants and people who may not have followed/read the question/answers provided up to that point. If some people bottom post and some top post it can become very difficult to follow who said what when and makes helping on a list like this more work than it would otherwise be. Please help the people on this list trying to help you by respecting this convention, thanks. Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Sun Dec 4 08:47:57 2011 From: suryak at live.com (surya k) Date: Sun, 4 Dec 2011 13:17:57 +0530 Subject: [Tutor] where python is used in real world Message-ID: I don't understand why python doesn't provide executable files for the source code. I am using py2exe for building executables and I found that, it doesn't completely change code into binary but creates dll files and python libraries to run that particular code. This process makes program very large although it isn't. 1. Why doesn't python doesn't offer executable file ? 2. If one wants to make a commercial software using python, how can he hide the code? 3. However, if one wants to make an open source software, as python doesn't offer executable files, how people make those so as to distribute their products to people? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlybrand at gmail.com Sun Dec 4 09:45:30 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Sun, 4 Dec 2011 00:45:30 -0800 Subject: [Tutor] Python Saved the Day Message-ID: No question. Last weekend I buckled down and learned as much Python as I could (just because I have had an interest to do so for a while). When I got to work on Monday, there was a serious database issue that needed addressing. As I was trying to assess the situation, I employed Python to help me do my data analysis. I was able to sort through all the issues, develop a corrective action plan and verify its accuracy, all in Python. Plan was successfully implemented at 6PM today and all is well again. It was a good week. -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sun Dec 4 09:51:59 2011 From: wescpy at gmail.com (wesley chun) Date: Sun, 4 Dec 2011 00:51:59 -0800 Subject: [Tutor] Python Saved the Day In-Reply-To: References: Message-ID: Congrats! I love hearing stuff like this... keep them coming! I'm curious as to how Python was able to help you get your job done this time (without going into anything confidential naturally). What was it about the language? Or was it specific Python modules/packages you used for the analysis? Does anyone else have similar stories? (I think I may be biased as I use Python for everything, trouble or otherwise, so I can't tell the difference anymore!) cheers, -wesley On Sun, Dec 4, 2011 at 12:45 AM, Mark Lybrand wrote: > No question. Last weekend I buckled down and learned as much Python as I > could (just because I have had an interest to do so for a while). When I > got to work on Monday, there was a serious database issue that needed > addressing. As I was trying to assess the situation, I employed Python to > help me do my data analysis. I was able to sort through all the issues, > develop a corrective action plan and verify its accuracy, all in Python. > Plan was successfully implemented at 6PM today and all is well again. It > was a good week. > > -- > Mark :) -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlybrand at gmail.com Sun Dec 4 10:00:10 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Sun, 4 Dec 2011 01:00:10 -0800 Subject: [Tutor] Fwd: Python Saved the Day In-Reply-To: References: Message-ID: Forgot to include the list. Sorry. ---------- Forwarded message ---------- From: Mark Lybrand Date: Sun, Dec 4, 2011 at 12:59 AM Subject: Re: [Tutor] Python Saved the Day To: wesley chun The quick process of trying out different ideas, first in IDLE and then in script was a biggie. List comprehensions rocked. RE of course (but I still have some stuff to learn about the differences in Python as compared to Perl 5). I was using odbc module to connect to SQL first, but quickly moved to pyodbc and was much happier. The problem was an application that uses tables from two separate databases. The database server was moved, but the old one was not disconnected. Further, a hosts file forced one office to continue to update the old server. The tables (12 in total) were rife with foreign key relationships that needed to be maintained. Don't misunderstand. I am a total noob in Python. And everything I wrote are total hacks. But it was fun, it was quick and it was accurate. Oh. One thing that delighted me to no end. I had a main script that I was using for processing. But would have to make separate scripts for more specific analysis of problems that would appear. The ability to import my main script and use the functions and constants I defined there was a godsend. Oh, and did I mention list comprehensions :) Mark On Sun, Dec 4, 2011 at 12:51 AM, wesley chun wrote: > Congrats! I love hearing stuff like this... keep them coming! I'm curious > as to how Python was able to help you get your job done this time (without > going into anything confidential naturally). What was it about the > language? Or was it specific Python modules/packages you used for the > analysis? > > Does anyone else have similar stories? (I think I may be biased as I use > Python for everything, trouble or otherwise, so I can't tell the difference > anymore!) > > cheers, > -wesley > > > On Sun, Dec 4, 2011 at 12:45 AM, Mark Lybrand wrote: > >> No question. Last weekend I buckled down and learned as much Python as >> I could (just because I have had an interest to do so for a while). When I >> got to work on Monday, there was a serious database issue that needed >> addressing. As I was trying to assess the situation, I employed Python to >> help me do my data analysis. I was able to sort through all the issues, >> develop a corrective action plan and verify its accuracy, all in Python. >> Plan was successfully implemented at 6PM today and all is well again. It >> was a good week. >> >> -- >> Mark :) > > > > -- > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.chun : wescpy-gmail.com : @wescpy > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -- Mark :) -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Sun Dec 4 10:13:27 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Sun, 4 Dec 2011 09:13:27 +0000 Subject: [Tutor] Python Saved the Day In-Reply-To: References: Message-ID: <1033084696-1322990009-cardhu_decombobulator_blackberry.rim.net-1471053520-@b11.c12.bise7.blackberry> We had a challenge recently where all of our internal department names changed, and due to our intranet system, we had to modify our Active Directory to reflect the new names. This meant changing all usernames, public drives and pc names. We were also migrating the profiles from one profile server to another at the same time. A manual test run of our procedure determined a 6 hour process per depart. Worried for the strain this would have on my sanity, I spent 3 hours automating this process in python, cutting the execution time down to 30 minutes of watching success messages printing to the screen. This saved an estimated 55 man hours of work. Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: wesley chun Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Sun, 4 Dec 2011 00:51:59 To: Mark Lybrand Cc: Subject: Re: [Tutor] Python Saved the Day _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From timomlists at gmail.com Sun Dec 4 11:00:16 2011 From: timomlists at gmail.com (Timo) Date: Sun, 04 Dec 2011 11:00:16 +0100 Subject: [Tutor] where python is used in real world In-Reply-To: References: Message-ID: <4EDB44B0.2080801@gmail.com> Op 04-12-11 08:47, surya k schreef: > I don't understand why python doesn't provide executable files for the > source code. > I am using py2exe for building executables and I found that, it > doesn't completely change code into binary but creates dll files and > python libraries to run that particular code. This process makes > program very large although it isn't. I think Windows is the only operating system which doesn't come with Python pre-installed (except some exotic ones). But on Windows, you do install JVM to run Jave programs, .NET, Flash, ... why not the Python interpreter to run Python programs? Cheers, Timo > 1. Why doesn't python doesn't offer executable file ? > 2. If one wants to make a commercial software using python, how can he > hide the code? > 3. However, if one wants to make an open source software, as python > doesn't offer executable files, how people make those so as to > distribute their products to people? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From robert.sjoblom at gmail.com Sun Dec 4 12:12:17 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 4 Dec 2011 12:12:17 +0100 Subject: [Tutor] Python Saved the Day In-Reply-To: <1033084696-1322990009-cardhu_decombobulator_blackberry.rim.net-1471053520-@b11.c12.bise7.blackberry> References: <1033084696-1322990009-cardhu_decombobulator_blackberry.rim.net-1471053520-@b11.c12.bise7.blackberry> Message-ID: I had a situation where there were 300+ files needed to be renamed to standardized naming; the problem was that each group that had worked on the project had their own naming convention and group tag. One group had date_number_subnumber_grouptag where others might have grouptag_date_number_subnumber and others dropped the grouptag and subnumbers and it was a very messy deal. I wrote a script that fixed the naming to date_number_subnumber_abbreviated-grouptag. The resulting script is a hack, for sure (there was simply no way to build a script that could deal with all variations of the names at once, so it had to run several times checking for different things). Instead of working directly with the files while trying things out, I wrote a simple script that yanked all the filenames and created empty copies of the files with a simple list comprehension, then I could try out the script without using the real files (or copying the actual files with content, which would have taken much longer). There was one file, after the script ran, that I just couldn't get to without specifically naming it in the script. But renaming one file manually instead of 300+ feels like an acceptable cost. -- best regards, Robert S. From tvssarma.omega9 at gmail.com Sun Dec 4 13:24:58 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Sun, 4 Dec 2011 17:54:58 +0530 Subject: [Tutor] Python Saved the Day In-Reply-To: <1033084696-1322990009-cardhu_decombobulator_blackberry.rim.net-1471053520-@b11.c12.bise7.blackberry> References: <1033084696-1322990009-cardhu_decombobulator_blackberry.rim.net-1471053520-@b11.c12.bise7.blackberry> Message-ID: We shoud have a new tag say [Superman Python] for posts like these. :D -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Dec 4 14:58:03 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 05 Dec 2011 00:58:03 +1100 Subject: [Tutor] Prime Factorization Tool In-Reply-To: References: Message-ID: On 12/02/2011 12:15 AM, Robert Sjoblom wrote: > So I've recently started poking at the Project Euler site, because I > feel that I need to practice writing code. For those of you interested > in solving the problems on your own I advice you to not read this, as > it will spoil the solution. > > Problem 3 is this: > The prime factors of 13195 are 5, 7, 13 and 29. > > What is the largest prime factor of the number 600851475143 ? > > I came up with this pseudocode: > #pseudocode: > # divide by x until non-prime is found: > # if not remainder: > # check if it's prime or not: > # if not prime: exit loop > # if not prime: store in variable > # increment x by 1 > > Here are the functions I came up with: > > def isprime(n): > if n == 1: > return False > for x in range(2, n): > if n % x == 0: > return False > else: > return True > > def factorization(n): > factor = 0 > x = 2 > while True: > if n % x == 0: > if isprime(x): > factor = x > else: > return factor > x += 1 > > This, however, feels horribly inefficient. Is there a better way to do > it? I think most of my problems stem from my weak mathematical skills, > to be honest. This wasn't too bad, but even for problems 1 and 2 I've > relied on brute forcing the answer instead of looking for a > mathematical solution. > With regards to primes, check out Sieve of Erastothenes; if you need to generate a "list of primes" instead of doing just "primality check", the sieve method will be much, much faster. From alan.gauld at btinternet.com Sun Dec 4 15:01:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 04 Dec 2011 14:01:54 +0000 Subject: [Tutor] where python is used in real world In-Reply-To: References: Message-ID: On 04/12/11 07:47, surya k wrote: > I don't understand why python doesn't provide executable files for the > source code. > 1. Why doesn't python doesn't offer executable file ? Because python is an interpreted language like Java, early Visual Basic and many other languages. It would be difficult to build a true native machine code compiler for Python and still retain the features that make it so productive. Some partial compilers exist but they cannot cover all of the features of the language. As programmers we have to make the trade-off of speed of development versus speed of execution, memory usage, ease of deployment and many other factors. This is what engineers do in any type of engineering, software engineering is no different. It's all about choosing the most appropriate compromise for the problem at hand. > I am using py2exe for building executables and I found that, it doesn't > completely change code into binary but creates dll files and python > libraries to run that particular code. This process makes program very > large although it isn't. Define large? It's not usually very large compared to things like Microsoft Office or even single applications like Photoshop. Compare the size of Visio against the Python open source equivalent: Dia. And remember that if you had to code up in C all the things you get as part of the Python language your short program would be much much bigger. A program's real size is determined by the functions it performs not the number of lines of source code. (If you want an objective measure calculate the Function Point metric) So yes, for trivial programs Pythons overheads will be higher than, say , C. But for real world applications the differences will be much less, and Python will often be smaller. And if the Python interpreter is already installed even small apps become comparable. > 2. If one wants to make a commercial software using python, how can he > hide the code? Use py2exe... Or only deploy the compiled modules (.pyc) or rely on a license agreement and the threat of litigation. Is hiding the source code a necessary thing? For many years it was common for commercial applications to come with the source code. In fact the very first PC that I used came with a manual containing the full assembler listing of the BIOS... It is a relatively modern idea that we should try to hide how our code works from the userts. And it is mainly paranoia that makes us think that not shipping source code makes our programs "safe" from copying. It is the ideas and concepts of code that need protecting - via patents - not the source. Just compare how many office apps are out there. Very similar to use but very different source code. Its easy to recreate a feature once you see how it works. Hiding the source makes very little difference and provided you have legal protection you can sue anyone who steals your code - after all they will have the same difficulty! > 3. However, if one wants to make an open source software, as python > doesn't offer executable files, how people make those so as to > distribute their products to people? Just take a look at the many open source applications written in Python. Essentially its the same as applications written in Java or .NET. The user has to install the execution environment ass wekl as the app. But they only need to do it once. And in Linux and MacOS Python is already installed alongside Java and Perl etc. But we have already given you all of this information in replies to your previous post on the same theme a few days ago. And to pick up on your subject line, Python is used extensively in "the real world" in many areas outside of developing shrink-wrapped commercial applications. If you are writing bespoke code for a contract then the client will expect you to provide the source code as normal practice. And provided the app does what was asked and runs quickly enough they are unlikely to care that it was written in Python (in factthey may prefer it since Python is comparatively easy to maintain). Similarly. Python is used in many large scale IT operations to provide support and test tools (Google being a good example) or for rapid prototyping. You can find many examples of real-world Python on the Python.org website, just look under success stories: http://www.python.org/about/success/ And browse the job adverts... http://www.python.org/community/jobs/ -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Sun Dec 4 15:24:56 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 4 Dec 2011 08:24:56 -0600 Subject: [Tutor] Python Saved the Day In-Reply-To: References: Message-ID: On Sun, Dec 4, 2011 at 2:51 AM, wesley chun wrote: > > Does anyone else have similar stories? (I think I may be biased as I use > Python for everything, trouble or otherwise, so I can't tell the difference > anymore!) > I work in a .NET shop, and the last project I worked on required us to re-implement a report system that was doing a variety of complicated things (due to the nature of the older tech used). This required us to run and re-run our version to compare against the old, many many times. My teammate started doing the comparisons by hand using a merge tool... after watching that process for about 5 minutes, I went ahead and wrote a quick Python script (<30 lines) that would compare the two reports. I ended out extending the script to a full blown text-program with some nice menus and things, and all told probably spent less than an hour or two writing scripts that saved... probably at least 10 man hours of comparisons, probably much more than that when you factor in the exhaustion from doing such a menial task. The tools that I found extremely useful: 1) Modules - I used re and csv fairly heavily. One piece of the report was textual and the re module allowed me to easily parse out the important information from each report. The other one was a spreadsheet, so csv readers were quite nice 2) List comprehensions/generator expressions - mutating the data from text to something that I could really use took two or three passes. Being able to express this in two or three lines was invaluable 3) Syntax (including dynamic binding) - the terse syntax allowed me to express what I wanted to express, with no extra "stuff" (e.g. End With) Personally I wish I was in your shoes (using it for everything), but I'm a huge Pythonista so that should hardly be a surprise ;) (and definitely wouldn't be a surprise for any of my former classmates. I was quite the evangelist... and still am) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Sun Dec 4 15:45:00 2011 From: python at bdurham.com (python at bdurham.com) Date: Sun, 04 Dec 2011 09:45:00 -0500 Subject: [Tutor] Python Saved the Day In-Reply-To: References: Message-ID: <1323009900.5146.140661007210785@webmail.messagingengine.com> I worked on a large pharma sales data warehouse project and we had the need to profile some complex 3rd party data feeds that were poorly documented. I was able to write, test, and run the code (across 500Gb data) to provide the required profiling information in less time than it took to install an evaluation version of a commercial product ... which after several weeks of extensive testing (and hundreds of man hours) never produced the correct results. It amazes me what can done with simple Python scripts and a KISS attitude. Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From modulok at gmail.com Sun Dec 4 17:36:01 2011 From: modulok at gmail.com (Modulok) Date: Sun, 4 Dec 2011 09:36:01 -0700 Subject: [Tutor] where python is used in real world In-Reply-To: References: Message-ID: >> 2. If one wants to make a commercial software using python, how can he >> hide the code? While it's a valid question, it's fun to imagine it in the physical world: "We need to permanently weld the engine compartment closed so that no one can steal our engine ideas." -Modulok- From roadierich at googlemail.com Sun Dec 4 22:59:25 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 4 Dec 2011 21:59:25 +0000 Subject: [Tutor] where python is used in real world In-Reply-To: References: Message-ID: <924BA8D8-A61C-4ECF-8DF1-EB1A0F9E6D1B@googlemail.com> On 4 Dec 2011, at 16:36, Modulok wrote: >>> 2. If one wants to make a commercial software using python, how can he >>> hide the code? > > While it's a valid question, it's fun to imagine it in the physical world: "We > need to permanently weld the engine compartment closed so that no one can steal > our engine ideas." > > -Modulok- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor That's not really a fair analogy: a user can install a patch for an application that's gone wrong without ever seeing any source code. The same can't be said of engines. A closer analogy would be Beethoven shredding his scores. Rich "RoadieRich" Lovely There are 10 types of people in the world: Those who know binary, Those who do not, And those who are off by one. From steve at pearwood.info Sun Dec 4 23:31:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 05 Dec 2011 09:31:53 +1100 Subject: [Tutor] where python is used in real world In-Reply-To: References: Message-ID: <4EDBF4D9.5070504@pearwood.info> surya k wrote: > I don't understand why python doesn't provide executable files for the > source code. I am afraid that you are confused. Python source code *are* executable. They would hardly be *programming* code if you can't execute them. They're just not stand-alone executable. They require a virtual machine environment to execute, just like Flash, .Net, Java, Javascript, Perl, PHP, .ASP, and hundreds of other languages. > I am using py2exe for building executables and I found that, it doesn't > completely change code into binary but creates dll files and python > libraries to run that particular code. This process makes program very > large although it isn't. I am afraid you are again working under a misunderstanding. The program *is* very large because most of the "smarts" is in the virtual machine environment. The source code on its own is small, but it doesn't do anything without the environment. Again, this is how Java works, and .Net, and Flash, to say nothing of other languages. The Java Runtime Environment (JRE) for Java 5 is 15 MB; the .Net 3.5 runtime is 197 MB. A small py2exe bundle is 6 MB. Python offers a rich, safe environment for the programmer, and that requires a rich, complex feature set. Programming in Python isn't just flipping bits and adding numbers. That requires a large infrastructure to support it. In 1984 the Macintosh API was maybe 100 functions; today, plain Python is probably fifty times larger than that, and if you add graphics perhaps 500 times larger. Do you think you get this code for free? It has to be *somewhere*. > 1. Why doesn't python doesn't offer executable file ? If you mean a stand-alone, minimal application like you used to get back in 1980 when hand-coding the absolute least amount of C or Pascal code that could be compiled to do the job, well, that's a hard thing to do, and it is unnecessary, so it doesn't get done. > 2. If one wants to > make a commercial software using python, how can he hide the code? There is lots of commercial code which is open source. Just ask Ubuntu and Red Hat for starters. Why do you want to hide the code? What are you afraid of? Tell us what your fear is, and we can perhaps help you. > However, if one wants to make an open source software, as python doesn't > offer executable files, how people make those so as to distribute their > products to people? You just make the Python runtime environment a requirement, exactly as people do with other languages. -- Steven From gollumgreg407366 at gmail.com Tue Dec 6 03:31:33 2011 From: gollumgreg407366 at gmail.com (Greg Nielsen) Date: Mon, 5 Dec 2011 21:31:33 -0500 Subject: [Tutor] Splitting a Tuple in Python 2.7 Message-ID: The following gets returned from a function that I am calling. (120, 400) While I can use the Tuple as is in my program, I would like the ability to change one or even both of the numbers depending on other events that happen. So here is my question, is there a way to either 1) save each part of the Tuple into a seperate variable or 2) edit just one part of the Tuple without knowing or affecting the other number. Thanks for the help! Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Tue Dec 6 03:50:38 2011 From: eire1130 at gmail.com (eire1130 at gmail.com) Date: Tue, 6 Dec 2011 02:50:38 +0000 Subject: [Tutor] Fw: Splitting a Tuple in Python 2.7 Message-ID: <868698604-1323139840-cardhu_decombobulator_blackberry.rim.net-899605838-@b5.c28.bise6.blackberry> Meant to send to group Sent from my Verizon Wireless BlackBerry -----Original Message----- From: eire1130 at gmail.com Date: Tue, 6 Dec 2011 02:48:00 To: Greg Nielsen Reply-To: eire1130 at gmail.com Subject: Re: [Tutor] Splitting a Tuple in Python 2.7 s =(1,2) x = s[0] Printing x above will print the digit 1. You cando the same for the second index as well Sent from my Verizon Wireless BlackBerry -----Original Message----- From: Greg Nielsen Sender: tutor-bounces+eire1130=gmail.com at python.org Date: Mon, 5 Dec 2011 21:31:33 To: Subject: [Tutor] Splitting a Tuple in Python 2.7 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From d at davea.name Tue Dec 6 04:07:35 2011 From: d at davea.name (Dave Angel) Date: Mon, 05 Dec 2011 22:07:35 -0500 Subject: [Tutor] Splitting a Tuple in Python 2.7 In-Reply-To: References: Message-ID: <4EDD86F7.3040305@davea.name> On 12/05/2011 09:31 PM, Greg Nielsen wrote: > The following gets returned from a function that I am calling. > > (120, 400) > > While I can use the Tuple as is in my program, I would like the ability to > change one or even both of the numbers depending on other events that > happen. So here is my question, is there a way to either 1) save each part > of the Tuple into a seperate variable or 2) edit just one part of the Tuple > without knowing or affecting the other number. Thanks for the help! > > Greg > To extract the individual elements, you can use [0] and [1] However, you cannot change an element, since a tuple is immutable. You have to build a new tuple. Or you can use a list, which is not immutable. a = (3, 5) print a[0] # you get 3 b = a[0], 42 print b # you get (3, 42) c,d = a # c gets 3 and d gets 5 -- DaveA From suryak at live.com Tue Dec 6 05:30:39 2011 From: suryak at live.com (surya k) Date: Tue, 6 Dec 2011 10:00:39 +0530 Subject: [Tutor] how to link GUI app to the code Message-ID: I have designed a application using WxGlade but I don't know how to link it to my code and run it.Could you please tell me? at least it would be helpful if you could show me relevant tutorials. Here is the part of the application code that is generated using WxGlade. self.panel_6 = wx.Panel(self.notebook_main_home, -1) self.label_title = wx.StaticText(self.notebook_main_home, -1, "Enter Names", style=wx.ALIGN_CENTRE) self.panel_7 = wx.Panel(self.notebook_main_home, -1) self.label_name1 = wx.StaticText(self.notebook_main_home, -1, "Name 1", style=wx.ALIGN_CENTRE) self.text_ctrl_name1 = wx.TextCtrl(self.notebook_main_home, -1, "") self.text_ctrl_output = wx.TextCtrl(self.notebook_main_home, -1, "", style=wx.TE_READONLY) self.label_name2 = wx.StaticText(self.notebook_main_home, -1, "Name 2") self.text_ctrl_name2 = wx.TextCtrl(self.notebook_main_home, -1, "") self.panel_5 = wx.Panel(self.notebook_main_home, -1) self.panel_8 = wx.Panel(self.notebook_main_home, -1) self.button_submit = wx.Button(self.notebook_main_home, -1, "Submit") self.panel_9 = wx.Panel(self.notebook_main_home, -1) Those bold lines are where I suppose to give controls. 1. self.text_ctrl_name1 : here I need to give input name12. self.text_ctrl_name2 : here I need to give input name23. self.button_submit: The program should take the above input values after clicking this button4. self.text_ctrl_output : here I need to get output. As far as my program is concerned, its just a small string manipulation program based upon the input names. How could I do this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Dec 6 10:18:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Dec 2011 09:18:01 +0000 Subject: [Tutor] how to link GUI app to the code In-Reply-To: References: Message-ID: On 06/12/11 04:30, surya k wrote: > I have designed a application using WxGlade but I don't know how to link > it to my code and run it. Glade generates wxPython code. In wxPython we bind methods to widgets using the Bind() method. Here is an example: self.Bind(wx.EVT_BUTTON, self.OnSubmit, self.button_submit) Where: EVT_BUTTON is a standard event time defined in wxPython. self.OnSubmit is your event handler method self.button_submit is your submit button widget It would be useful for you to go through the wxPython tutorials. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From o0MB0o at hotmail.se Tue Dec 6 13:10:08 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 6 Dec 2011 13:10:08 +0100 Subject: [Tutor] Creating arbitrary number of destinations. (GUI program) In-Reply-To: References: Message-ID: Hi again :) First of all, I thought the topic name was correct. Arbitrary means as many as one would like or a realistic number right? I am back with one of my TKinter programs and with new questions: I have written a program where you can book train tickets. At first , there were only a fixed number of seats availible to book, but I have now manged to create as many seats as I would like. That's nice. However, this was only for one destination. I want to be able to have as many destinations as I want. The numbers of seats should be the same for every destination. I sat the entire evening and afternoon trying to get it to work yesterday, but I have no idea on how to accomplish this. I tried using for i in range() and while loops, without success sadly. Here is the code so far. I translated all variable name and function names to English, so sorry if I missed something. from tkinter import* import tkinter as tk import os NUMBEROFCHAIRS=32 class ChooseDestinationWindow(Frame): def __init__(self,master): super(ChooseDestinationWindow,self).__init__(master) self.grid() self.create_different_destinations() def create_different_destinations(self): self.destination1=Button(self, text="Destination1",command=self.Destination1_function) self.destination1.grid() self.destination2=Button(self, text="Destination2") self.destination2.grid() self.destination3=Button(self,text="Destination3") self.destination3.grid() def Destination1_function(self): class Seats_Destination1(tk.Button): def __init__(self,master,index): text=str(index+1) self.OCCUPIED="red" self.FREE="green" super(Seats_Destination1, self).__init__(master, text=text, bg=self.FREE, command=self.PressedChair) self.filename2 = "Destination1{}.txt".format(index+1) self.occupied = False if os.path.exists(self.filename2): self["bg"]=self.OCCUPIED self.OCCUPIED=True def PressedChair(self): self.occupied = not self.occupied if self.occupied: self["bg"] = self.OCCUPIED text_file=open(self.filename2,"w") text_file.write(self.filename2) text_file.close() else: self["bg"] = self.FREE try: os.remove(self.filename2) except: pass class Destination1_Chairs(Frame): def __init__(self,master): super(Destination1_Chairs,self).__init__(master) self.grid() self.Create_Chairs() Satt till 32. def Create_Chairs(self): for index in range(NUMBEROFCHAIRS): button = Seats_Destination1(self, index) row, column = divmod(index, 4) button.grid(row=row, column=column) root=Tk() root.title("Booking Window") app=Destination1_Chairs(root) root.mainloop() root=Tk() root.title("Choose your destination") root.geometry("900x200") app=ChooseDestinationWindow(root) root.mainloop() Thanks for your time and help! Mic From andre.hilbig at googlemail.com Tue Dec 6 13:39:55 2011 From: andre.hilbig at googlemail.com (=?ISO-8859-15?Q?Andr=E9_Hilbig?=) Date: Tue, 06 Dec 2011 13:39:55 +0100 Subject: [Tutor] How can I realize a Echolot with Python on a Linux machine? Message-ID: <4EDE0D1B.1050807@googlemail.com> I am doing a special education project in Physic about the speed of sound. I will do some experiments to measure it. At the end my pupils should be able to build a little echolot. I want to have a very simple buildup, so I thought of doing it with the soundcard of a computer and python. This means that I want to use a mic to throw out a signal that gets saved by a speaker. Then I can calculate the distance with the time-difference and make a noise or something like that to know how far away the next wall is. The algorithm is very easy, but I do not have the know-how and the time to build a library that accesses the hardware. Does anybody have some ideas how I can do this? A special library would be nice, that can access the soundcard and measure the time difference between two signals in realtime. I was thinking of a pulsing sinus made by the speaker of the soundcard (or maybe by an extern device with a fixed frequency) and measured by the mic. I had tested some things with aubio (http://aubio.org/) to calculate the time difference, but then I would have to write something like a deamon to handle the soundcard. And there is always the time problem, because it should do everything in realtime. Maybe someone knows a special library that does the most work for me. My main function should only do the calculation of the distance and get the time by a simple deamon, etc. wkr Andr? From wprins at gmail.com Tue Dec 6 14:08:50 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 6 Dec 2011 13:08:50 +0000 Subject: [Tutor] How can I realize a Echolot with Python on a Linux machine? In-Reply-To: <4EDE0D1B.1050807@googlemail.com> References: <4EDE0D1B.1050807@googlemail.com> Message-ID: Hi, On 6 December 2011 12:39, Andr? Hilbig wrote: > A special library would > be nice, that can access the soundcard and measure the time difference > between two signals in realtime. > > This seems apropriate: http://stackoverflow.com/questions/1936828/how-get-sound-input-from-microphone-in-python-and-process-it-on-the-fly Short URL: http://is.gd/uCMV37 It suggests PyAudio (Windows) and PyALSAAudio (Linux) and provides an example script for Linux using PyALSAAudio and I surmise you should be able to do what you want with it. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From geonyoro at gmail.com Tue Dec 6 18:17:38 2011 From: geonyoro at gmail.com (George Nyoro) Date: Tue, 6 Dec 2011 14:17:38 -0300 Subject: [Tutor] Interprocess communication Message-ID: Hey guys, Really want to thank all of you for helping and bearing with some of us and the questions we ask around here. I was making a gtk app sometime ago to copy files from a cd or dvd to my hard disk since the normal ubuntu copy thing would stop when it encountered some error, so I needed one that read through errors or none. I did in two modules: one having gtk code and the other having the copy code, then id import the copy code into gtk. The thing is that when the gtk called the copy module to do so, the process would take long and so the application would become none responsive. Also, there was a progress bar that was supposed to get data after the copy module copied some block so that it displayed amouint copied so far but it wouldnt display progress, even when it was supposed to do so from the return value of a function. Can anyone show me how to run the gtk and copy code as separate processes since this seems to be the only way that the application graphics wont hang? Thanks in advance. From alan.gauld at btinternet.com Tue Dec 6 19:56:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Dec 2011 18:56:10 +0000 Subject: [Tutor] Creating arbitrary number of destinations. (GUI program) In-Reply-To: References: Message-ID: On 06/12/11 12:10, Mic wrote: > Hi again :) > First of all, I thought the topic name was correct. Arbitrary means as > many as one would like or a realistic number right? Yes, but its not clear what you mean by it. > I have written a program where you can book train tickets. At first , > there were only a fixed number of seats availible to book, but I have > now manged to create as many seats as I would like. That's nice. Well done. > However, this was only for one destination. I want to be able > to have as many destinations as I want. > The numbers of seats should be the same for every destination. OK, How will this work. One common technique for capturing these kinds of requirements is to write a "story" of how the user interacts with the system. (Sometimes called a "Usecase") Imagine that the system exists, how would you describe the interaction? Do it as a dialog, for example: 1 User logs into application 2 System presents welcome screen 3 User selects first destination from dropp down list 4 System presents seat chooser screen with available seats displayed 5 User selects seat(*) 6 System updates display 7 System displays price to user 8 User validates choice 9 System returns to home screen and confirms the booking 10 User selects next destination(*) 11 Repeat from step 4-9 5A Alternately user rejects all choices and cancels booking 10A Alternately user logs out. By doing that it will be clearer how youi want the system to respond. At the moment we can only guess what you are thinking the system should do. > I sat the entire evening and afternoon trying to get it to work > yesterday, but I have no idea on how to accomplish this. I tried using > for i in range() and while loops, without success sadly. And I can't imagine what you were trying to do. Literally. I have no idea how this arbitrary number of destinations would be chosen by the user. One at a time, or many in one go? From a list, or typed at a prompt? And what should the system do? Give the same seat for each trip? Or offer different seat booking screens per destination? You need to get the vision clear. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From suryak at live.com Tue Dec 6 19:57:30 2011 From: suryak at live.com (surya k) Date: Wed, 7 Dec 2011 00:27:30 +0530 Subject: [Tutor] unable to run file though dir path included Message-ID: I have included the path directory of the file but still I couldn't run it!. 1. I created a .pth file and wrote all required path list's and saved in "site-packages" of python dir.( python\Lib\Site-packages). 2. I also included python path ( c:\python27\) in system path so as to run it using command prompt. Now when I use this command to run a file "foo.py" at command prompt ( run>cmd ) command: "python foo.py".. it isn't running. The following error is shown. " python: can't open file 'foo': [ Errno 2] no such file or directory". What should I do? But the following command didn't give me an error in python shell " import foo" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Dec 6 20:04:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Dec 2011 19:04:01 +0000 Subject: [Tutor] Interprocess communication In-Reply-To: References: Message-ID: On 06/12/11 17:17, George Nyoro wrote: > Hey guys, > Really want to thank all of you for helping and bearing with > some of us and the questions we ask around here. I was making a gtk > app sometime ago to copy files from a cd or dvd to my hard disk since > the normal ubuntu copy thing would stop when it encountered some > error, so I needed one that read through errors or none. For me the normal copy thing is the cp command. It reads through errors quite happily... I assume you mean one of the graphical file managers abailable in Ubuntu? > I did in two modules: one having gtk code and the other having the > copy code, then id import the copy code into gtk. The thing is that > when the gtk called the copy module to do so, the process would take > long and so the application would become none responsive. How are you doing the copy? If its a long loop or using os.walk() then you need to put it in a separate thread. Thats probably the best solution. Alternartively invoke the cp command line and run it in the background(with &), but then you won;t get suvch good error reports etc... Otherwise break it into chunks so you only copy a few files at a time and then return to the GUI. But that will slow the copy process even more! > Can anyone show me how to run the gtk and copy code as separate > processes since this seems to be the only way that the application > graphics wont hang? Thanks in advance. You don't need separate processes just separate threads. Check the Python documentation for a threading tutorial. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bodsda at googlemail.com Tue Dec 6 20:09:18 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 6 Dec 2011 19:09:18 +0000 Subject: [Tutor] unable to run file though dir path included In-Reply-To: References: Message-ID: <566839922-1323198557-cardhu_decombobulator_blackberry.rim.net-957477054-@b11.c12.bise7.blackberry> This is only a guess, but when your typing 'python foo.py' the command prompt is looking for foo.py in its path and can't find it, then it throws the error. When your in the interpreter, python has already updated its path so it can find your file. I don't think adding the directory to 'python\Lib\Site-packages' is doing what you think it should do. Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: surya k Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Wed, 7 Dec 2011 00:27:30 To: Python Tutor Subject: [Tutor] unable to run file though dir path included _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From bodsda at googlemail.com Tue Dec 6 20:10:46 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Tue, 6 Dec 2011 19:10:46 +0000 Subject: [Tutor] Interprocess communication In-Reply-To: References: Message-ID: <338122018-1323198645-cardhu_decombobulator_blackberry.rim.net-1791090702-@b11.c12.bise7.blackberry> If you invoke the system 'cp' command though, it may not be possible to have a progress bar because the command will only talk back when it exits. Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Alan Gauld Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Tue, 06 Dec 2011 19:04:01 To: Subject: Re: [Tutor] Interprocess communication On 06/12/11 17:17, George Nyoro wrote: > Hey guys, > Really want to thank all of you for helping and bearing with > some of us and the questions we ask around here. I was making a gtk > app sometime ago to copy files from a cd or dvd to my hard disk since > the normal ubuntu copy thing would stop when it encountered some > error, so I needed one that read through errors or none. For me the normal copy thing is the cp command. It reads through errors quite happily... I assume you mean one of the graphical file managers abailable in Ubuntu? > I did in two modules: one having gtk code and the other having the > copy code, then id import the copy code into gtk. The thing is that > when the gtk called the copy module to do so, the process would take > long and so the application would become none responsive. How are you doing the copy? If its a long loop or using os.walk() then you need to put it in a separate thread. Thats probably the best solution. Alternartively invoke the cp command line and run it in the background(with &), but then you won;t get suvch good error reports etc... Otherwise break it into chunks so you only copy a few files at a time and then return to the GUI. But that will slow the copy process even more! > Can anyone show me how to run the gtk and copy code as separate > processes since this seems to be the only way that the application > graphics wont hang? Thanks in advance. You don't need separate processes just separate threads. Check the Python documentation for a threading tutorial. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From o0MB0o at hotmail.se Tue Dec 6 20:27:51 2011 From: o0MB0o at hotmail.se (Mic) Date: Tue, 6 Dec 2011 20:27:51 +0100 Subject: [Tutor] Creating arbitrary numbers of destinations. (GUI program) In-Reply-To: References: Message-ID: >> However, this was only for one destination. I want to be able >> to have as many destinations as I want. >> The numbers of seats should be the same for every destination. >OK, How will this work. >One common technique for capturing these kinds of requirements is to >write a "story" of how the user interacts with the system. (Sometimes >called a "Usecase") I>magine that the system exists, how would you describe the interaction? >Do it as a dialog, for example: >1 User logs into application >2 System presents welcome screen >3 User selects first destination from dropp down list >4 System presents seat chooser screen with available seats displayed >5 User selects seat(*) >6 System updates display >7 System displays price to user >8 User validates choice >9 System returns to home screen and confirms the booking >10 User selects next destination(*) >11 Repeat from step 4-9 >5A Alternately user rejects all choices and cancels booking >10A Alternately user logs out. >By doing that it will be clearer how youi want the system to respond. At >the moment we can only guess what you are thinking the system should do. Alright, my apologise for being unclear about this. To begin with, it is in the code you create how many destinations you want. In my example I created three destination buttons. The user is not supposed to change anything when the program is running. As you can see in the code, I am using a variable "NUMBEROFCHAIRS". If you want 30 chairs you simply set the value to 30 for that value. If you want 50 chairs you set the value to 50 and so on. I want to do this in a similiar way, but for destinations instead. So if I press the destination1 button, one window with 32 buttons appear. The filename should be destination one. If I press destination2 button, one window with 32 buttons appear, and the filename for the saved files should be destination2. You asked why I was trying to get this to work with for and while loops? I figured that since that was the way I created the chairs I figured I could do the same to create destinations. I will write on of these Usercases so what I am trying to accomplish is understandably. 1.User starts program. 2.User choose destination1. 3. window with chairs appear. 4.User press one/many of the chairs 5. File is saved with the name of the destination and seat number (ie destination1 seat 2) 6. User close window and is returned to the window with the destinations. 7. He can choose another destination, which repats step 2-6. So it is in the code I should be able to create any number of destinations that I want. Like I have a variable named NUMBERSOFDESTINATIONS=5 for example. Then there should be five destinations buttons. If one is pressed a window with chairs should appear. If a green button is pressed, a file with the name destination(x) and seat(a) should be saved. x is the number of the destination. It should be one if it is the button labeled destination 1 that is clicked, two if the button labeled destination2 is clicked and so on. A is the number of the seat that is clicked. This is already working fine though! I really hope I made my intentions clearer now. Tell me if it is still unclear or confusing! Thanks for your reply! Mic From d at davea.name Wed Dec 7 00:13:52 2011 From: d at davea.name (Dave Angel) Date: Tue, 06 Dec 2011 18:13:52 -0500 Subject: [Tutor] unable to run file though dir path included In-Reply-To: References: Message-ID: <4EDEA1B0.3050709@davea.name> On 12/06/2011 01:57 PM, surya k wrote: > I have included the path directory of the file but still I couldn't run it!. > 1. I created a .pth file and wrote all required path list's and saved in "site-packages" of python dir.( python\Lib\Site-packages). > 2. I also included python path ( c:\python27\) in system path so as to run it using command prompt. > Now when I use this command to run a file "foo.py" at command prompt ( run>cmd ) > command: "python foo.py".. it isn't running. > The following error is shown. > " python: can't open file 'foo': [ Errno 2] no such file or directory". > > What should I do? > But the following command didn't give me an error in python shell > " import foo" > When you're at a cmd prompt, the current directory can be very important. The cmd shell will search the PATH for the exe (python.exe), but nobody does a search for the script file. So if it's not the current directory, you'll have to either: 1) cd to the proper place 2) use a path specification to the file. At this point, it's just a regular filename, and you follow Windows rules to specify its path. Imports are entirely different. They follow search path rules, and do not need (are not permitted) a .py extension. -- DaveA From alan.gauld at btinternet.com Wed Dec 7 00:37:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Dec 2011 23:37:54 +0000 Subject: [Tutor] unable to run file though dir path included In-Reply-To: References: Message-ID: On 06/12/11 18:57, surya k wrote: > I have included the path directory of the file but still I couldn't run it!. > The question is whicvh file? Instead of telling us what you did it woyuld be more useful to cut n paste the actual command used into the mail (including the prompt since it usually shows which directory you are in) > 1. I created a .pth file and wrote all required path list's and saved in > "site-packages" of python dir. > ( python\Lib\Site-packages). That only helps with imports. > 2. I also included python path ( c:\python27\) in system path so as to > run it using command prompt. That will help Wiondows find python.exe but has no affect omn whether Windows can see foo.py > Now when I use this command to run a file "foo.py" at command prompt ( > run>cmd ) > > command: "python foo.py".. it isn't running. > > The following error is shown. > > " python: can't open file 'foo': [ Errno 2] no such file or directory". Notice that the error says it is foo.py that it cannot find. You need to provide the path to foo.py (or change into the directory where it lives) > But the following command didn't give me an error in python shell > > " import foo" Thats because import uses the PYTHONPATH and your .pth file to find files. Windows doesn't know about them. Incidentally the easiest way to run foo.py in Windows is simply to double click it in Windows explorer... Although you may need to add a pause line (eg raw_input("Hit enter to quit") ) at the end to see the output. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Dec 7 00:39:47 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Dec 2011 23:39:47 +0000 Subject: [Tutor] Interprocess communication In-Reply-To: <338122018-1323198645-cardhu_decombobulator_blackberry.rim.net-1791090702-@b11.c12.bise7.blackberry> References: <338122018-1323198645-cardhu_decombobulator_blackberry.rim.net-1791090702-@b11.c12.bise7.blackberry> Message-ID: On 06/12/11 19:10, bodsda at googlemail.com wrote: > If you invoke the system 'cp' command though, it may > not be possible to have a progress bar because the > command will only talk back when it exits. Not if you use the -v (verbose) option. That slows it down but does provide a listing of every file copied. You can use the Subprocess module to read that output and update your status bar. But its not trivial I agree. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Dec 7 00:46:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Dec 2011 23:46:57 +0000 Subject: [Tutor] Creating arbitrary numbers of destinations. (GUI program) In-Reply-To: References: Message-ID: On 06/12/11 19:27, Mic wrote: > I will write on of these Usercases so what I am trying to accomplish is > understandably. Thanks, although you actually missed a step somewhere - the bit where the user selects how many chairs... But ignoring that... Where do we select how many destinations you want? If we stick to 3 for now: > 1.User starts program. > 2.User choose destination1. > 3. window with chairs appear. > .... selects chairs > 7. He can choose another destination, which repats step 2-6. OK, So the real question is how to create three buttons each of which can launch a window to select chairs. But this is just the same as your chairs window. You just create buttons and link them to a function which opens the chair window. And if you do want more buttons you just do exactly what you did with the chairs... > I really hope I made my intentions clearer now. Tell me if it is still > unclear or confusing! Clearer, although there are still some bits missing - like how the user selects the number of destinations/chairs. I'll take a look at the code you posted and follow up on that in a separate post. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Dec 7 00:53:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Dec 2011 23:53:28 +0000 Subject: [Tutor] Creating arbitrary number of destinations. (GUI program) In-Reply-To: References: Message-ID: On 06/12/11 12:10, Mic wrote: > from tkinter import* > import tkinter as tk You only need one of these two lines, the second is probably best. > import os > NUMBEROFCHAIRS=32 > > class ChooseDestinationWindow(Frame): > def __init__(self,master): > super(ChooseDestinationWindow,self).__init__(master) > self.grid() > self.create_different_destinations() > > def create_different_destinations(self): > self.destination1=Button(self, > text="Destination1",command=self.Destination1_function) > self.destination1.grid() > > self.destination2=Button(self, text="Destination2") > self.destination2.grid() > > self.destination3=Button(self,text="Destination3") > self.destination3.grid() OK, that should work except you haven't set the command value to the function that creates the seat booking window. You probabvly also want to set the filename here too. > def Destination1_function(self): > class Seats_Destination1(tk.Button): I see you are still defining your classes inside yoyur functions. It really is more normal (and useful) to define them all at the top level. It also makes your functions easier to read! > class Destination1_Chairs(Frame): This is the thing you want to call from your destination buttons. So create a method in the top level window that creates one of these objects. > root=Tk() > root.title("Booking Window") > app=Destination1_Chairs(root) > root.mainloop() > > > root=Tk() > root.title("Choose your destination") > root.geometry("900x200") > app=ChooseDestinationWindow(root) > root.mainloop() And you still have multiple root objects and multiple mainloops. That's bad practice and it will bite you eventually. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From o0MB0o at hotmail.se Wed Dec 7 16:16:01 2011 From: o0MB0o at hotmail.se (Mic) Date: Wed, 7 Dec 2011 16:16:01 +0100 Subject: [Tutor] Creating arbitrary numbers of destinations. (GUI) In-Reply-To: References: Message-ID: >Thanks, although you actually missed a step somewhere - the bit where >the user selects how many chairs... But ignoring that... >Where do we select how many destinations you want? >If we stick to 3 for now: Actually, the user never selects how many destinations that he wants. It is in the code you should be able to change it. As seen in my code, you change the amount of chairs by changing the value of the variable NUMBERSOFCHAIRS. I want to be able to create as many destinations as I would like in a smiliar way, provided there isn't a better way to go. Was this understandable? >> 1.User starts program. >> 2.User choose destination1. >> 3. window with chairs appear. >> .... selects chairs >> 7. He can choose another destination, which repats step 2-6. >OK, So the real question is how to create three buttons each of which >can launch a window to select chairs. But this is just the same as your >chairs window. You just create buttons and link them to a function which >opens the chair window. >And if you do want more buttons you just do exactly what you did with >the chairs... Okay, I will try that! > I really hope I made my intentions clearer now. Tell me if it is still > unclear or confusing! >Clearer, although there are still some bits missing - like how the user >selects the number of destinations/chairs. As stated above, the users aren't allowed to change the number of destinations and chairs, it is supposed to be changed in the code, by changing the value of a variable :) >> from tkinter import* >> import tkinter as tk >You only need one of these two lines, the second is >probably best. Okay, thanks! > >import os > >NUMBEROFCHAIRS=32 > > >class ChooseDestinationWindow(Frame): > >def __init__(self,master): > >super(ChooseDestinationWindow,self).__init__(master) >> self.grid() >> self.create_different_destinations() > > def create_different_destinations(self): >> self.destination1=Button(self, >>text="Destination1",command=self.Destination1_function) >> self.destination1.grid() > >> self.destination2=Button(self, text="Destination2") >> self.destination2.grid() > > >self.destination3=Button(self,text="Destination3") >> self.destination3.grid() >OK, that should work except you haven't set the command value to the >function that creates the seat booking window. You probabvly also want >to set the filename here too Hmm, yes but I don't want to write two lines of code for each chair I create, I want them in a for loop, if that is convienient? >> def Destination1_function(self): >> class Seats_Destination1(tk.Button): >I see you are still defining your classes inside yoyur functions. It >really is more normal (and useful) to define them all at the top level. >It also makes your functions easier to read! Really? I actually thinks it is easier to read the code using inner classes, but thats just me probably! > class Destination1_Chairs(Frame): This is the thing you want to call from your destination buttons. So create a method in the top level window that creates one of these objects. >> root=Tk() >> root.title("Booking Window") >> app=Destination1_Chairs(root) >>root.mainloop() > > > >root=Tk() > >root.title("Choose your destination") > >root.geometry("900x200") > >app=ChooseDestinationWindow(root) > >root.mainloop() >And you still have multiple root objects and multiple >mainloops. That's bad practice and it will bite you >eventually. Yes, it actually bit me last week :) I will work on that when I have solved this problem with the destinations:) Thanks for your suggestions! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 94, Issue 20 ************************************* From steve at pearwood.info Wed Dec 7 17:33:54 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Dec 2011 03:33:54 +1100 Subject: [Tutor] unable to run file though dir path included In-Reply-To: References: Message-ID: <4EDF9572.7010401@pearwood.info> surya k wrote: > I have included the path directory of the file but still I couldn't run it!. > 1. I created a .pth file and wrote all required path list's and saved in "site-packages" of python dir.( python\Lib\Site-packages). > 2. I also included python path ( c:\python27\) in system path so as to run it using command prompt. > Now when I use this command to run a file "foo.py" at command prompt ( run>cmd ) > command: "python foo.py".. it isn't running. > The following error is shown. > " python: can't open file 'foo': [ Errno 2] no such file or directory". That error shows that you are NOT calling "python foo.py", as you should, but are calling "python foo". Notice that if the file is missing, the error message prints the file name you give on the command line: [steve at orac ~]$ python foo.py python: can't open file 'foo.py': [Errno 2] No such file or directory (1) Inside the Python environment, you import modules by giving the bare name *without* the file extension: import foo # correct import foo.py # incorrect The import command will search sys.path for the module. sys.path is initialised in part from the environment variable PYTHONPATH and from any .pth files visible to Python. (2) Outside of Python, you are dealing with the command shell, and the command shell rules apply. The PATH (not PYTHONPATH) tells your shell where to find .exe files, but not documents. So you must give the full path to the file: python C:\subdirectory\spam\ham\foo.py or you must give a relative path starting from the current working directory: python ..\ham\foo.py In either case, you *must* give the file extension. (3) The third option is to combine the best of both, by using the -m switch which instructs Python to search the PYTHONPATH for the named module and then execute it: python -m foo -- Steven From geonyoro at gmail.com Wed Dec 7 18:01:49 2011 From: geonyoro at gmail.com (George Nyoro) Date: Wed, 7 Dec 2011 14:01:49 -0300 Subject: [Tutor] Super In tkinter class inheritance Message-ID: I was observing the tkinter code under the topic "Creating arbitrary number of destinations. (GUI program)" in the previous email and saw this super thing: > class ChooseDestinationWindow(Frame): def __init__(self,master): >super(ChooseDestinationWindow,self).__init_ _(master) What exactly does this super method since I have seen it numerous times before and as far as I can see it is not anything the user created himself in the class? From cspears2002 at yahoo.com Wed Dec 7 19:31:06 2011 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 7 Dec 2011 10:31:06 -0800 (PST) Subject: [Tutor] creating a pie chart in Python Message-ID: <1323282666.94038.YahooMailNeo@web39421.mail.mud.yahoo.com> I need to create a pie chart that is referenced by a wiki page.? I am impressed with matplotlib.? Any other good libraries out there? I do need to be able to save the chart as an image file, so it can be linked to the wiki.? My only complaint about matplotlib is that I have not figured out a way to save a graph as an image using a python script.? From what I can tell, you need to save the image interactively through the GUI.? Of course, this might mean that I just do not know a lot about matplotlib. All suggestions are welcome! Chris ? "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "There is no such thing as luck; there is only adequate or inadequate preparation to cope with a statistical universe." -Robert A. Heinlein, "Have Space Suit - Will Travel" "Why do we fall, sir? So that we might learn to pick ourselves up." -Alfred Pennyworth, "Batman Begins" -------------- next part -------------- An HTML attachment was scrubbed... URL: From kliateni at gmail.com Wed Dec 7 20:56:47 2011 From: kliateni at gmail.com (Karim) Date: Wed, 07 Dec 2011 20:56:47 +0100 Subject: [Tutor] creating a pie chart in Python In-Reply-To: <1323282666.94038.YahooMailNeo@web39421.mail.mud.yahoo.com> References: <1323282666.94038.YahooMailNeo@web39421.mail.mud.yahoo.com> Message-ID: <4EDFC4FF.6070202@gmail.com> Le 07/12/2011 19:31, Christopher Spears a ?crit : > I need to create a pie chart that is referenced by a wiki page. I am > impressed with matplotlib. Any other good libraries out there? > > I do need to be able to save the chart as an image file, so it can be > linked to the wiki. My only complaint about matplotlib is that I have > not figured out a way to save a graph as an image using a python > script. From what I can tell, you need to save the image > interactively through the GUI. Of course, this might mean that I just > do not know a lot about matplotlib. > > All suggestions are welcome! > Chris > "I'm the last person to pretend that I'm a radio. I'd rather go out > and be a color television set." > -David Bowie > > "Who dares wins" > -British military motto > > > "There is no such thing as luck; there is only adequate or inadequate > preparation to cope with a statistical universe." > -Robert A. Heinlein, "Have Space Suit - Will Travel" > > > "Why do we fall, sir? So that we might learn to pick ourselves up." > -Alfred Pennyworth, "Batman Begins" > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor With tkinter I made one time a chart so check to be able to do pie one. Another solution is to use pychart cf link below: http://home.gna.org/pychart/ cheers Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Dec 7 23:45:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 07 Dec 2011 22:45:39 +0000 Subject: [Tutor] Super In tkinter class inheritance In-Reply-To: References: Message-ID: On 07/12/11 17:01, George Nyoro wrote: > I was observing the tkinter code under the topic "Creating arbitrary > number of destinations. (GUI program)" in the previous email and saw > this super thing: >> class ChooseDestinationWindow(Frame): def __init__(self,master): >> super(ChooseDestinationWindow,self).__init_ > _(master) > > What exactly does this super method since I have seen it numerous > times before and as far as I can see it is not anything the user > created himself in the class? It's the recommended way to call the super-class version of a method. In older versions of Python it would be done like this: class C(A): def m(self): A.m(self) # call superclass method m() # local code here In later versions of Python it has been possible to use the super() style instead which works better in some cases. In Python v3 it is now the only approved way to call the superclass (although the older way still works for simple cases, but you should just get used to super()... but I'm struggling to follow my own advice! ;-). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Dec 7 23:57:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 07 Dec 2011 22:57:41 +0000 Subject: [Tutor] Creating arbitrary numbers of destinations. (GUI) In-Reply-To: References: Message-ID: On 07/12/11 15:16, Mic wrote: >> OK, that should work except you haven't set the command value to the >> function that creates the seat booking window. You probabvly also want >> to set the filename here too > > Hmm, yes but I don't want to write two lines of code for each chair I > create, I want them in > a for loop, if that is convienient? Yes, remember the technique of defining the data in a file or data structure? Just make the function to launch the chairs take a parameter of the filename. Then pass the filename in using a lambda in the widget definition part of the loop, like this pseudocode: for n in number_of_destinations: filename = make_filename() b = Button(parent, label, color, command=lambda f=filename : ChairWindow(f) ) >> I see you are still defining your classes inside your functions. It >> really is more normal (and useful) to define them all at the top level. >> It also makes your functions easier to read! > > Really? I actually thinks it is easier to read the code using inner > classes, but thats just me probably! Its harder to read because you are splitting your code def FunctionNameHere(args here): some code here some more class Fooo lots of class specific stiuff more more etc/... back to that method again, now where were we????? The class code just acts to separate the function definition and early code fom the main body of code that defines it. And if the class has lots of functions its even more confuising and difficult to be sure where the outer function resumes. Plus of course that the inner class is completely inaccessible outside the function. But one of the greatest benefits of classes is that they allow easy reuse - but only if they are visible! >> class Destination1_Chairs(Frame): > > This is the thing you want to call from your destination buttons. So > create a method in the top level window that creates one of these objects. So as per my pseudo code above you probvably need to add a filename parameter to your init method. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mrsannman at yahoo.com Thu Dec 8 02:17:19 2011 From: mrsannman at yahoo.com (Do youknow who) Date: Wed, 7 Dec 2011 17:17:19 -0800 (PST) Subject: [Tutor] beginner here Message-ID: <1323307039.87981.YahooMailClassic@web114009.mail.gq1.yahoo.com> Im trying to write this program where i make it flip a coin 100 times then tells me the number of heads and tails it came up with. ? this is what I got but it does not run ? # Coin Flip # Demonstrating the While loop import random print("I will flip a coin 100 times and tell you") print(", how many heads and how many tails I got.") coin_rolls = random.randint(1,2) heads = 0 tails = 0 rolls = 0 ? if rolls <= 100: ??? rolls += 1 ??????? elif coin_rolls == 1: ??? heads += 1 elif coin_rolls == 2: ??? tails += 1 else: ??? print("error") print("There was ", heads, "rolls for heads,") print("\nand there was ", tails, " rolls for tails.") input("\n\nPress the enter key to exit.") I end up with 0 rolls for heads and 0 rolls for tails...I have made attempts to put the "coin_rolls = random.randint(1,2)" within the loops but only end up with errors what wrong with my code? -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxskywalker1 at gmail.com Thu Dec 8 02:39:06 2011 From: maxskywalker1 at gmail.com (Max S.) Date: Wed, 7 Dec 2011 20:39:06 -0500 Subject: [Tutor] beginner here In-Reply-To: <1323307039.87981.YahooMailClassic@web114009.mail.gq1.yahoo.com> References: <1323307039.87981.YahooMailClassic@web114009.mail.gq1.yahoo.com> Message-ID: You are using an 'elif' for your 'coin_rolls == 1:'. The 'elif' keyword means that if the last 'if' statement (and any 'elif's behind it) was *not* true, only then will it be executed. Your code could be written as 'if rolls is NOT less than or equal to 100, only then check to see if it is 1 or 2'. Replace your first 'elif' with 'if', and it should work. On Wed, Dec 7, 2011 at 8:17 PM, Do youknow who wrote: > Im trying to write this program where i make it flip a coin 100 times then > tells me the number of heads and tails it came up with. > > this is what I got but it does not run > > # Coin Flip > # Demonstrating the While loop > import random > print("I will flip a coin 100 times and tell you") > print(", how many heads and how many tails I got.") > coin_rolls = random.randint(1,2) > heads = 0 > tails = 0 > rolls = 0 > > if rolls <= 100: > rolls += 1 > > elif coin_rolls == 1: > heads += 1 > elif coin_rolls == 2: > tails += 1 > else: > print("error") > print("There was ", heads, "rolls for heads,") > print("\nand there was ", tails, " rolls for tails.") > input("\n\nPress the enter key to exit.") > > I end up with 0 rolls for heads and 0 rolls for tails...I have made > attempts to put the > "coin_rolls = random.randint(1,2)" within the loops but only end up with > errors > what wrong with my code? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Dec 8 05:15:00 2011 From: d at davea.name (Dave Angel) Date: Wed, 07 Dec 2011 23:15:00 -0500 Subject: [Tutor] beginner here In-Reply-To: References: <1323307039.87981.YahooMailClassic@web114009.mail.gq1.yahoo.com> Message-ID: <4EE039C4.1040509@davea.name> On 12/07/2011 08:39 PM, Max S. wrote: > You are using an 'elif' for your 'coin_rolls == 1:'. The 'elif' keyword > means that if the last 'if' statement (and any 'elif's behind it) was *not* > true, only then will it be executed. Your code could be written as 'if > rolls is NOT less than or equal to 100, only then check to see if it is 1 > or 2'. Replace your first 'elif' with 'if', and it should work. > You top-posted. On this forum, you should put your comments after whatever you're quoting. > On Wed, Dec 7, 2011 at 8:17 PM, Do youknow who wrote: > >> Im trying to write this program where i make it flip a coin 100 times then >> tells me the number of heads and tails it came up with. >> >> this is what I got but it does not run >> >> # Coin Flip >> # Demonstrating the While loop >> import random >> print("I will flip a coin 100 times and tell you") >> print(", how many heads and how many tails I got.") >> coin_rolls = random.randint(1,2) >> heads = 0 >> tails = 0 >> rolls = 0 >> >> if rolls<= 100: >> rolls += 1 >> >> elif coin_rolls == 1: >> heads += 1 >> elif coin_rolls == 2: >> tails += 1 >> else: >> print("error") >> print("There was ", heads, "rolls for heads,") >> print("\nand there was ", tails, " rolls for tails.") >> input("\n\nPress the enter key to exit.") >> >> I end up with 0 rolls for heads and 0 rolls for tails...I have made >> attempts to put the >> "coin_rolls = random.randint(1,2)" within the loops but only end up with >> errors >> what wrong with my code? >> First point is if you're getting errors, you should post the error message, including the full traceback. Or if you get no errors, but the results aren't what you expect, you should indicate what you expected, and how the actual results were different than expected. What you expect is that rolls will be == 100, and that heads and tails will add up to 100. In addition to Max's point, there's another glaring problem here. You don't have a loop of any kind. Your comment indicates it's going to be a while loop, but since you already know how many times you're going to loop, there's no point. Just make it a for loop. for roll in range(100): Then of course the body of the loop will need to be indented. So you have to decide what's going to be inside the loop, and what's initialization, or summary stuff. You will then discover that the order of your code isn't quite right. Work on those two points, and see what you come up with. -- DaveA From shantanoo at gmail.com Thu Dec 8 05:49:46 2011 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Thu, 8 Dec 2011 10:19:46 +0530 Subject: [Tutor] beginner here In-Reply-To: <1323307039.87981.YahooMailClassic@web114009.mail.gq1.yahoo.com> References: <1323307039.87981.YahooMailClassic@web114009.mail.gq1.yahoo.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 08-Dec-2011, at 6:47 AM, Do youknow who wrote: > Im trying to write this program where i make it flip a coin 100 times then tells me the number of heads and tails it came up with. > > this is what I got but it does not run > > # Coin Flip > # Demonstrating the While loop > import random > print("I will flip a coin 100 times and tell you") > print(", how many heads and how many tails I got.") > coin_rolls = random.randint(1,2) > heads = 0 > tails = 0 > rolls = 0 > > if rolls <= 100: > rolls += 1 > > elif coin_rolls == 1: > heads += 1 > elif coin_rolls == 2: > tails += 1 > else: > print("error") > print("There was ", heads, "rolls for heads,") > print("\nand there was ", tails, " rolls for tails.") > input("\n\nPress the enter key to exit.") > > I end up with 0 rolls for heads and 0 rolls for tails...I have made attempts to put the > "coin_rolls = random.randint(1,2)" within the loops but only end up with errors > what wrong with my code? # head(h) --- even number # tail(t) --- odd number # roll(r) --- number of rolls === import random r = 100 h = len([1 for x in range(r) if random.randint(1,1000) % 2]) t = r - h print('There were %d rolls for head and %d rolls for tail.' % (h, t)) === Little more pythonic way... - -- ????? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.11 (Darwin) iQEcBAEBAgAGBQJO4EHrAAoJEJYe6XdHCE0VlvQH/3hhvv4PL75EQe6wyVlUOuSw fJiH8IMqm4BGUsgLOUhGyRETlDD3poI3Ae02zJN0K2VpGrNsqRq4VdN9GNBfHtoC C90eM1dCvyNHWic4Lbo+9UQGDUFXAngeDNnpY7LjNEvjpyVGsog2ptiyIauoY8zy ySun1rvcv+uUChd6+P/IEBppX6cf9ijgWt/zl8B0aCsJleCtOuh4WvTY4yX4upss hQaCDta0L6Tog1SF9PdevJgFENTVK36DEXU43xzqlEYyNLGUBTXUd2DeeKes8GJd kR553QTizOYDwWRgA7ZiJ99zr+oOt1s0wkpb01A8geXXDJo6sCfxbafAmizY18w= =uCdb -----END PGP SIGNATURE----- From andreas.perstinger at gmx.net Thu Dec 8 07:33:16 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 08 Dec 2011 07:33:16 +0100 Subject: [Tutor] creating a pie chart in Python In-Reply-To: <1323282666.94038.YahooMailNeo@web39421.mail.mud.yahoo.com> References: <1323282666.94038.YahooMailNeo@web39421.mail.mud.yahoo.com> Message-ID: <4EE05A2C.7020907@gmx.net> On 2011-12-07 19:31, Christopher Spears wrote: > I do need to be able to save the chart as an image file, so it can be > linked to the wiki. My only complaint about matplotlib is that I > have not figured out a way to save a graph as an image using a python > script. You can save a graph with "matplotlib.plot.savefig()": Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib.pyplot as plot >>> fig = plot.figure(figsize=(8,8)) >>> ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) >>> pie_chart = ax.pie([10, 20, 30, 40]) >>> fig.savefig("piechart.png") More about "savefig()" in the documentation: http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.savefig Bye, Andreas From sunil.techspk at gmail.com Thu Dec 8 10:03:40 2011 From: sunil.techspk at gmail.com (sunil tech) Date: Thu, 8 Dec 2011 14:33:40 +0530 Subject: [Tutor] Dictionary to variable copy Message-ID: *Can i copy the content if a dictionary in to another variable, with out any link between the dictionary & the variable? if so, please teach. * -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Thu Dec 8 11:14:46 2011 From: timomlists at gmail.com (Timo) Date: Thu, 08 Dec 2011 11:14:46 +0100 Subject: [Tutor] Dictionary to variable copy In-Reply-To: References: Message-ID: <4EE08E16.3070207@gmail.com> Op 08-12-11 10:03, sunil tech schreef: > /Can i copy the content if a dictionary in to another variable, with > out any link between the dictionary & the variable? > / Have a look at the copy module [1], or use the builtin dict.copy() method. Cheers, Timo [1] http://docs.python.org/library/copy.html#module-copy > / > if so, please teach. > / > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From suryak at live.com Thu Dec 8 11:59:31 2011 From: suryak at live.com (surya k) Date: Thu, 8 Dec 2011 16:29:31 +0530 Subject: [Tutor] how to calculate program compile time? Message-ID: I'm doing puzzles where we need to write code that works as fast a possible So, how can I check the compile time of my program ?... -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Thu Dec 8 12:19:13 2011 From: suryak at live.com (surya k) Date: Thu, 8 Dec 2011 16:49:13 +0530 Subject: [Tutor] unable to use find(), index() Message-ID: I am using the following code? astr = "foobar"str1 ="foo"astr.find(str1, beg=0, end=3) This is showing the following error Traceback (most recent call last):??File "", line 1, in TypeError: find() takes no keyword arguments I even tried by importing "string" module, but it isn't working. This same problem with find() Could you please help me! From cwitts at compuscan.co.za Thu Dec 8 12:19:04 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 08 Dec 2011 13:19:04 +0200 Subject: [Tutor] how to calculate program compile time? In-Reply-To: References: Message-ID: <4EE09D28.3000909@compuscan.co.za> On 2011/12/08 12:59 PM, surya k wrote: > I'm doing puzzles where we need to write code that works as fast a > possible > > So, how can I check the compile time of my program ?... > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You can use the `timeit` [1] module or outside of Python if you're using Linux you can use `time`. That will give you your total execution time. You can also look at further performance tips [2] if needed. [1] http://docs.python.org/library/timeit.html [2] http://wiki.python.org/moin/PythonSpeed/PerformanceTips -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Dec 8 12:36:14 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 8 Dec 2011 11:36:14 +0000 Subject: [Tutor] unable to use find(), index() In-Reply-To: References: Message-ID: Hi Surya, On 8 December 2011 11:19, surya k wrote: > > >>>astr.find(str1, beg=0, end=3) > This is showing the following error > Traceback (most recent call last): File "", line 1, in > TypeError: find() takes no keyword arguments > See the documentation for the str.find() method here: http://docs.python.org/release/2.5.2/lib/string-methods.html The error says that find() does not take any keyword arguments, and you've supplied 2, (namely, "beg" and "end".) So, try calling find() without trying to specify beg and end as keyword (e.g. named as you've done) arguments. Also read up on keyword arguments (and arguments in general): http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Dec 8 12:37:20 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 08 Dec 2011 13:37:20 +0200 Subject: [Tutor] unable to use find(), index() In-Reply-To: References: Message-ID: <4EE0A170.1030605@compuscan.co.za> On 2011/12/08 01:19 PM, surya k wrote: > I am using the following code > astr = "foobar"str1 ="foo"astr.find(str1, beg=0, end=3) > > This is showing the following error > Traceback (most recent call last): File "", line 1, inTypeError: find() takes no keyword arguments > I even tried by importing "string" module, but it isn't working. > This same problem with find() > Could you please help me! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Your traceback message gives you the reason it's not working, `find() takes no keyword arguments`. The function only takes positional arguments so if you just write `astr.find(str1, 0, 3)` it will work as you expect it to. >>> help(''.find) Help on built-in function find: find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. -- Christian Witts Python Developer // -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Dec 8 12:42:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 08 Dec 2011 22:42:27 +1100 Subject: [Tutor] unable to use find(), index() In-Reply-To: References: Message-ID: <4EE0A2A3.9020402@pearwood.info> surya k wrote: > I am using the following code > astr = "foobar"str1 ="foo"astr.find(str1, beg=0, end=3) You have mangled the code in your email and lost line breaks. Fortunately this is simple enough to fix: astr = "foobar" str1 ="foo" astr.find(str1, beg=0, end=3) Please take more care to post code in PLAIN TEXT, not html "rich text", which may mangle line breaks and break the code. > This is showing the following error > Traceback (most recent call last): File "", line 1, in TypeError: find() takes no keyword arguments > I even tried by importing "string" module, but it isn't working. > This same problem with find() > Could you please help me! Did you read the error message? "find() takes no keyword arguments" This means just what it says: the find method does not take keyword arguments. Do you understand what keyword arguments are? # Wrong, will not work: astr.find(str1, begin=23, end=42) # Right, will work: astr.find(str1, 23, 42) -- Steven From suryak at live.com Thu Dec 8 13:33:25 2011 From: suryak at live.com (surya k) Date: Thu, 8 Dec 2011 18:03:25 +0530 Subject: [Tutor] how to use int and split() simultaneously Message-ID: This is something I am trying to do.. Say, we are entering a string "1 2 3 4 5".so, I want to assign the numbers directly as numbers. how can I do it? I could put that numbers as string but not as number.. strNum = raw_input('enter:').split() I can convert the list into numbers by doing this... for i in range(len(strNum)):? ?strNum[i] = int(strNum[i]). but I feel, its a long process. How can I do it in the shortest possible way?? From cl2dlope at gmail.com Thu Dec 8 14:43:41 2011 From: cl2dlope at gmail.com (=?ISO-8859-1?Q?Dario_Lopez=2DK=E4sten?=) Date: Thu, 8 Dec 2011 14:43:41 +0100 Subject: [Tutor] how to use int and split() simultaneously In-Reply-To: References: Message-ID: oh, yes, no top posting. See below. On Thu, Dec 8, 2011 at 1:33 PM, surya k wrote: > > This is something I am trying to do.. > Say, we are entering a string "1 2 3 4 5".so, I want to assign the numbers > directly as numbers. how can I do it? > I could put that numbers as string but not as number.. > strNum = raw_input('enter:').split() > I can convert the list into numbers by doing this... > for i in range(len(strNum)): strNum[i] = int(strNum[i]). > but I feel, its a long process. How can I do it in the shortest possible > way?? > Using a list comprehension is one example of a compact way of doing it: strNum = raw_input("enter numbers, separated by space: ").split() strNum = [int(x) for x in strNum] You would have to assume that the entire string consists of tokens that can be type cast into integers. If not you get an error: >>> strNum = raw_input("enter numbers, separated by space: ").split() enter numbers, separated by space: 1 2 3 4 5 66 asd >>> strNum = [int(x) for x in strNum] Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): asd In that case a for loop with a try-except would better: strNum = raw_input("enter numbers, separated by space: ").split() num_list = [] for token in strNum: try: num_list.append(int(token)) except ValueError: # Do nothing, fetch the next token continue print repr(num_list) This code gives this result: enter numbers, separated by space: 1 2 3 4 5 66 [1, 2, 3, 4, 5, 66] enter numbers, separated by space: 1 2 3 4 5 66 asd 77 [1, 2, 3, 4, 5, 66, 77] Strictly speaking the "continue" in the except clause is not necessary in this simple example. Hope this helps! /dario -------------- next part -------------- An HTML attachment was scrubbed... URL: From rail.shafigulin at gmail.com Thu Dec 8 15:49:38 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Thu, 8 Dec 2011 09:49:38 -0500 Subject: [Tutor] print method name Message-ID: i created a class and in some instances when i use it call some of its methods i need to print a method name. the online search did produce some results but none of them seem to work for me. for example one of them said just to use __name__ or func_name but it didn't work for me. i'm using python 3.1.1 any help is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Dec 8 16:15:05 2011 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 8 Dec 2011 10:15:05 -0500 Subject: [Tutor] print method name In-Reply-To: References: Message-ID: On Thu, Dec 8, 2011 at 9:49 AM, rail shafigulin wrote: > i created a class and in some instances when i use it call some of its > methods i need to print a method name. the online search did produce some > results but none of them seem to work for me. for example one of them said > just to use __name__ or func_name but it didn't work for me. i'm using > python 3.1.1 > > any help is appreciated. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Can you show the code? This works for me: class A(object): def __init__(self): pass def addr(self,a,b): return a + b a = A() print a.addr.__name__ >>addr -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Dec 8 16:17:30 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 8 Dec 2011 10:17:30 -0500 Subject: [Tutor] print method name In-Reply-To: References: Message-ID: On Thu, Dec 8, 2011 at 9:49 AM, rail shafigulin wrote: > i created a class and in some instances when i use it call some of its > methods i need to print a method name. the online search did produce some > results but none of them seem to work for me. for example one of them said > just to use __name__ or func_name but it didn't work for me. i'm using > python 3.1.1 > > any help is appreciated. > > It would be better if you send us the code you tried. I'm not sure what you are looking to do. When you invoke the method, do you want it to print its own name? class A(object): ... def first(self): ... pass ... >>> a = A() >>> a.first.__name__ 'first' > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Thu Dec 8 16:28:37 2011 From: suryak at live.com (surya k) Date: Thu, 8 Dec 2011 20:58:37 +0530 Subject: [Tutor] how to find index of list with its value Message-ID: Well, we all know to know the value when we have the index of a list. But how can we find it in the reverse way... say a listl=[1,2,3,4] l[0]=1.but how can I find its address with its value 1 ?? From mail at timgolden.me.uk Thu Dec 8 16:33:27 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 08 Dec 2011 15:33:27 +0000 Subject: [Tutor] how to find index of list with its value In-Reply-To: References: Message-ID: <4EE0D8C7.1020908@timgolden.me.uk> On 08/12/2011 15:28, surya k wrote: > > Well, we all know to know the value when we have the index of a list. > But how can we find it in the reverse way... say a listl=[1,2,3,4] > l[0]=1.but how can I find its address with its value 1 ?? help ([]) ... index(...) L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. TJG From joel.goldstick at gmail.com Thu Dec 8 16:33:43 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 8 Dec 2011 10:33:43 -0500 Subject: [Tutor] how to find index of list with its value In-Reply-To: References: Message-ID: On Thu, Dec 8, 2011 at 10:28 AM, surya k wrote: > > Well, we all know to know the value when we have the index of a list. But > how can we find it in the reverse way... > say a listl=[1,2,3,4] > l[0]=1.but how can I find its address with its value 1 ?? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > l.index(1) This will find the index of the first element with the value of 1 -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Thu Dec 8 16:36:04 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Thu, 8 Dec 2011 15:36:04 +0000 Subject: [Tutor] how to find index of list with its value In-Reply-To: References: Message-ID: <1605182952-1323358563-cardhu_decombobulator_blackberry.rim.net-1736745288-@b11.c12.bise7.blackberry> >>>mylist = [1,2,3,4,1] >>>mylist.index(1) 0 But note that this only shows the index for the first occurrence of the item. Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: surya k Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Thu, 8 Dec 2011 20:58:37 To: Python Tutor Subject: [Tutor] how to find index of list with its value Well, we all know to know the value when we have the index of a list. But how can we find it in the reverse way... say a listl=[1,2,3,4] l[0]=1.but how can I find its address with its value 1 ?? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From lie.1296 at gmail.com Thu Dec 8 16:40:18 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 09 Dec 2011 02:40:18 +1100 Subject: [Tutor] print method name In-Reply-To: References: Message-ID: On 12/09/2011 01:49 AM, rail shafigulin wrote: > i created a class and in some instances when i use it call some of its > methods i need to print a method name. the online search did produce > some results but none of them seem to work for me. for example one of > them said just to use __name__ or func_name but it didn't work for me. > i'm using python 3.1.1 > I'm guessing that you're doing something like def foo(): ... print foo().__name__ foo() would call the foo() function, so you'd be asking the .__name__ of the object returned by foo not the __name__ of foo. Instead you'd need to use the the function object itself, IOW don't call foo just do: print foo.__name__ This should work for both python 2 and python 3, and for both class methods or regular functions. From rail.shafigulin at gmail.com Thu Dec 8 16:56:10 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Thu, 8 Dec 2011 10:56:10 -0500 Subject: [Tutor] print method name In-Reply-To: References: Message-ID: On Thu, Dec 8, 2011 at 10:17 AM, Joel Goldstick wrote: > > > On Thu, Dec 8, 2011 at 9:49 AM, rail shafigulin > wrote: > >> i created a class and in some instances when i use it call some of its >> methods i need to print a method name. the online search did produce some >> results but none of them seem to work for me. for example one of them said >> just to use __name__ or func_name but it didn't work for me. i'm using >> python 3.1.1 >> >> any help is appreciated. >> >> It would be better if you send us the code you tried. I'm not sure what > you are looking to do. When you invoke the method, do you want it to print > its own name? > > > class A(object): > ... def first(self): > ... pass > ... > >>> a = A() > >>> a.first.__name__ > 'first' > > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Joel Goldstick > > folks, never mind. i'm not sure what went wrong when i ran my code and got an error. i ran it again and it is working fine. my sincere apologies. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rail.shafigulin at gmail.com Thu Dec 8 17:06:41 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Thu, 8 Dec 2011 11:06:41 -0500 Subject: [Tutor] print method name In-Reply-To: References: Message-ID: On Thu, Dec 8, 2011 at 10:40 AM, Lie Ryan wrote: > On 12/09/2011 01:49 AM, rail shafigulin wrote: > >> i created a class and in some instances when i use it call some of its >> methods i need to print a method name. the online search did produce >> some results but none of them seem to work for me. for example one of >> them said just to use __name__ or func_name but it didn't work for me. >> i'm using python 3.1.1 >> >> > I'm guessing that you're doing something like > > def foo(): > ... > > print foo().__name__ > > foo() would call the foo() function, so you'd be asking the .__name__ of > the object returned by foo not the __name__ of foo. Instead you'd need to > use the the function object itself, IOW don't call foo just do: > > print foo.__name__ > > > This should work for both python 2 and python 3, and for both class > methods or regular functions. > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > as a matter of apology i found another way of getting a method name without actually knowing the name of the method: import inspect class MyClass(object): def __init__(self): pass def mymethod(self): print(inspect.getframeinfo(inspect.currentframe()).function) def main(): a = MyClass() a.mymethod() if __name__ == '__main__': main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Dec 8 19:53:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Dec 2011 18:53:51 +0000 Subject: [Tutor] how to calculate program compile time? In-Reply-To: References: Message-ID: On 08/12/11 10:59, surya k wrote: > I'm doing puzzles where we need to write code that works as fast a possible > > So, how can I check the compile time of my program ?... Why would that be helpful? The code is only compiled the first time you use it so any second run will use the compiled code for imported modules. Put your program in a module and then write a driver file that imports the main program... If you want to improve performance check the timings with the Python profiler. Tune the bits that need tuning. If thats still not enough look at rewriting the critical parts in Cython. Or if that fails use C. But that should be a last resort. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Thu Dec 8 19:57:26 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 8 Dec 2011 12:57:26 -0600 Subject: [Tutor] how to use int and split() simultaneously In-Reply-To: References: Message-ID: On Thu, Dec 8, 2011 at 7:43 AM, Dario Lopez-K?sten wrote: > > > In that case a for loop with a try-except would better: > > strNum = raw_input("enter numbers, separated by space: ").split() > num_list = [] > > for token in strNum: > try: > num_list.append(int(token)) > except ValueError: > # Do nothing, fetch the next token > continue > > print repr(num_list) > > Strictly speaking the "continue" in the except clause is not necessary in > this simple example. > Though you do have to have *something* or you'll get a syntax error because you can't have an empty block. The keyword `pass` works well in cases like this. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Dec 8 20:05:30 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Dec 2011 19:05:30 +0000 Subject: [Tutor] print method name In-Reply-To: References: Message-ID: On 08/12/11 14:49, rail shafigulin wrote: > i created a class and in some instances when i use it call some of its > methods i need to print a method name. I'm curious why you need this? In most cases if you call a method you know its name... myObj = MyClass() myObj.spam() print "Just called MyClass.spam()" This would only be useful if you were creating references to methods dynamically or using callbacks from asynchronous messages or something? Just wondering what you are doing that requires this? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Dec 8 20:10:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 08 Dec 2011 19:10:57 +0000 Subject: [Tutor] Dictionary to variable copy In-Reply-To: References: Message-ID: On 08/12/11 09:03, sunil tech wrote: > /Can i copy the content if a dictionary in to another variable, with out > any link between the dictionary & the variable? > > if so, please teach. Yes, but they will both refer to the same object. But the two references will be entirely independant: D = {1:2,3:4} d = D[1] # both d and D[1] reference 2 D[1] = 42 # d still refers to 2 del(D) # d still refers to 2 Is that what you mean? Or do you wantbto make a clone of the value so that you can change it without changing the original? In that case you can use several techniques depending on object type. Generically use copy or deepcopy. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Thu Dec 8 20:07:36 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 8 Dec 2011 19:07:36 +0000 Subject: [Tutor] how to link GUI app to the code In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47406DC76@SCACMX008.exchad.jpmchase.net> >self.Bind(wx.EVT_BUTTON, self.OnSubmit, self.button_submit) How do you decide when it is appropriate to bind to a panel/frame and when to bind to the widget itself? I understand that certain events do not propagate up the widget stack, but what about for events that do? Is there a guideline of which is appropriate when? Ramit P.S. Yes, I should probably ask the wxPython mailing list...but I don't care enough (yet) to subscribe to a new list. :) Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Thu Dec 8 20:51:01 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 8 Dec 2011 19:51:01 +0000 (GMT) Subject: [Tutor] how to link GUI app to the code In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47406DC76@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47406DC76@SCACMX008.exchad.jpmchase.net> Message-ID: <1323373861.92837.YahooMailNeo@web86701.mail.ird.yahoo.com> The general rule with GUIs is to bind at the lowest practical level, usually the widget itself. The exception is usually for things like global accelerators. For example launching a? help browser might be at window level. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ >________________________________ > From: "Prasad, Ramit" >To: Alan Gauld ; "tutor at python.org" >Sent: Thursday, 8 December 2011, 19:07 >Subject: RE: [Tutor] how to link GUI app to the code > >>self.Bind(wx.EVT_BUTTON, self.OnSubmit, self.button_submit) > >How do you decide when it is appropriate to bind to a panel/frame and when to bind to the widget itself? I understand that certain events do not propagate up the widget stack, but what about for events that do? Is there a guideline of which is appropriate when? > >Ramit > >P.S. Yes, I should probably ask the wxPython mailing list...but I don't care enough (yet) to subscribe to a new list. :) > > >Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology >712 Main Street | Houston, TX 77002 >work phone: 713 - 216 - 5423 > >-- > >This email is confidential and subject to important disclaimers and >conditions including on offers for the purchase or sale of >securities, accuracy and completeness of information, viruses, >confidentiality, legal privilege, and legal entity disclaimers, >available at http://www.jpmorgan.com/pages/disclosures/email. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From shantanoo at gmail.com Thu Dec 8 21:33:03 2011 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Fri, 9 Dec 2011 02:03:03 +0530 Subject: [Tutor] how to use int and split() simultaneously In-Reply-To: References: Message-ID: On 08-Dec-2011, at 7:13 PM, Dario Lopez-K?sten wrote: > oh, yes, no top posting. See below. > > On Thu, Dec 8, 2011 at 1:33 PM, surya k wrote: > > This is something I am trying to do.. > Say, we are entering a string "1 2 3 4 5".so, I want to assign the numbers directly as numbers. how can I do it? > I could put that numbers as string but not as number.. > strNum = raw_input('enter:').split() > I can convert the list into numbers by doing this... > for i in range(len(strNum)): strNum[i] = int(strNum[i]). > but I feel, its a long process. How can I do it in the shortest possible way?? > > Using a list comprehension is one example of a compact way of doing it: > > strNum = raw_input("enter numbers, separated by space: ").split() > strNum = [int(x) for x in strNum] > > You would have to assume that the entire string consists of tokens that can be type cast into integers. If not you get an error: > > >>> strNum = raw_input("enter numbers, separated by space: ").split() > enter numbers, separated by space: 1 2 3 4 5 66 asd > >>> strNum = [int(x) for x in strNum] > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): asd > > In that case a for loop with a try-except would better: > > strNum = raw_input("enter numbers, separated by space: ").split() > num_list = [] > > for token in strNum: > try: > num_list.append(int(token)) > except ValueError: > # Do nothing, fetch the next token > continue > > print repr(num_list) > > This code gives this result: > > enter numbers, separated by space: 1 2 3 4 5 66 > [1, 2, 3, 4, 5, 66] > > enter numbers, separated by space: 1 2 3 4 5 66 asd 77 > [1, 2, 3, 4, 5, 66, 77] > > Strictly speaking the "continue" in the except clause is not necessary in this simple example. > > Hope this helps! > > /dario > Using re module: === import re strNum = raw_input("enter numbers, separated by space: ") if re.search('[^\d ]', strNum): print('Invalid input') else: data = [int(x) for x in strNum.split()] print(data) === -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Dec 8 22:13:32 2011 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Dec 2011 16:13:32 -0500 Subject: [Tutor] list.index() question Message-ID: <4EE1287C.3090004@cfl.rr.com> Hi, Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want to get the index of 'c'. A one dimensional list is extremely easy; val = list.index(value). But how do I get it for a list similar to l1. I have tried ind = l1[0].index('c') and that tells me 'c' is not in list. Either my syntax is way off or I am missing the viable solution. I am reasonably certain I could iterate over l1 until I find either the value or do not find the value. If that is the only way to go, could someone share an example of workable code to do that task reasonably well. Thank you for your assistance. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Dec 8 22:22:42 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 8 Dec 2011 16:22:42 -0500 Subject: [Tutor] list.index() question In-Reply-To: <4EE1287C.3090004@cfl.rr.com> References: <4EE1287C.3090004@cfl.rr.com> Message-ID: On 12/8/11, Robert Berman wrote: > Hi, > > Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want > to get the index of 'c'. A one dimensional list is extremely easy; val = > list.index(value). But how do I get it for a list similar to l1. I have > tried ind = l1[0].index('c') and that tells me 'c' is not in list. That's right, 'c' is in l1[2], not l1[0]. Are you trying to search all lists inside l1 for 'c' instead of a specific list inside l1? > Either my syntax is way off or I am missing the viable solution. > > I am reasonably certain I could iterate over l1 until I find either the > value or do not find the value. If that is the only way to go, could > someone share an example of workable code to do that task reasonably well. Maybe: def contains(lst, val): for i in lst: if isinstance(i, list): return contains(i, val) elif val==i: return True return False > > Thank you for your assistance. > > Robert > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From bodsda at googlemail.com Thu Dec 8 22:27:03 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Thu, 8 Dec 2011 21:27:03 +0000 Subject: [Tutor] list.index() question In-Reply-To: <4EE1287C.3090004@cfl.rr.com> References: <4EE1287C.3090004@cfl.rr.com> Message-ID: <1633921213-1323379623-cardhu_decombobulator_blackberry.rim.net-193158558-@b11.c12.bise7.blackberry> That won't work because l1[0] is ['a', 1] What happens if you don't change the code? l1.index('c') Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Robert Berman Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Thu, 08 Dec 2011 16:13:32 To: tutor Subject: [Tutor] list.index() question _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From bermanrl at cfl.rr.com Thu Dec 8 22:33:53 2011 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Dec 2011 16:33:53 -0500 Subject: [Tutor] list.index() question In-Reply-To: <1633921213-1323379623-cardhu_decombobulator_blackberry.rim.net-193158558-@b11.c12.bise7.blackberry> References: <4EE1287C.3090004@cfl.rr.com> <1633921213-1323379623-cardhu_decombobulator_blackberry.rim.net-193158558-@b11.c12.bise7.blackberry> Message-ID: <4EE12D41.3010701@cfl.rr.com> On 12/08/2011 04:27 PM, bodsda at googlemail.com wrote: > That won't work because l1[0] is ['a', 1] > > What happens if you don't change the code? > > l1.index('c') > > Bodsda > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: Robert Berman > Sender: tutor-bounces+bodsda=googlemail.com at python.org > Date: Thu, 08 Dec 2011 16:13:32 > To: tutorIn [1]: l1=[['a',1],['b',2],['c',3]] > > In [2]: l1 > Out[2]: [['a', 1], ['b', 2], ['c', 3]] > > In [3]: l1.index('c') > --------------------------------------------------------------------------- > ValueError Traceback (most recent call last) > > /home/bermanrl/ in() > > ValueError: 'c' is not in list > > > Subject: [Tutor] list.index() question > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Bodsa et al, What happens is as follows: In [1]: l1=[['a',1],['b',2],['c',3]] In [2]: l1 Out[2]: [['a', 1], ['b', 2], ['c', 3]] In [3]: l1.index('c') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/bermanrl/ in () ValueError: 'c' is not in list I really appreciate the help I am getting. Eventually I am certain there is a relatively easy solution I simply do not have the expertise to see it. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Dec 8 23:03:02 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Dec 2011 09:03:02 +1100 Subject: [Tutor] list.index() question In-Reply-To: <4EE1287C.3090004@cfl.rr.com> References: <4EE1287C.3090004@cfl.rr.com> Message-ID: <4EE13416.9090503@pearwood.info> Robert Berman wrote: > Hi, > > Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want > to get the index of 'c'. You will need to explain what you mean by "the index of 'c'". Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]? Or do you mean 2, because 'c' is in the sub-list at position 2? What happens if there is a sub-list ['d', 'c']? Should that also count? What about sub-sub-lists, should they be checked too? Here is a version which checks each sub-list in turn, and returns the index of any 'c' it finds of the first such sub-list. def inner_find(list_of_lists): for sublist in list_of_lists: try: return sublist.index('c') except ValueError: pass # go to the next one # If not found at all: raise ValueError('not found') Here's a version which finds the index of the first sub-list that begins with 'c' as the zeroth element: def match_sublist(list_of_lists): for i, sublist in enumerate(list_of_lists): if sublist and sublist[0] == 'c': return i raise ValueError('not found') Other variations on these two techniques are left for you to experiment with. -- Steven From steve at pearwood.info Thu Dec 8 23:06:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 09 Dec 2011 09:06:56 +1100 Subject: [Tutor] how to use int and split() simultaneously In-Reply-To: References: Message-ID: <4EE13500.9090303@pearwood.info> ????? wrote: > Using re module: > > === > import re > strNum = raw_input("enter numbers, separated by space: ") > if re.search('[^\d ]', strNum): > print('Invalid input') > else: > data = [int(x) for x in strNum.split()] > print(data) This is not Perl, where everything is a nail that needs to be hammered with a regex. Especially not a regex which is wrong: your regex is too strict. It disallows using tabs as separators, while str.split() will happily consume tabs for you. In general, in Python, the way to check of an error condition is to try it, and if it fails, catch the exception. This doesn't always apply, but it does apply most of the time. data = [int(x) for x in strNum.split()] will print a perfectly good error message if it hits invalid input. There's no need to check the input first with a regex. If you want to recover from errors, it is easy by taking the conversion out of a list comprehension and into an explicit for loop: data = [] for s in strNum.split(): try: data.append(int(s)) except ValueError: data.append(42) # Or some other default value. If you don't care about recovering from individual errors, but only care whether the entire conversion succeeds or fails: try: data = [int(s) for s in strNum.split()] except ValueError: data = [] -- Steven From joel.goldstick at gmail.com Thu Dec 8 23:11:59 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 8 Dec 2011 17:11:59 -0500 Subject: [Tutor] list.index() question In-Reply-To: <4EE13416.9090503@pearwood.info> References: <4EE1287C.3090004@cfl.rr.com> <4EE13416.9090503@pearwood.info> Message-ID: On Thu, Dec 8, 2011 at 5:03 PM, Steven D'Aprano wrote: > Robert Berman wrote: > >> Hi, >> >> Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I want >> to get the index of 'c'. >> > > You will need to explain what you mean by "the index of 'c'". > > Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]? > > Or do you mean 2, because 'c' is in the sub-list at position 2? > > What happens if there is a sub-list ['d', 'c']? Should that also count? > What about sub-sub-lists, should they be checked too? > > Here is a version which checks each sub-list in turn, and returns the > index of any 'c' it finds of the first such sub-list. > > def inner_find(list_of_lists): > for sublist in list_of_lists: > try: > return sublist.index('c') > except ValueError: > pass # go to the next one > # If not found at all: > raise ValueError('not found') > > > Here's a version which finds the index of the first sub-list that begins > with 'c' as the zeroth element: > > def match_sublist(list_of_lists): > for i, sublist in enumerate(list_of_lists): > if sublist and sublist[0] == 'c': > return i > raise ValueError('not found') > > > > > Other variations on these two techniques are left for you to experiment > with. > > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > l1=[['a',1],['b',2],['c',3]] >>> r = [s for s in l1 if s[0] == 'c'] >>> r [['c', 3]] > This doesn't get you all the way, but maybe its a start. If you had more than one sublist like ['c', 8] is would include that too -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Dec 8 23:23:12 2011 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Dec 2011 17:23:12 -0500 Subject: [Tutor] list.index() question In-Reply-To: <4EE13416.9090503@pearwood.info> References: <4EE1287C.3090004@cfl.rr.com> <4EE13416.9090503@pearwood.info> Message-ID: <4EE138D0.4020103@cfl.rr.com> On 12/08/2011 05:03 PM, Steven D'Aprano wrote: > Robert Berman wrote: >> Hi, >> >> Assuming a list similar to this: l1=[['a',1],['b',2],['c',3]] and I >> want to get the index of 'c'. > > You will need to explain what you mean by "the index of 'c'". > > Do you mean 0, because 'c' is in position 0 of the sub-list ['c', 3]? > > Or do you mean 2, because 'c' is in the sub-list at position 2? > > What happens if there is a sub-list ['d', 'c']? Should that also > count? What about sub-sub-lists, should they be checked too? > > Here is a version which checks each sub-list in turn, and returns the > index of any 'c' it finds of the first such sub-list. > > def inner_find(list_of_lists): > for sublist in list_of_lists: > try: > return sublist.index('c') > except ValueError: > pass # go to the next one > # If not found at all: > raise ValueError('not found') > > > Here's a version which finds the index of the first sub-list that > begins with 'c' as the zeroth element: > > def match_sublist(list_of_lists): > for i, sublist in enumerate(list_of_lists): > if sublist and sublist[0] == 'c': > return i > raise ValueError('not found') > > > > > Other variations on these two techniques are left for you to > experiment with. > > > Thank you Steven and Joel. You have given me information to experiment with which is most appreciated. Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Dec 8 23:39:59 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 8 Dec 2011 22:39:59 +0000 Subject: [Tutor] Super In tkinter class inheritance In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47406EEFE@SCACMX008.exchad.jpmchase.net> >> class ChooseDestinationWindow(Frame): def __init__(self,master): >>super(ChooseDestinationWindow,self).__init_ _(master) >What exactly does this super method since I have seen it numerous >times before and as far as I can see it is not anything the user >created himself in the class? This has to do a lot with inheritance in object-oriented programming. If you are not aware of this, you might want to read some basics on that. The gist of the reason to call super is that the TKinter (or whatever base class) does some work in the background to create a "Frame" type, so if you are inheriting from the Frame class, you still (normally) want the Frame class to behave normally with very specific deviations. For instance, you may want to setup the Frame but (like an Office-type application) have it ask the user to save when the app tries to close. You use super in a function to call the behavior of the base class so that you do not need to duplicate the code. It is a fairly language-agnostic OOP idea. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From emekamicro at gmail.com Fri Dec 9 13:47:15 2011 From: emekamicro at gmail.com (Emeka) Date: Fri, 9 Dec 2011 13:47:15 +0100 Subject: [Tutor] Help with update_wrapper Message-ID: Hello All, Could someone explain " functools.update_wrapper" with simple examples? Regards, Janus -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Fri Dec 9 15:37:06 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Fri, 9 Dec 2011 09:37:06 -0500 Subject: [Tutor] What style do you call Python programming? Message-ID: I'm looking for a term to call the kind of Python programming that Python is, in other words, programming with no branching, no GOTOs, no statement labels and no line numbers. I'm tempted to call it Structured Progamming, but we had that in COBOL, and this is not like COBOL. It seems to be with Python the whole thing is creating functions and then using loops, with an occasional BREAK or CONTINUE, to control program flow. I know it's Structured, but it's not like COBOL structured, if you know what I mean. I hope this is clear enough. -- Frank L. "Cranky Frankie" Palmeri From tvssarma.omega9 at gmail.com Fri Dec 9 15:54:46 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Fri, 9 Dec 2011 20:24:46 +0530 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: On 9 December 2011 20:07, Cranky Frankie wrote: > I'm looking for a term to call the kind of Python programming that > Python is, in other words, programming with no branching, no GOTOs, no > statement labels and no line numbers. I'm tempted to call it > Structured Progamming, but we had that in COBOL, and this is not like > COBOL. > > The keyword you are looking for is 'programming paradigm' and python implements several and not just any specific one such as structured. You could call it a multi-paradigm programming language. http://en.wikipedia.org/wiki/Programming_paradigm > It seems to be with Python the whole thing is creating functions and > then using loops, with an occasional BREAK or CONTINUE, to control > program flow. I know it's Structured, but it's not like COBOL > structured, if you know what I mean. > > The point is its a scripted language. Most of what you want to do should be about a line. Python is derived from the idea of scripted languages wherein constructs like loops and functions were added for more control. The main idea of programming in python is not essentially writing a functions but rather like shell scripting, one line of syntax at a time. Having functions, for example, gives you greater control or rather an abstraction of control for clarity of thought. I hope this is clear enough. > > -- > Frank L. "Cranky Frankie" Palmeri > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From cl2dlope at gmail.com Fri Dec 9 16:20:44 2011 From: cl2dlope at gmail.com (=?ISO-8859-1?Q?Dario_Lopez=2DK=E4sten?=) Date: Fri, 9 Dec 2011 16:20:44 +0100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: On Fri, Dec 9, 2011 at 3:54 PM, Sarma Tangirala wrote: > > On 9 December 2011 20:07, Cranky Frankie wrote: > >> I'm looking for a term to call the kind of Python programming that >> >> <...snip...> > >> > The keyword you are looking for is 'programming paradigm' and python > implements several and not just any specific one such as structured. You > could call it a multi-paradigm programming language. > > http://en.wikipedia.org/wiki/Programming_paradigm > > <...snip..> > The point is its a scripted language. Most of what you want to do should > be about a line. Python is derived from the idea of scripted languages > wherein constructs like loops and functions were added for more control. > The main idea of programming in python is not essentially writing a > functions but rather like shell scripting, one line of syntax at a time. > Having functions, for example, gives you greater control or rather an > abstraction of control for clarity of thought. > > I actually don't agree at all with your last statements. Since you quote Wikipedia, allow me to do the same: http://en.wikipedia.org/wiki/Python_(programming_language) * * > *"Python supports multiple programming paradigms, primarily but not > limited to object-oriented, imperative and, to a lesser extent, functional > programming styles. It features a fully dynamic type system and > automatic memory management, similar to that of Scheme, Ruby, Perl, > and Tcl. Like other dynamic languages, Python is often used as a scripting > language, but is also used in a wide range of non-scripting contexts. Using > third-party tools, Python code can be packaged into standalone executable > programs. Python interpreters are available for many operating systems."* Keywords, IMHO are: imperative, object oriented, interpreted dynamic programming language. Scripting comes as a bonus of the fact that it is interpreted. My 0.02? /dario -------------- next part -------------- An HTML attachment was scrubbed... URL: From tvssarma.omega9 at gmail.com Fri Dec 9 16:36:50 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Fri, 9 Dec 2011 21:06:50 +0530 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: On 9 December 2011 20:50, Dario Lopez-K?sten wrote: > On Fri, Dec 9, 2011 at 3:54 PM, Sarma Tangirala > wrote: > >> >> On 9 December 2011 20:07, Cranky Frankie wrote: >> >>> I'm looking for a term to call the kind of Python programming that >>> >>> <...snip...> > >> >>> >> The keyword you are looking for is 'programming paradigm' and python >> implements several and not just any specific one such as structured. You >> could call it a multi-paradigm programming language. >> >> http://en.wikipedia.org/wiki/Programming_paradigm >> >> <...snip..> > >> The point is its a scripted language. Most of what you want to do should >> be about a line. Python is derived from the idea of scripted languages >> wherein constructs like loops and functions were added for more control. >> The main idea of programming in python is not essentially writing a >> functions but rather like shell scripting, one line of syntax at a time. >> Having functions, for example, gives you greater control or rather an >> abstraction of control for clarity of thought. >> >> > I actually don't agree at all with your last statements. Since you quote > Wikipedia, allow me to do the same: > > http://en.wikipedia.org/wiki/Python_(programming_language) > * > * > >> *"Python supports multiple programming paradigms, primarily but not >> limited to object-oriented, imperative and, to a lesser extent, functional >> programming styles. It features a fully dynamic type system and >> automatic memory management, similar to that of Scheme, Ruby, Perl, >> and Tcl. Like other dynamic languages, Python is often used as a scripting >> language, but is also used in a wide range of non-scripting contexts. Using >> third-party tools, Python code can be packaged into standalone executable >> programs. Python interpreters are available for many operating systems."* > > > Keywords, IMHO are: imperative, object oriented, interpreted dynamic > programming language. Scripting comes as a bonus of the fact that it is > interpreted. > > My 0.02? > Where does it say that python was originally not designed to be scripted? If thats the case then I agree my comment was completely incorrect. I read somewhere that it was designed so. I don't get exactly where you disagree with me as I wrote that part about scripting for the second paragraph. With respect to the OP's question how does being imperative, OO or dynamic determine "I'm looking for a term to call the kind of Python programming that Python is, in other words, programming with no branching, no GOTOs, no statement labels and no line numbers."? > > /dario > > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Dec 9 16:55:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 10 Dec 2011 02:55:48 +1100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: <4EE22F84.8040101@pearwood.info> Cranky Frankie wrote: > I'm looking for a term to call the kind of Python programming that > Python is, in other words, programming with no branching, no GOTOs, no > statement labels and no line numbers. I'm tempted to call it > Structured Progamming, but we had that in COBOL, and this is not like > COBOL. Python is a mixed paradigm language with a syntax which has been described as "executable pseudo-code". http://en.wikipedia.org/wiki/Programming_paradigm As Python has no line numbers or statement labels, and forbids arbitrary GOTOs, it is a structured language, like nearly all languages today. The main unstructured language old-timers may be familiar with is early BASIC; younger programmers may never have even seen an unstructured language. Python allows the user to write code in a mix of procedural style (like Fortran, Pascal or C), functional style (like Haskell) style, and object-oriented style (like C++ or Java). Unlike some other languages, Python encourages you to mix styles within a single module, and use whatever works best for the specific fine-grained task. -- Steven From steve at pearwood.info Fri Dec 9 17:14:31 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 10 Dec 2011 03:14:31 +1100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: <4EE233E7.5040902@pearwood.info> Sarma Tangirala wrote: > The point is its a scripted language. Define "scripted language". (Scripting language?) > Most of what you want to do should be > about a line. Python is derived from the idea of scripted languages wherein > constructs like loops and functions were added for more control. I don't understand what you mean by "should be about a line". If your idea is that Python is an interpreter that reads the source code line by line, interpreting then executing each one in turn, you couldn't be more wrong. Python uses a compiler that generates byte-code, then executes it in a virtual machine, just like (for example) Java. The CPython compiler and virtual machine is the reference implementation; the PyPy implementation is a JIT compiler which can approach the speed of optimized C code, and in a very few cases, actually beat it. If Python is a "scripting language", it is a scripting language which can perform video processing on the fly: http://morepypy.blogspot.com/2011/07/realtime-image-processing-in-python.html > The main > idea of programming in python is not essentially writing a functions but > rather like shell scripting, one line of syntax at a time. I can't imagine why you think that is the "main idea" for programming in Python. Even in true scripting languages like bash, the use of functions is strongly recommended. For anything but the simplest script, you are better off encapsulating code into functions or classes. Of course Python can be used to write simple scripts without functions. And complex scripts with functions. And "glue" code to interface between libraries written in C or Fortran. And major applications with tens or hundreds of thousands of lines of code, dozens of modules, hundreds of classes and functions. And everything in between. -- Steven From tvssarma.omega9 at gmail.com Fri Dec 9 17:52:25 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Fri, 9 Dec 2011 22:22:25 +0530 Subject: [Tutor] What style do you call Python programming? In-Reply-To: <4EE233E7.5040902@pearwood.info> References: <4EE233E7.5040902@pearwood.info> Message-ID: On 9 December 2011 21:44, Steven D'Aprano wrote: > Sarma Tangirala wrote: > > The point is its a scripted language. >> > > Define "scripted language". (Scripting language?) > > > I meant scripting language. :) > > Most of what you want to do should be >> about a line. Python is derived from the idea of scripted languages >> wherein >> constructs like loops and functions were added for more control. >> > > I don't understand what you mean by "should be about a line". If your idea > is that Python is an interpreter that reads the source code line by line, > interpreting then executing each one in turn, you couldn't be more wrong. > Python uses a compiler that generates byte-code, then executes it in a > virtual machine, just like (for example) Java. The CPython compiler and > virtual machine is the reference implementation; the PyPy implementation is > a JIT compiler which can approach the speed of optimized C code, and in a > very few cases, actually beat it. > > Well, what I meant was the way you write things like list comprehension. I agree, that comment gave a completely incorrect picture. Sorry about that. > If Python is a "scripting language", it is a scripting language which can > perform video processing on the fly: > > http://morepypy.blogspot.com/**2011/07/realtime-image-** > processing-in-python.html > > > Scripting language not in the true sense. My bad. > > The main >> idea of programming in python is not essentially writing a functions but >> rather like shell scripting, one line of syntax at a time. >> > > I can't imagine why you think that is the "main idea" for programming in > Python. Even in true scripting languages like bash, the use of functions is > strongly recommended. For anything but the simplest script, you are better > off encapsulating code into functions or classes. > > Of course Python can be used to write simple scripts without functions. > And complex scripts with functions. And "glue" code to interface between > libraries written in C or Fortran. And major applications with tens or > hundreds of thousands of lines of code, dozens of modules, hundreds of > classes and functions. And everything in between. > > > I disagree here. Writing bigger pieces of code warrant the use of functions not the other way around. What I was trying to say was that in C you'd have to use a main function and in Java a public class in your code. In python it is not a business of using functions as the OP had mentioned. As to the "main idea", I think I could have worded that a bit better. I'm really sorry if what I posed before was annoying crap. :) > > -- > Steven > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Sarma Tangirala, Class of 2012, Department of Information Science and Technology, College of Engineering Guindy - Anna University -------------- next part -------------- An HTML attachment was scrubbed... URL: From james.homme at highmark.com Fri Dec 9 19:41:06 2011 From: james.homme at highmark.com (Homme, James) Date: Fri, 9 Dec 2011 18:41:06 +0000 Subject: [Tutor] Python Windows Vista Installation Question Message-ID: Hi, Can Python easily be installed on a Windows Vista computer without needing administrative rights to that machine? Thanks. Jim Jim Homme, Usability Services, Phone: 412-544-1810. ________________________________ This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. -------------- next part -------------- An HTML attachment was scrubbed... URL: From snoylr at cheqnet.net Fri Dec 9 20:03:55 2011 From: snoylr at cheqnet.net (Richard Lyons) Date: Fri, 09 Dec 2011 13:03:55 -0600 Subject: [Tutor] Python and Tkinter (total newbie) Message-ID: <4EE25B9B.1080204@cheqnet.net> I have tried to enter the first sample program from p. 19 in Grayson: Python and Tkinter Programming. When I run the program I get an error as follows: Traceback (most recent call last): File "/home/dick/Desktop/calc1.py", line 50, in if _name_ == '_main_': NameError: name '_name_' is not defined The error makes sense because nowhere in the code is _main_ defined. How do I fix this? from Tkinter import * def frame(root, side): w = Frame(root) w.pack(side=side, expand=Yes, fill=BOTH) return w def button(root, side, text, command=NONE): w = Button(root, text+text, command+command) w.pack(side=side, expand=YES, fill=BOTH) return w class Calculator(Frame) : def _init_(self) : Frame._init_(self) self.pack(expand=YES, fill=BOTH) self.master.title('Simple Calculator') self.master.iconname("calc1") diplay = StringVar() Entry(self, relief=SUNKEN, textvariable=display).pack( side=TOP, expand=YES, fill=BOTH) for key in ("123", "456", "789", "-0."): keyF = frame(self, TOP) for char in key: button(keyF, LEFT, char, lambda w=display,s='%s'%char: w.set(w.get()+s)) opsF = frame(self, TOP) for char in "+-*/=": if char == '=': btn = button(opsF, LEFT, char) btn.bind('', lambda e, s=self, w=display: s.calc(w), '+') else: btn = button(opsF, LEFT, char, lambda w=display, c=char: w.set(w.get()+' '+c+' ')) clearF = frame(self, BOTTOM) button(clearF, LEFT, 'Clr', lambda w=display: w.set(' ')) def calc(self, display): try: display,set('eval(display.get())') except ValueError: display.set("ERROR") if _name_ == '_main_': Calculator().mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Dec 9 20:24:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Dec 2011 19:24:00 +0000 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: On 09/12/11 15:36, Sarma Tangirala wrote: > Where does it say that python was originally not designed to be > scripted? If thats the case then I agree my comment was completely > incorrect. I read somewhere that it was designed so. It was designed as a "scripting language" but not for the purpose of scripting in the OS sense, it was an attempt to build a teaching language which could also be used for real world tasks. Its predecessor was ABC. The evolution of Python from its ABC roots is well documented by Guido. He designed it as a "scripting language" but from the very beginning intended it to support features like functions, modules and OO. These are not add-ons as they were in, for example, Perl and Tcl. Here is what the official FAQ entry says: ========================= Here?s a very brief summary of what started it all, written by Guido van Rossum: I had extensive experience with implementing an interpreted language in the ABC group at CWI, and from working with this group I had learned a lot about language design. This is the origin of many Python features, including the use of indentation for statement grouping and the inclusion of very-high-level data types (although the details are all different in Python). I had a number of gripes about the ABC language, but also liked many of its features. It was impossible to extend the ABC language (or its implementation) to remedy my complaints ? in fact its lack of extensibility was one of its biggest problems. I had some experience with using Modula-2+ and talked with the designers of Modula-3 and read the Modula-3 report. Modula-3 is the origin of the syntax and semantics used for exceptions, and some other Python features. I was working in the Amoeba distributed operating system group at CWI. We needed a better way to do system administration than by writing either C programs or Bourne shell scripts, since Amoeba had its own system call interface which wasn?t easily accessible from the Bourne shell. My experience with error handling in Amoeba made me acutely aware of the importance of exceptions as a programming language feature. It occurred to me that a scripting language with a syntax like ABC but with access to the Amoeba system calls would fill the need. I realized that it would be foolish to write an Amoeba-specific language, so I decided that I needed a language that was generally extensible. During the 1989 Christmas holidays, I had a lot of time on my hand, so I decided to give it a try. During the next year, while still mostly working on it in my own time, Python was used in the Amoeba project with increasing success, and the feedback from colleagues made me add many early improvements. In February 1991, after just over a year of development, I decided to post to USENET. The rest is in the Misc/HISTORY file. ============================= Hopefully that clarifies rather than condfusing! :-) The HISTORY file gives more detail still. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Fri Dec 9 20:24:22 2011 From: d at davea.name (Dave Angel) Date: Fri, 09 Dec 2011 14:24:22 -0500 Subject: [Tutor] Python and Tkinter (total newbie) In-Reply-To: <4EE25B9B.1080204@cheqnet.net> References: <4EE25B9B.1080204@cheqnet.net> Message-ID: <4EE26066.5040805@davea.name> On 12/09/2011 02:03 PM, Richard Lyons wrote: > I have tried to enter the first sample program from p. 19 in Grayson: > Python and Tkinter Programming. When I run the program I get an error > as follows: > > Traceback (most recent call last): > File "/home/dick/Desktop/calc1.py", line 50, in > if _name_ == '_main_': > NameError: name '_name_' is not defined > > The error makes sense because nowhere in the code is _main_ defined. > How do I fix this? > > > from Tkinter import * > def frame(root, side): > w = Frame(root) > w.pack(side=side, expand=Yes, fill=BOTH) > return w > > def button(root, side, text, command=NONE): > w = Button(root, text+text, command+command) > w.pack(side=side, expand=YES, fill=BOTH) > return w > > class Calculator(Frame) : > def _init_(self) : > Frame._init_(self) > self.pack(expand=YES, fill=BOTH) > self.master.title('Simple Calculator') > self.master.iconname("calc1") > > diplay = StringVar() > Entry(self, relief=SUNKEN, > textvariable=display).pack( > side=TOP, expand=YES, > fill=BOTH) > > for key in ("123", "456", "789", "-0."): > keyF = frame(self, TOP) > for char in key: > button(keyF, LEFT, char, > lambda w=display,s='%s'%char: w.set(w.get()+s)) > > > opsF = frame(self, TOP) > for char in "+-*/=": > if char == '=': > btn = button(opsF, LEFT, char) > btn.bind('', > lambda e, s=self, w=display: s.calc(w), '+') > else: > btn = button(opsF, LEFT, char, > lambda w=display, c=char: w.set(w.get()+' '+c+' > ')) > > clearF = frame(self, BOTTOM) > button(clearF, LEFT, 'Clr', lambda w=display: w.set(' ')) > > def calc(self, display): > try: > display,set('eval(display.get())') > except ValueError: > display.set("ERROR") > > if _name_ == '_main_': > Calculator().mainloop() > The problem is simple: __name__ has two underscores before,and two underscrores after the letters. You typed only one. That name is predefined for you in every script and module. In a script it has the value "__main__" (again with two underscores each place), and in a module, it has the module name. -- DaveA From suryak at live.com Fri Dec 9 20:25:17 2011 From: suryak at live.com (surya k) Date: Sat, 10 Dec 2011 00:55:17 +0530 Subject: [Tutor] how to handle big numbers Message-ID: Finding factorial of 8 or 9 isn't big.?If I would like to find factorial of 32327, how can I ?? From alan.gauld at btinternet.com Fri Dec 9 20:34:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Dec 2011 19:34:49 +0000 Subject: [Tutor] Python and Tkinter (total newbie) In-Reply-To: <4EE25B9B.1080204@cheqnet.net> References: <4EE25B9B.1080204@cheqnet.net> Message-ID: On 09/12/11 19:03, Richard Lyons wrote: > I have tried to enter the first sample program from p. 19 in Grayson: > Python and Tkinter Programming. When I run the program I get an error > as follows: > > Traceback (most recent call last): > File "/home/dick/Desktop/calc1.py", line 50, in > if _name_ == '_main_': > NameError: name '_name_' is not defined > > The error makes sense because nowhere in the code is _main_ defined. Read the error again. It is actually _name_ that it is complaining about! However, neither _name_ or "_main_" (notoice the quotes!) are defined. The real problem is that you need a double underscore on each side. This is a special convention that is used in Python to indicate special "magic" being performed by Python behind the scenes. In this case the magic variable __name__ is assigned the name of the file if the file is used as a module but the name "__main__" if the file is run as a program. (In python there is no real difference between programs and module files. One file can do both jobs) You will come across several other magic names as you explore python, most notably __init__ when looking at classes. One thing to beware. Grayson's book is based on a very old version of Python so some things may have changed a little. If you hit unexplainable errors post them here and we can probably help you over them. Also Grayson's book takes no prisoners in its code. There is a lot of it and he assumes you know Python and GUI programming in general quite well. You may want to go through the standard Python tutorials before plunging too far into Tkinter! HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Dec 9 20:46:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Dec 2011 19:46:33 +0000 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: On 09/12/11 19:24, Alan Gauld wrote: > In February 1991, after just over a year of development, I decided to > post to USENET. The rest is in the Misc/HISTORY file. > > ============================= > > Hopefully that clarifies rather than condfusing! :-) > The HISTORY file gives more detail still. Hmm, I just went to check the HISTORY file and I can't find it. It used to come with the source tarball, but I haven't downloaded the source for years!... Where has the online source code repository gone? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Dec 9 20:52:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Dec 2011 19:52:54 +0000 Subject: [Tutor] how to handle big numbers In-Reply-To: References: Message-ID: On 09/12/11 19:25, surya k wrote: > > Finding factorial of 8 or 9 isn't big. If I would like to find factorial of 32327, how can I ?? Just type it in, but expect to wait a long time for the answer... Python integers are limited by the memory of your machine. factorial(30000) took about 7 seconds on my PC - much faster than I expected! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Fri Dec 9 20:53:07 2011 From: d at davea.name (Dave Angel) Date: Fri, 09 Dec 2011 14:53:07 -0500 Subject: [Tutor] how to handle big numbers In-Reply-To: References: Message-ID: <4EE26723.1020005@davea.name> On 12/09/2011 02:25 PM, surya k wrote: > Finding factorial of 8 or 9 isn't big. If I would like to find factorial of 32327, how can I ?? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > How close do you want your answer? The gamma function can be used to calculate it, but it won't be precise. I don't know how many digits are in 32327!, but it must be at least hundreds of thousands, and a float cannot represent that exactly. In fact it cannot represent a number that big, even approximately. It might be millions of digits, but I don't have the time right now to figure it out. If you use a long int (which int will promote to, automatically), you could do the calculation with a very simple program, providing you don't run out of either time or memory. if it were my problem, I'd do it in three steps. First write a program to calculate N! exactly. See how long it takes for 100, and how many digits are in the answer. Then try it again for 1000! Next, I'd look up the gamma function, and figure out how large the desired value will be. Finally, depending on what I got from those first two, I'd either run the first program with 32327, and wait a long time, or write a specialized math package to calculate the gamma function to whatever precision I thought Ineeded. -- DaveA From suryak at live.com Fri Dec 9 21:04:39 2011 From: suryak at live.com (surya k) Date: Sat, 10 Dec 2011 01:34:39 +0530 Subject: [Tutor] how to handle big numbers In-Reply-To: <4EE26723.1020005@davea.name> References: , <4EE26723.1020005@davea.name> Message-ID: ---------------------------------------- > Date: Fri, 9 Dec 2011 14:53:07 -0500 > From: d at davea.name > To: suryak at live.com > CC: tutor at python.org > Subject: Re: [Tutor] how to handle big numbers > > On 12/09/2011 02:25 PM, surya k wrote: > > Finding factorial of 8 or 9 isn't big. If I would like to find factorial of 32327, how can I ?? > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > How close do you want your answer? The gamma function can be used to > calculate it, but it won't be precise. I don't know how many digits > are in 32327!, but it must be at least hundreds of thousands, and a > float cannot represent that exactly. In fact it cannot represent a > number that big, even approximately. It might be millions of digits, > but I don't have the time right now to figure it out. > > If you use a long int (which int will promote to, automatically), you > could do the calculation with a very simple program, providing you don't > run out of either time or memory. > > if it were my problem, I'd do it in three steps. First write a program > to calculate N! exactly. See how long it takes for 100, and how many > digits are in the answer. Then try it again for 1000! > > Next, I'd look up the gamma function, and figure out how large the > desired value will be. > > Finally, depending on what I got from those first two, I'd either run > the first program with 32327, and wait a long time, or write a > specialized math package to calculate the gamma function to whatever > precision I thought Ineeded. > > > -- > > DaveA > Well, its in a puzzle.. everything is done except this part.?I need to calculate N! ( max value of N is 10^6). From waynejwerner at gmail.com Fri Dec 9 21:10:50 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 9 Dec 2011 14:10:50 -0600 Subject: [Tutor] Python Windows Vista Installation Question In-Reply-To: References: Message-ID: On Fri, Dec 9, 2011 at 12:41 PM, Homme, James wrote: > Hi, > > Can Python easily be installed on a Windows Vista computer without needing > administrative rights to that machine? > > > If you use portable python: http://www.portablepython.com/ that might work for you. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Dec 9 21:18:09 2011 From: d at davea.name (Dave Angel) Date: Fri, 09 Dec 2011 15:18:09 -0500 Subject: [Tutor] how to handle big numbers In-Reply-To: References: , <4EE26723.1020005@davea.name> Message-ID: <4EE26D01.6060403@davea.name> On 12/09/2011 03:04 PM, surya k wrote: > > > > ---------------------------------------- >> Date: Fri, 9 Dec 2011 14:53:07 -0500 >> From: d at davea.name >> To: suryak at live.com >> CC: tutor at python.org >> Subject: Re: [Tutor] how to handle big numbers >> >> On 12/09/2011 02:25 PM, surya k wrote: >>> Finding factorial of 8 or 9 isn't big. If I would like to find factorial of 32327, how can I ?? >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> How close do you want your answer? The gamma function can be used to >> calculate it, but it won't be precise. I don't know how many digits >> are in 32327!, but it must be at least hundreds of thousands, and a >> float cannot represent that exactly. In fact it cannot represent a >> number that big, even approximately. It might be millions of digits, >> but I don't have the time right now to figure it out. >> >> If you use a long int (which int will promote to, automatically), you >> could do the calculation with a very simple program, providing you don't >> run out of either time or memory. >> >> if it were my problem, I'd do it in three steps. First write a program >> to calculate N! exactly. See how long it takes for 100, and how many >> digits are in the answer. Then try it again for 1000! >> >> Next, I'd look up the gamma function, and figure out how large the >> desired value will be. >> >> Finally, depending on what I got from those first two, I'd either run >> the first program with 32327, and wait a long time, or write a >> specialized math package to calculate the gamma function to whatever >> precision I thought Ineeded. >> >> >> -- >> >> DaveA >> > > Well, its in a puzzle.. everything is done except this part. I need to calculate N! ( max value of N is 10^6). > I decided to take the time, and the desired number is 1317440 digits long, and takes about 3 seconds to compute. So try it, and forget my stuff till you want a really large factorial. I tried factorial of 10 times your number, and decided to kill it after 5 minutes. So if you have to go up to a million, my 3-part answer is still appropriate. If it's part of a larger puzzle, perhaps you are not really looking for the actual value, but are going to do something with it. For example, you may just want the last 1000 digits (I can tell you that answer without a program). What does your code look like so far? If it's more than one line, perhaps you haven't loooked hard enough at the standard library. it has both gamma and factorial functions. Unfortunately, the gamma function runs out of steam at less than 180, when the float just isn't big enough. There are other approaches that may bear looking at, like the SciPy library. But first we'd need to know just what you need with this factorial. -- DaveA From robert.sjoblom at gmail.com Fri Dec 9 21:32:35 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Fri, 9 Dec 2011 21:32:35 +0100 Subject: [Tutor] how to handle big numbers In-Reply-To: <4EE26D01.6060403@davea.name> References: <4EE26723.1020005@davea.name> <4EE26D01.6060403@davea.name> Message-ID: > There are other approaches that may bear looking at, like the SciPy library. > ?But first we'd need to know just what you need with this factorial. Wouldn't a prime swing implementation be the absolutely fastest? Something like this: http://en.literateprograms.org/Special:Downloadcode/Factorials_with_prime_factorization_%28Python%29 (Well, excepting actually storing prime numbers in a list which would be much, much faster) -- best regards, Robert S. From ramit.prasad at jpmorgan.com Fri Dec 9 22:13:27 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 9 Dec 2011 21:13:27 +0000 Subject: [Tutor] Python Windows Vista Installation Question In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740714E5@SCACMX008.exchad.jpmchase.net> >>Can Python easily be installed on a Windows Vista computer without needing administrative rights to that machine? >If you use portable python:?http://www.portablepython.com/?that might work for you. You can manually install python relatively easily without administrative rights. Although, "relatively" is subjective to the installer's abilities. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From malaclypse2 at gmail.com Fri Dec 9 22:28:38 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 9 Dec 2011 16:28:38 -0500 Subject: [Tutor] Python Windows Vista Installation Question In-Reply-To: References: Message-ID: On Fri, Dec 9, 2011 at 1:41 PM, Homme, James wrote: > Can Python easily be installed on a Windows Vista computer without needing > administrative rights to that machine? > I thought the standard installer worked for non-admin installs, as long as you select "Just for me" instead of "All users on this computer" when given the option. Did you try that? Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From rail.shafigulin at gmail.com Fri Dec 9 22:43:40 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Fri, 9 Dec 2011 16:43:40 -0500 Subject: [Tutor] attribute overwrite Message-ID: i need to overwrite and attribute from the inherited class. i also need to run the constructor of the super class. here is the code import datetime class DateTime(datetime.datetime): def __init__(self, year, month, day, *args): super().__init__(year, month, day, *args) if self.year >= 1000: self.year = self.year % 1000 i'm getting the following error: AttributeError: attribute 'year' of datetime.datetime objects are not writable. some of you might suggest to change self.year = self.year % 1000 to self.yr = self.year % 1000 but i'd need to keep the name the same. any help is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rail.shafigulin at gmail.com Fri Dec 9 23:14:44 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Fri, 9 Dec 2011 17:14:44 -0500 Subject: [Tutor] attribute overwrite In-Reply-To: References: Message-ID: On Fri, Dec 9, 2011 at 4:43 PM, rail shafigulin wrote: > i need to overwrite and attribute from the inherited class. i also need to > run the constructor of the super class. here is the code > > import datetime > > class DateTime(datetime.datetime): > def __init__(self, year, month, day, *args): > super().__init__(year, month, day, *args) > if self.year >= 1000: > self.year = self.year % 1000 > > i'm getting the following error: > AttributeError: attribute 'year' of datetime.datetime objects are not > writable. > > some of you might suggest to change > > self.year = self.year % 1000 > to > self.yr = self.year % 1000 > > but i'd need to keep the name the same. > > any help is appreciated. > > my apologies, but there is a minor mistake in the code: import datetime class DateTime(datetime.datetime): def __init__(self, year, month, day, *args): super().__init__() if self.year >= 1000: self.year = self.year % 1000 def main(): mytme = DateTime.now() if __name__ == '__main__' main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Sat Dec 10 00:16:46 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 9 Dec 2011 23:16:46 +0000 Subject: [Tutor] attribute overwrite In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474071642@SCACMX008.exchad.jpmchase.net> >class DateTime(datetime.datetime): > def __init__(self, year, month, day, *args): > super().__init__() > if self.year >= 1000: > self.year = self.year % 1000 I have no idea how you could use the sample you have given (or why) but, this was actually a fun exercise that forced me to learn more about immutable types (which makes sense because a date should never really be modifiable if you think about it). Instead of overriding the __init__ you need to override the __new__ method. Try the following >>> class DateTime(datetime.datetime): ... def __new__(self, year, month, day, *args): ... if year >= 1000: ... year = year % 1000 ... return super( DateTime, self ).__new__(self, year, month, day, *args ) ... >>> DateTime( 2011, 1, 1 ) DateTime(11, 1, 1, 0, 0) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of rail shafigulin Sent: Friday, December 09, 2011 4:15 PM To: tutor at python.org Subject: Re: [Tutor] attribute overwrite On Fri, Dec 9, 2011 at 4:43 PM, rail shafigulin wrote: i need to overwrite and attribute from the inherited class. i also need to run the constructor of the super class. here is the code import datetime class DateTime(datetime.datetime): ? def __init__(self, year, month, day, *args): ??? super().__init__(year, month, day, *args) ??? if self.year >= 1000: ????? self.year = self.year % 1000 i'm getting the following error: AttributeError: attribute 'year' of datetime.datetime objects are not writable. some of you might suggest to change self.year = self.year % 1000 to self.yr = self.year % 1000 but i'd need to keep the name the same. any help is appreciated. my apologies, but there is a minor mistake in the code: import datetime class DateTime(datetime.datetime): ? def __init__(self, year, month, day, *args): ??? super().__init__() ??? if self.year >= 1000: ????? self.year = self.year % 1000 def main(): ? mytme = DateTime.now() if __name__ == '__main__' ? main() This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Sat Dec 10 00:18:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 10 Dec 2011 10:18:38 +1100 Subject: [Tutor] how to handle big numbers In-Reply-To: References: Message-ID: <4EE2974E.2040606@pearwood.info> surya k wrote: > Finding factorial of 8 or 9 isn't big. If I would like to find factorial of 32327, how can I ?? py> import math py> n = math.factorial(32327) # takes about 2 seconds on my computer py> s = str(n) # takes about 30 seconds py> len(s) 131744 py> print s[:10] + "..." + s[-10:] 8648628691...0000000000 -- Steven From cranky.frankie at gmail.com Sat Dec 10 02:58:32 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Fri, 9 Dec 2011 20:58:32 -0500 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: I appreciate all the comments in this thread so far, but what I'm really looking for is what to call the style of programming where you have no direct branching via line numbers, statement names, and gotos. I'm finding that lacking these things that I've been familiar with in other languages is good, in that it forces you to really think through the best way to organize the logic. It seems to me that this is such a big departure from traditional procedural styled programming there ought to be a name for it, other than structured programming, since you can code that way even with line numbers, etc. I'd also be interested in reading the Python history file. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From d at davea.name Sat Dec 10 03:20:10 2011 From: d at davea.name (Dave Angel) Date: Fri, 09 Dec 2011 21:20:10 -0500 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: <4EE2C1DA.4070709@davea.name> On 12/09/2011 08:58 PM, Cranky Frankie wrote: > I appreciate all the comments in this thread so far, but what I'm > really looking for is what to call the style of programming where you > have no direct branching via line numbers, statement names, and gotos. > I'm finding that lacking these things that I've been familiar with in > other languages is good, in that it forces you to really think through > the best way to organize the logic. > > It seems to me that this is such a big departure from traditional > procedural styled programming there ought to be a name for it, other > than structured programming, since you can code that way even with > line numbers, etc. > > I'd also be interested in reading the Python history file. > > It was called structured programming long ago. I don't understand your reluctance to use the name that has applied for at least 35 years. Just because some of those non-structured languages have survived, doesn't take anything away from the term procedural. You can write object oriented code in hex if you really want, it doesn't make raw machine language object oriented. I think it was Djikstra that said that a programmer that has learned BASIC has been ruined for life. And that statement was probably made about 30 years ago. And what has this got to do with Python? Pascal, C, and probably a thousand other languages have at least encouraged structured programming, long before Python came out. Python has lots more to offer than the mere absence of a feature that has been obsolete for so long. -- DaveA From cranky.frankie at gmail.com Sat Dec 10 03:43:36 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Fri, 9 Dec 2011 21:43:36 -0500 Subject: [Tutor] What style do you call Python programming? Message-ID: From: Dave Angel <> Probably because I work in a shop that still heavily uses older languages like COBOL and CULPRIT where you still deal with labels, branching, goto, etc. The fact that it is possible to code "structured" that way AND the Python way amazes me. -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From steve at pearwood.info Sat Dec 10 03:55:37 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 10 Dec 2011 13:55:37 +1100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: <4EE2CA29.20801@pearwood.info> Cranky Frankie wrote: > I appreciate all the comments in this thread so far, but what I'm > really looking for is what to call the style of programming where you > have no direct branching via line numbers, statement names, and gotos. Structured programming. > I'm finding that lacking these things that I've been familiar with in > other languages is good, in that it forces you to really think through > the best way to organize the logic. I'm curious what other languages you're familiar with that have GOTOs. > It seems to me that this is such a big departure from traditional > procedural styled programming there ought to be a name for it, other > than structured programming, since you can code that way even with > line numbers, etc. "Procedural" and "structured" coding are not opposites. By definition, procedural coding *must* be structured, but a procedural language can still include unstructured elements. E.g. both C and Pascal include GOTOs. Unstructured languages like early BASIC was not procedural, since it lacked functions, but it did have a very weak structural element in the form of the GOSUB command. Did you read the link on Wikipedia? http://en.wikipedia.org/wiki/Programming_paradigm Most languages contain elements of more than one style or paradigm, and styles overlap considerably. E.g. procedural, object-oriented and functional styles are all sub-types of structured programming. Python is also an imperative language: you are (generally) responsible for specifying the order in which statements are executed. But you can also program in a more declarative style. Google for Python and Prolog to see examples. > I'd also be interested in reading the Python history file. This is a good place to start: http://docs.python.org/py3k/whatsnew/index.html -- Steven From steve at pearwood.info Sat Dec 10 04:07:32 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 10 Dec 2011 14:07:32 +1100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: <4EE2CCF4.30706@pearwood.info> Cranky Frankie wrote: > From: Dave Angel > > < for at least 35 years. Just because some of those non-structured > languages have survived, doesn't take anything away from the term > procedural. You can write object oriented code in hex if you really > want, it doesn't make raw machine language object oriented.>> > > Probably because I work in a shop that still heavily uses older > languages like COBOL and CULPRIT where you still deal with labels, > branching, goto, etc. The fact that it is possible to code > "structured" that way AND the Python way amazes me. You have misunderstood. If you call GOTO (or its bizarre cousin, COMEFROM), you are *not* programming in a structured way. You are programming in an unstructured way. Some structured languages, like Cobol, C and Pascal, allow a full or limited unstructured style. Some, like ancient Basic, *only* included unstructured style -- but even Basic includes GOSUB, which is almost structured. Cobol 2002 is a mostly structured language, with functions, procedures and even objects. Way back in 1959, Cobol was unstructured, but that hasn't been the case for some time now. Nevertheless, it does include unstructured features, and programmers are free to ignore the structured features and use or abuse the unstructured features if they so choose. Even Python has a limited unstructured feature: exception handling with try blocks. This doesn't make Python unstructured. It makes it a structured language with one small and limited unstructured feature. -- Steven From sunil.techspk at gmail.com Sat Dec 10 08:41:56 2011 From: sunil.techspk at gmail.com (sunil tech) Date: Sat, 10 Dec 2011 13:11:56 +0530 Subject: [Tutor] Need Explanation... Message-ID: *hi,* * * *Consider a list: a = [1,2,3]* * * *& a simple function, which when called it will append 100 to the list.* * * *def app(x):* * return x.append(100)* * * *p = app(a)* * * *now list holds appended value [1,2,3,100]* *but p is empty... why it is?* * * *please teach.* -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Sat Dec 10 09:11:11 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Sat, 10 Dec 2011 13:41:11 +0530 Subject: [Tutor] Need Explanation... In-Reply-To: References: Message-ID: On Sat, Dec 10, 2011 at 1:11 PM, sunil tech wrote: > hi, > > Consider a list: a = [1,2,3] > > & a simple function, which when called it will append 100 to the list. > > def app(x): > ? ? ?return x.append(100) > > p = app(a) > > now list holds appended value [1,2,3,100] > but p is empty... why it is? > > please teach. > append() Method is a mutator; it modifies the list. DOES NOT return the modified list; returns None to be exact HTH Asokan Pichai From alan.gauld at btinternet.com Sat Dec 10 10:15:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Dec 2011 09:15:42 +0000 Subject: [Tutor] Need Explanation... In-Reply-To: References: Message-ID: On 10/12/11 07:41, sunil tech wrote: > /def app(x):/ > / return x.append(100)/ > / > /p = app(a)/ > / > /now list holds appended value [1,2,3,100]/ > /but p is empty... why it is?/ Because app() returns the result of append(). But append() returns None, since it modifies the list in place. This is one of the few features of Python I dislike. It would not have been difficult to make these modifier methods return the thing modified. This style would then allow chained methods. We do it with strings: "foobar is a string".rstrip('ing').upper() because strings are immutable. But we could have done it with other sequence types too. Sadly we didn't and history/tradition leaves us with these counterintuitive modifiers that return None. It catches everybody out at some point... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Sat Dec 10 10:56:32 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Dec 2011 10:56:32 +0100 Subject: [Tutor] Help with update_wrapper References: Message-ID: Emeka wrote: > Could someone explain " functools.update_wrapper" with simple examples? Since this is not for the absolute beginner I'm assuming you are already familiar with decorators. In their most common form these are functions that take a function and wrap that function into another function. @deco def f(...): ... is only syntactic sugar for def f(...): ... f = deco(f) i. e. you can get a decorated version of f on the fly with deco(f). Suppose you have a function add() that adds two arguments and a decorator log_call() that prints the name of the called function before calling it: >>> import pydoc >>> pydoc.pager = pydoc.plainpager # this lets you see the output of help() >>> from functools import update_wrapper >>> def add(x, y): ... "calculate x+y" ... return x + y ... >>> def log_call(f): ... def g(*args, **kw): ... print "calling", f.__name__ ... return f(*args, **kw) ... return g ... >>> add(1, 2) 3 >>> log_call(add)(3, 4) calling add 7 It works, but if you want to learn more about the decorated function >>> help(log_call(add)) Help on function g in module __main__: g(*args, **kw) you get the name, the signature and docstring of the wrapping function g(), i. e. by decorating it you lose valuable information about add(). If you decorate a mul() function >>> @log_call ... def mul(x, y): ... "multiply x and y" ... return x * y ... >>> help(mul) Help on function g in module __main__: g(*args, **kw) the help will be exactly the same. functools.update_wrapper() is a partial fix for the problem: >>> add2 = update_wrapper(log_call(add), add) >>> add2(5, 6) calling add 11 >>> help(add2) Help on function add in module __main__: add(*args, **kw) calculate x+y It copies name and docstring (but not the function signature). However, I don't think I will ever use it directly, I'd prefer using functools.wraps: >>> def log_call2(f): ... @wraps(f) ... def g(*args, **kw): ... print "calling", f.__name__ ... return f(*args, **kw) ... return g ... >>> @log_call2 ... def add(x, y): ... "yadda" ... return x + y ... >>> add(1, 2) calling add 3 >>> help(add) Help on function add in module __main__: add(*args, **kw) yadda If you are seriously interested in this you should also have a look at Michele Simionato's decorator module (http://pypi.python.org/pypi/decorator) that also fixes the signature: >>> import decorator >>> @decorator.decorator ... def log_call(f, *args, **kw): ... print "calling", f.__name__ ... return f(*args, **kw) ... >>> @log_call ... def add(x, y): ... "calculate x+y" ... return x + y ... >>> add(1, 2) calling add 3 >>> help(add) Help on function add in module __main__: add(x, y) calculate x+y From __peter__ at web.de Sat Dec 10 11:09:58 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Dec 2011 11:09:58 +0100 Subject: [Tutor] how to handle big numbers References: Message-ID: surya k wrote: > Finding factorial of 8 or 9 isn't big. If I would like to find factorial > of 32327, how can I ? gmpy is a library designed for working with large numbers. Compare: >>> import time >>> def bench(f, *args): ... start = time.time() ... try: ... return f(*args) ... finally: ... print time.time() - start ... >>> def fac(n): ... f = 1 ... for i in xrange(1, n+1): ... f *= i ... return f ... >>> x = bench(fac, 1000) 0.00276589393616 >>> x = bench(fac, 10000) 0.247038125992 >>> x = bench(fac, 30000) 1.40305805206 >>> import gmpy >>> x = bench(gmpy.fac, 30000) 0.0243360996246 >>> x = bench(gmpy.fac, 10**6) 0.8047311306 >>> x.numdigits() 5565709 http://pypi.python.org/pypi/gmpy From mat.korycinski at gmail.com Sat Dec 10 11:12:38 2011 From: mat.korycinski at gmail.com (=?UTF-8?B?TWF0ZXVzeiBLb3J5Y2nFhHNraQ==?=) Date: Sat, 10 Dec 2011 11:12:38 +0100 Subject: [Tutor] Pysces Problem In-Reply-To: References: Message-ID: <4EE33096.9060708@gmail.com> Hi, Does any of you use Pysces? I need to run some simulations and unfortunately I cannot create plot. After importing Pysces it claims that Matplotlib is not available, but it's installed for sure since I can import matplotlib. When I try to do plot after simulation: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /home/mateusz/Pysces/ in () ----> 1 mod.doSimPlot() /usr/lib/python2.7/site-packages/pysces/PyscesModel.pyc in doSimPlot(self, end, points, plot, fmt, filename) 5584 self.sim_points = points 5585 self.Simulate() -> 5586 self.SimPlot(plot=plot, format=fmt, filename=filename) 5587 5588 def doSimPerturb(self,pl,end): /usr/lib/python2.7/site-packages/pysces/PyscesModel.pyc in SimPlot(self, plot, filename, title, log, format) 6955 data, labels = self.data_sim.getSimData(*plot, **kwargs) 6956 del allowedplots -> 6957 plt.plotLines(data, 0, range(1, data.shape[1]), titles=labels, formats=[format]) 6958 # set the x-axis range so that it is original range + 0.2*sim_end 6959 # this is a sceintifcally dtermned amount of space that is needed for the title at the AttributeError: 'NoneType' object has no attribute 'plotLines' I've already exported matplotlib localization in ipython by: sys.path.append("/usr/lib/python2.7/site-packages/") Thank you in advance for any help! Cheers, Mateusz From lina.lastname at gmail.com Sat Dec 10 15:49:00 2011 From: lina.lastname at gmail.com (lina) Date: Sat, 10 Dec 2011 22:49:00 +0800 Subject: [Tutor] how to handle big numbers In-Reply-To: References: Message-ID: On Sat, Dec 10, 2011 at 6:09 PM, Peter Otten <__peter__ at web.de> wrote: > surya k wrote: > >> Finding factorial of 8 or 9 isn't big. If I would like to find factorial >> of 32327, how can I ? > > gmpy is a library designed for working with large numbers. Compare: > >>>> import time >>>> def bench(f, *args): > ... ? ? start = time.time() > ... ? ? try: > ... ? ? ? ? ? ? return f(*args) > ... ? ? finally: > ... ? ? ? ? ? ? print time.time() - start > ... >>>> def fac(n): > ... ? ? f = 1 > ... ? ? for i in xrange(1, n+1): > ... ? ? ? ? ? ? f *= i > ... ? ? return f > ... sorry to interrupt, I tried your example, $ cat time_func.py #!/usr/bin/python3 import time def bench(f, *args): start = time.time() try: return f(*args) finally: print(time.time() - start) def fac(n): f = 1 for i in range(1,n+1): f *= i return f on idle3 >>> import time_func >>> time_func.bench(time_func.fac,1000) 0.0015549659729003906 402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 >>> time_func.bench(time_func.fac,100) 2.193450927734375e-05 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 why the output so long, Thanks, >>>> x = bench(fac, 1000) > 0.00276589393616 >>>> x = bench(fac, 10000) > 0.247038125992 >>>> x = bench(fac, 30000) > 1.40305805206 >>>> import gmpy >>>> x = bench(gmpy.fac, 30000) > 0.0243360996246 >>>> x = bench(gmpy.fac, 10**6) > 0.8047311306 >>>> x.numdigits() > 5565709 > > http://pypi.python.org/pypi/gmpy > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Sat Dec 10 16:37:31 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 10 Dec 2011 16:37:31 +0100 Subject: [Tutor] how to handle big numbers References: Message-ID: lina wrote: > On Sat, Dec 10, 2011 at 6:09 PM, Peter Otten <__peter__ at web.de> wrote: >> surya k wrote: >> >>> Finding factorial of 8 or 9 isn't big. If I would like to find factorial >>> of 32327, how can I ? >> >> gmpy is a library designed for working with large numbers. Compare: >> >>>>> import time >>>>> def bench(f, *args): >> ... start = time.time() >> ... try: >> ... return f(*args) >> ... finally: >> ... print time.time() - start >> ... >>>>> def fac(n): >> ... f = 1 >> ... for i in xrange(1, n+1): >> ... f *= i >> ... return f >> ... > > sorry to interrupt, I tried your example, > > $ cat time_func.py > #!/usr/bin/python3 > > import time > > def bench(f, *args): > start = time.time() > try: > return f(*args) > finally: > print(time.time() - start) > > def fac(n): > f = 1 > for i in range(1,n+1): > f *= i > return f > > on idle3 > >>>> import time_func >>>> time_func.bench(time_func.fac,1000) > 0.0015549659729003906 > 402...[snip many digits]...000 > > why the output so long, bench() calls the function passed as its first argument with the arguments that follow, prints the time this function takes and returns the result of the function call. In the case of bench(fac, 1000) that result is fac(1000), or 1*2*3*4*...*997*998*999*1000 -- a number with 2568 digits. To avoid printing out these huge numbers I assigned them to x >>>>> x = bench(fac, 1000) >> 0.00276589393616 Therfore you only see the time in seconds which is printed rather than returned by bench(). From andreas.perstinger at gmx.net Sat Dec 10 17:29:25 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 10 Dec 2011 17:29:25 +0100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: Message-ID: <4EE388E5.4050102@gmx.net> On 2011-12-09 20:46, Alan Gauld wrote: > On 09/12/11 19:24, Alan Gauld wrote: > >> In February 1991, after just over a year of development, I decided to >> post to USENET. The rest is in the Misc/HISTORY file. >> >> ============================= >> >> Hopefully that clarifies rather than condfusing! :-) >> The HISTORY file gives more detail still. > > Hmm, I just went to check the HISTORY file and I can't find it. > It used to come with the source tarball, but I haven't downloaded > the source for years!... http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY > Where has the online source code repository gone? http://hg.python.org/cpython/branches Bye, Andreas From steve at pearwood.info Sat Dec 10 17:46:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 11 Dec 2011 03:46:11 +1100 Subject: [Tutor] Need Explanation... In-Reply-To: References: Message-ID: <4EE38CD3.6000704@pearwood.info> Alan Gauld wrote: [...] > Because app() returns the result of append(). > But append() returns None, since it modifies the list in place. > > This is one of the few features of Python I dislike. It would not have > been difficult to make these modifier methods return the thing modified. > This style would then allow chained methods. Very true. It would be useful to be able to write: a = [1, 2, 3] a.append(4).insert(0, 0) But... > We do it with strings: > > "foobar is a string".rstrip('ing').upper() > > because strings are immutable. But we could have done it with other > sequence types too. Sadly we didn't and history/tradition leaves us with > these counterintuitive modifiers that return None. It catches everybody > out at some point... ...the alternative would also have caught out everybody at some point. Consider a hypothetical Python where mutator methods returned a result: a = [1, 2, 3] b = a.append(4) Does this mean...? * append 4 to a, then return a (and therefore a and b are alternative names for the same list) * append 4 to a, then return a copy of a (and therefore a and b are different lists that merely have the same content) * make a copy of a, then return the copy with 4 appended (and therefore a keeps its old value and b gets the new value) Since each of the behaviours are reasonable and useful under some circumstances, regardless of which behaviour was choosen for append, it would catch out some people some time. append() returning None is probably the least worst decision, since the error is obvious and so will likely be discovered as close as possible to the source of the error, rather than being subtle and so likely to cause hard-to-diagnose bugs. A better alternative would be for Python to have procedures as well as functions/methods, so that: b = a.append(4) would raise an exception immediately. This would require the language to distinguish between "returning None" and "doesn't return anything", which I believe would be a good thing. -- Steven From massimodisasha at gmail.com Sat Dec 10 17:46:33 2011 From: massimodisasha at gmail.com (Massimo Di Stefano) Date: Sat, 10 Dec 2011 11:46:33 -0500 Subject: [Tutor] how to return an object generated during a python threading code Message-ID: Hi All, i'm tring to learn how to use threads in python to save a list of object. i'm starting from this code : ##### import threading import urllib from tempfile import NamedTemporaryFile singlelock = threading.Lock() class download(threading.Thread): def __init__(self, sitecode, lista): threading.Thread.__init__(self) self.sitecode = sitecode self.status = -1 def run(self): url = "http://waterdata.usgs.gov/nwis/monthly?referred_module=sw&site_no=" url += self.sitecode url += "&PARAmeter_cd=00060&partial_periods=on&format=rdb&submitted_form=parameter_selection_list" tmp = NamedTemporaryFile(delete=False) urllib.urlretrieve(url, tmp.name) print "loaded Monthly data for sitecode : ", self.sitecode lista.append(tmp.name) print lista sitecodelist = ["01046500", "01018500", "01010500", "01034500", "01059000", "01066000", "01100000"] lista = [] for k in sitecodelist: get_data = download(k,lista) get_data.start() ##### it just print out the list generated during the thread execution, while i'm tring to return it. Trying to read the documentation, i'm looking on how to use " threading.Lock() " and its methods "acquire() and release()" that seems to be the solution to my issue ... but i'm really far to understand how to implement it in my example code. thanks so much for any hints! -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Dec 10 17:58:04 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 10 Dec 2011 08:58:04 -0800 Subject: [Tutor] how to return an object generated during a python threading code In-Reply-To: References: Message-ID: On 12/10/2011 8:46 AM Massimo Di Stefano said... > Hi All, > > i'm tring to learn how to use threads in python to save a list of > object. i'm starting from this code : > Moving lista into the instance seems to do it... Emile > ##### import threading import urllib from tempfile import NamedTemporaryFile singlelock = threading.Lock() class download(threading.Thread): def __init__(self, sitecode, lista): threading.Thread.__init__(self) self.sitecode = sitecode self.status = -1 self.lista = lista def run(self): url = "http://waterdata.usgs.gov/nwis/monthly?referred_module=sw&site_no=" url += self.sitecode url += "&PARAmeter_cd=00060&partial_periods=on&format=rdb&submitted_form=parameter_selection_list" tmp = NamedTemporaryFile(delete=False) urllib.urlretrieve(url, tmp.name) print "loaded Monthly data for sitecode : ", self.sitecode self.lista.append(tmp.name) print lista sitecodelist = ["01046500", "01018500", "01010500", "01034500", "01059000", "01066000", "01100000"] lista = [] for k in sitecodelist: get_data = download(k,lista) get_data.start() > ##### > > it just print out the list generated during the thread execution, while > i'm tring to return it. > > Trying to read the documentation, i'm looking on how to use " > threading.Lock() " and its methods "acquire() and release()" that seems > to be the solution to my issue > > ... but i'm really far to understand how to implement it in my example code. > > thanks so much for any hints! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Dec 10 18:04:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Dec 2011 17:04:19 +0000 Subject: [Tutor] Need Explanation... In-Reply-To: <4EE38CD3.6000704@pearwood.info> References: <4EE38CD3.6000704@pearwood.info> Message-ID: On 10/12/11 16:46, Steven D'Aprano wrote: > ...the alternative would also have caught out everybody at some point. > Consider a hypothetical Python where mutator methods returned a result: > > a = [1, 2, 3] > b = a.append(4) > > Does this mean...? > > * append 4 to a, then return a (and therefore a and b are > alternative names for the same list) This is what I'd expect. I'm thinking about the Smalltalk model where the default return value from a method is self... I'm particularly sensitive to this just now because I'm playing with Squeak (again) and the elegance and consistency of Smalltalk's mechanism stands in stark contrast to the mixed model in Python. (OTOH Smalltalk overall is a frustrating experience for me, I would like to love it but never quite get there... :-) > circumstances, regardless of which behaviour was choosen for append, it > would catch out some people some time. Probably, although if returning 'self' were the default (which of course only makes sense in a pure OO world like Smalltalk) people would get used to the semantics. Consistency is all in these kinds of situations. Sadly its one of the few areas where Python is slightly inconsistent. > A better alternative would be for Python to have procedures as well as > functions/methods, so that: > > b = a.append(4) > > would raise an exception immediately. Better than silently returning None for sure. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Dec 10 18:04:29 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 11 Dec 2011 04:04:29 +1100 Subject: [Tutor] how to return an object generated during a python threading code In-Reply-To: References: Message-ID: <4EE3911D.3060601@pearwood.info> Massimo Di Stefano wrote: [...] > it just print out the list generated during the thread execution, while i'm tring to return it. Since lista is a mutable global variable, you don't need to return it. Just look at lista once the threads have completed its work and you will find the content you expect. -- Steven From alan.gauld at btinternet.com Sat Dec 10 18:12:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Dec 2011 17:12:31 +0000 Subject: [Tutor] What style do you call Python programming? In-Reply-To: <4EE388E5.4050102@gmx.net> References: <4EE388E5.4050102@gmx.net> Message-ID: On 10/12/11 16:29, Andreas Perstinger wrote: >> Hmm, I just went to check the HISTORY file and I can't find it. >> It used to come with the source tarball, but I haven't downloaded >> the source for years!... > > http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY > Thanks Andreas. Now, how was I supposed to find that? Is it linked in any way from the main Python.org website? I couldn't find it (or the code) anywhere. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From andreas.perstinger at gmx.net Sat Dec 10 18:49:37 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 10 Dec 2011 18:49:37 +0100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: <4EE388E5.4050102@gmx.net> Message-ID: <4EE39BB1.9040508@gmx.net> On 2011-12-10 18:12, Alan Gauld wrote: > On 10/12/11 16:29, Andreas Perstinger wrote: > >>> Hmm, I just went to check the HISTORY file and I can't find it. >>> It used to come with the source tarball, but I haven't downloaded >>> the source for years!... >> >> http://hg.python.org/cpython/file/e37a7dc8944e/Misc/HISTORY >> > > Thanks Andreas. Now, how was I supposed to find that? Is it linked in > any way from the main Python.org website? I couldn't find it (or the > code) anywhere. > On www.python.org there is on the left sidebar a link to the "Core Development". This gets you to the "Developer's Guide" where you'll find in the QuickStart-Section the link to the Mercurial-Repository. Bye, Andreas From mlybrand at gmail.com Sat Dec 10 18:54:15 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Sat, 10 Dec 2011 09:54:15 -0800 Subject: [Tutor] TypeError in class destructor Message-ID: I am working on the Files chapter of Dive into Python 3, and have implemented the example script at the end of this message. The first input prints to the terminal as expected, the second value prints to the file as expected. Then the script tries to destroy in the class instance and bombs with: TypeError: __exit__() takes exactly 1 positional argument (4 given) Exception ValueError: 'I/O operation on closed file.' in <_io.TextIOWrapper name ='out.log' mode='w' encoding='utf-8'> ignored and the final input is, naturally, never printed. Is the example wrong, or is this something to do with how Windows handles stdout that is causing this not to work as designed? I am using Python 3.2 on Windows Vista Home Premium. import sys class RedirectStdoutTo: def __init__(self, out_new): self.out_new = out_new def __enter__(self): self.out_old = sys.stdout sys.stdout = self.out_new def __exit__(self): sys.stdout = self.out_old print('A') with open('out.log', mode='w', encoding='utf-8') as a_file, RedirectStdoutTo(a_file): print('B') print('C') -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Dec 10 20:22:10 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 10 Dec 2011 19:22:10 +0000 Subject: [Tutor] TypeError in class destructor In-Reply-To: References: Message-ID: Hi Mark, On 10 December 2011 17:54, Mark Lybrand wrote: > > I am working on the Files chapter of Dive into Python 3, and have implemented the example script at the end of this message.? The first input prints to the terminal as expected, the second value prints to the file as expected.? Then the script tries to destroy in the class instance and bombs with: > > TypeError: __exit__() takes exactly 1 positional argument (4 given) > Exception ValueError: 'I/O operation on closed file.' in <_io.TextIOWrapper name > ='out.log' mode='w' encoding='utf-8'> ignored > > and the final input is, naturally, never printed. > > Is the example wrong, or is this something to do with how Windows handles stdout that is causing this not to work as designed?? I am using Python 3.2 on Windows Vista Home Premium. It seems the example may be wrong -- the __exit__ method, as stated by the error, is being given 4 parameters whereas the one defined in the code only expects one.? I've looked an this is correct on Python 3.2 that I have on Windows as well. Perhaps the implementation of __exit__ has been changed somewhere and had the paramters added and the book is just out of date?? In any case, changing the def __exit__ line to: def __exit__(self, type, value, traceback): ... will fix the problem. Cheers Walter From andreas.perstinger at gmx.net Sat Dec 10 20:56:02 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Sat, 10 Dec 2011 20:56:02 +0100 Subject: [Tutor] TypeError in class destructor In-Reply-To: References: Message-ID: <4EE3B952.9060609@gmx.net> On 2011-12-10 20:22, Walter Prins wrote: >> Is the example wrong, or is this something to do with how Windows >> handles stdout that is causing this not to work as designed? I am >> using Python 3.2 on Windows Vista Home Premium. > > It seems the example may be wrong -- the __exit__ method, as stated > by the error, is being given 4 parameters whereas the one defined in > the code only expects one. I've looked an this is correct on Python > 3.2 that I have on Windows as well. Perhaps the implementation of > __exit__ has been changed somewhere and had the paramters added and > the book is just out of date? In any case, changing the def > __exit__ line to: > > def __exit__(self, type, value, traceback): > > ... will fix the problem. Perhaps a typo in the book, because the online-version (http://www.diveintopython3.net/examples/stdout.py) works: def __exit__(self, *args): sys.stdout = self.out_old Bye, Andreas From maxskywalker1 at gmail.com Sat Dec 10 21:53:35 2011 From: maxskywalker1 at gmail.com (Max gmail) Date: Sat, 10 Dec 2011 15:53:35 -0500 Subject: [Tutor] Need Explanation... In-Reply-To: References: <4EE38CD3.6000704@pearwood.info> Message-ID: <465111ED-4C4B-4783-955F-E014D8AB082C@gmail.com> On Dec 10, 2011, at 12:04 PM, Alan Gauld wrote: > On 10/12/11 16:46, Steven D'Aprano wrote: > >> ...the alternative would also have caught out everybody at some point. >> Consider a hypothetical Python where mutator methods returned a result: >> >> a = [1, 2, 3] >> b = a.append(4) >> >> Does this mean...? >> >> * append 4 to a, then return a (and therefore a and b are >> alternative names for the same list) > > This is what I'd expect. > I'm thinking about the Smalltalk model where the default return > value from a method is self... > > I'm particularly sensitive to this just now because I'm playing > with Squeak (again) and the elegance and consistency of > Smalltalk's mechanism stands in stark contrast to the mixed > model in Python. (OTOH Smalltalk overall is a frustrating > experience for me, I would like to love it but never quite > get there... :-) Personally, I found that returning a copy of a seemed more logical- after all, if you return 4 to b, then adding 2 to b wouldn't make 4 equal 6. > >> circumstances, regardless of which behaviour was choosen for append, it >> would catch out some people some time. > > Probably, although if returning 'self' were the default (which > of course only makes sense in a pure OO world like Smalltalk) people would get used to the semantics. Consistency is all in these kinds of situations. Sadly its one of the few areas where Python is slightly inconsistent. > >> A better alternative would be for Python to have procedures as well as >> functions/methods, so that: >> >> b = a.append(4) >> >> would raise an exception immediately. > > Better than silently returning None for sure. Of course, by silently returning None, you can just go on with your daily life and be happily ignorant of any return value; in other more strongly typed languages, the void functions/methods tend to alter other variables and situations more than, for example, ints. I feel myself that it is no more trouble to simply type 'a.append(4); b = a'. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From mlybrand at gmail.com Sat Dec 10 22:06:41 2011 From: mlybrand at gmail.com (Mark Lybrand) Date: Sat, 10 Dec 2011 13:06:41 -0800 Subject: [Tutor] TypeError in class destructor In-Reply-To: <4EE3B952.9060609@gmx.net> References: <4EE3B952.9060609@gmx.net> Message-ID: def __exit__(self, *args): Thanks guys. This is the solution I implemented and it works great. Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Dec 10 23:42:20 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 10 Dec 2011 22:42:20 +0000 (GMT) Subject: [Tutor] Need Explanation... In-Reply-To: <465111ED-4C4B-4783-955F-E014D8AB082C@gmail.com> References: <4EE38CD3.6000704@pearwood.info> <465111ED-4C4B-4783-955F-E014D8AB082C@gmail.com> Message-ID: <1323556940.97482.YahooMailNeo@web86702.mail.ird.yahoo.com> >> Smalltalk's mechanism? stands in stark contrast to the mixed >> model in Python. (OTOH Smalltalk overall is a frustrating >> experience for me, I would like to love it but never quite >> get there... :-) > >Personally, I found that returning a copy of a seemed more logical- after all,? >if you return 4 to b, then adding 2 to b wouldn't make 4 equal 6. > >But the object is modified in both cases.? But returning a copy loses the biggest advantage of returning self,? namely, that you can chain methods. As it is you have to do: a.append(42) a.sort() b = a[3] With self returns you can write b = a.append(42).sort().[3] The best we can do in Python is two lines: a.append(42) b = sorted(a)[3] Being able to chain methods is a very powerful idiom. Just look at how often people do it with strings. aList = myFile.read().strip().split() is a particularly common pattern that relies on string modifier? operations returning the modified string. > Better than silently returning None for sure. > >Of course, by silently returning None, you can just go on with your daily life? >and be happily ignorant of any return value;?As you can with any default return value. After all printf() in C returns the number of characters printed, but? when was the last time you saw code that did anything with the? return value from printf()? Similarly with None, most Pythonistas just ignore it. The same applies to self,? you would just ignore it if you didn't need it. in other more strongly typed languages, the void functions/methods tend? >to alter other variables and situations more than, for example, ints. ?Sorry I don't get that bit. a void function doesn't alter anything.? At least no more than an int function can. I feel myself that it is no more trouble to simply type 'a.append(4); b = a'.But that's not chaining methods that's setting two variables to refer to the same object. Not particularly useful most of the time. Alan g. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Dec 11 02:53:26 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 11 Dec 2011 12:53:26 +1100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: <4EE233E7.5040902@pearwood.info> Message-ID: On 12/10/2011 03:52 AM, Sarma Tangirala wrote: > > Well, what I meant was the way you write things like list comprehension. > I agree, that comment gave a completely incorrect picture. Sorry about that. list comprehension originated from Haskell, which is a language with a very strong functional paradigm. Functions/procedures comes from procedural paradigm. for-loop, while-loop, and if-conditional comes from structured programming. Classes comes from object-oriented programming. Although I've said such, the terms are not actually that clear cut. Most object-oriented languages also have a for-loop, while-loop, and if-conditional of a structured programming. And not all object-oriented languages have classes (e.g. javascript). From lie.1296 at gmail.com Sun Dec 11 04:23:31 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 11 Dec 2011 14:23:31 +1100 Subject: [Tutor] Need Explanation... In-Reply-To: References: <4EE38CD3.6000704@pearwood.info> Message-ID: On 12/11/2011 04:04 AM, Alan Gauld wrote: > On 10/12/11 16:46, Steven D'Aprano wrote: >> circumstances, regardless of which behaviour was choosen for append, it >> would catch out some people some time. > > Probably, although if returning 'self' were the default (which > of course only makes sense in a pure OO world like Smalltalk) people > would get used to the semantics. Consistency is all in these kinds of > situations. Sadly its one of the few areas where Python is slightly > inconsistent. If returning 'self' is the default expected behavior, it would cause inconsistencies with respect to immutable types. For example, `5 .__add__(2)`, one could expect it to return 5 instead of 7. While I liked the attraction of "fluent interface" of being able to easily chain function calls, it is inherently more inconsistent than what Python are doing. From steve at pearwood.info Sun Dec 11 04:33:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 11 Dec 2011 14:33:43 +1100 Subject: [Tutor] What style do you call Python programming? In-Reply-To: References: <4EE233E7.5040902@pearwood.info> Message-ID: <4EE42497.1030608@pearwood.info> Lie Ryan wrote: > Although I've said such, the terms are not actually that clear cut. Most > object-oriented languages also have a for-loop, while-loop, and > if-conditional of a structured programming. And not all object-oriented > languages have classes (e.g. javascript). There is a lot of overlap in programming paradigms. Javascript is an example of prototype-based object-oriented programming. Other examples include Lua and Flash. http://c2.com/cgi/wiki?PrototypeBasedProgramming http://en.wikipedia.org/wiki/Prototype-based_programming Class-based object-oriented programming and prototype-based ("classless") object-oriented programming are both sub-types of OOP. There's no reason you can't have both: Javascript has now introduced classes, and Python can support prototypes: http://lists.canonical.org/pipermail/kragen-hacks/2000-September/000264.html -- Steven From alan.gauld at btinternet.com Sun Dec 11 10:26:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Dec 2011 09:26:06 +0000 Subject: [Tutor] Need Explanation... In-Reply-To: References: <4EE38CD3.6000704@pearwood.info> Message-ID: On 11/12/11 03:23, Lie Ryan wrote: > If returning 'self' is the default expected behavior, it would cause > inconsistencies with respect to immutable types. For example, `5 > .__add__(2)`, one could expect it to return 5 instead of 7. That's not a case where default behaviour would be invoked. I'm talking about where None is currently returned. Returning None in the above case would make arithmetic impossible. In "modifying" immutables you have to return the modified value, that wouldn't change. And the same applies in Smalltalk, you only return self as a default value in those situations where there is no specific return value required (as Steve put it, for a "procedure like" function). It just makes those procedure like functions more usable IMHO. > While I liked the attraction of "fluent interface" of being able to > easily chain function calls, it is inherently more inconsistent than > what Python are doing. I disagree. However there are so many Smalltalk like features in Python that I'm sure Guido was well aware of returning self as an option and he obviously deliberately chose not to. So he presumably felt the gains were outweighed by the negatives. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From as.winshan at hotmail.com Mon Dec 12 06:49:03 2011 From: as.winshan at hotmail.com (Aswin Shan) Date: Sun, 11 Dec 2011 21:49:03 -0800 Subject: [Tutor] (no subject) Message-ID: Hi! I need help in creating a GUI for my python code to program a Hangman. I have programmed a working code of Hangman, but I need to make it to a proper program with GUI. please help. The code is given below: import random; import time; correct_guesses = ['-', ' '] guessed_letters = [] def Input_Error(input): if input.isdigit() == True: print "Input Error. \nIt's Hangman. Your secret word only includes letters. " while input.isdigit() == False: input = raw_input('Guess a letter: ') if len(input)>1: print 'Only enter one guess at a time' def Get_Random_Word(): global word word_list = [] for line in open('dictionary.txt'): word_list=line.split() wordno=random.randint(0, len(word_list) -1) word= word_list[wordno] print word return word def displayBoard(): display = [] i = 0 while i < len(word): if word[i] in correct_guesses: display.append(word[i]) if word[i] not in correct_guesses: display.append('_ ') i +=1 for w in display: print w, def play(): global player_guess global guess player_guess = (raw_input('\nGuess a letter: ')).lower() Input_Error(player_guess) guess = 0 while guess < 9: print guess if player_guess.lower() in guessed_letters: print "You have guessed this letter already" elif player_guess in word: guessed_letters.append(player_guess) correct_guesses.append(player_guess) elif player_guess not in word and player_guess.isdigit()== False: guessed_letters.append(player_guess) print 'wrong' guess += 1 if len(correct_guesses)-2 == len(word): print word print 'Congratulation, you guessed the word correctly in', guess, 'guesses.' break if guess == 8: break displayBoard() player_guess = (raw_input('\nGuess another letter: ')).lower() Input_Error(player_guess) def Welcome(): print """ | | | | /\ | ___ \ / _____) ___ \ /\ | ___ \ | |__ | | / \ | | | | / ___| | _ | | / \ | | | | | __)| |/ /\ \| | | | | (___) || || |/ /\ \| | | | | | | | |__| | | | | \____/| || || | |__| | | | | |_| |_|______|_| |_|\_____/|_||_||_|______|_| |_| Welcome to Hangman v1.0 Rules: 1. You will have 8 chances to guess the letters correctly. 2. For each wrong guess one chance will be decremented. 3. If you guess the same word again, the chances will not be decremented. Good luck.""" print "Generating your secret word..." time.sleep(3) Welcome() Get_Random_Word() displayBoard() play() I also find trouble with the some hangman pic which I have provided below. I shows a EOL Error. def Answer_Feedback(w_count): if w_count==1: print """ +---+ | | | | | | ========= Wrong! """ elif w_count == 2: print """ +---+ | | O | | | | ========= Wrong! """ elif w_count == 3: print """ +---+ | | O | | | | | ========= Wrong! """ elif w_count == 4: print """ +---+ | | O | /| | | | ========= Wrong! """ elif w_count == 5: print """ +---+ | | O | /| | | | ========= Wrong!"""" elif w_count == 6: print """ +---+ | | O | /|\ | | | ========= Wrong!""" elif w_count == 7: print """ +---+ | | O | /|\ | / | | ========= Wrong! """ elif w_count == 8: print """ _______ | | | O | ^-|-^ | | | | _|__ / \ You lost!!! """ Thank you thanks for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Sun Dec 11 15:38:47 2011 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Mon, 12 Dec 2011 01:08:47 +1030 Subject: [Tutor] return, why do I need it? Message-ID: Hi I have been writing python code for a while now and I never return anything within any of my functions, I just (eg.) print stuff or make directories or update a log or what have you. When I look at other people's code they are always returning in their functions and I was wondering if someone could give me an example of when I would absolutely have to return something. The thing I don't like about returning is that when I unindent a function and try to run the code to inspect parts of it for debugging I always have to alter the code so as not to get the "return not inside a function error", so I will change the word "return" to "print" and in many cases that's the way I leave it. Anyone have any thoughts on this? Thanks Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Sun Dec 11 15:49:08 2011 From: suryak at live.com (surya k) Date: Sun, 11 Dec 2011 20:19:08 +0530 Subject: [Tutor] best book for OOP Message-ID: I'm reading "Core Python Programming" - Chun..? Currently, I am studying OOP in it.. and I feel there is something I am missing in that while studying. Actually I am from C.. so, no idea of OOP. Could you tell me the best, simple, easy to understand book!! From bodsda at googlemail.com Sun Dec 11 15:56:10 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Sun, 11 Dec 2011 14:56:10 +0000 Subject: [Tutor] return, why do I need it? In-Reply-To: References: Message-ID: <1106445358-1323615367-cardhu_decombobulator_blackberry.rim.net-1111591367-@b14.c12.bise7.blackberry> Why unindent functions for testing? Challenge: write a function called myadd(one, two) that accepts 2 parameters, both will be ints. When the function is called, it should add both parameters together. It should allow me to do this: a = myadd(5, 10) a += myadd(10, 5) a == 30 True Hopefully that shows one usage of return values Hth, Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: "Pete O'Connell" Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Mon, 12 Dec 2011 01:08:47 To: Subject: [Tutor] return, why do I need it? _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Dec 11 17:33:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Dec 2011 16:33:35 +0000 Subject: [Tutor] Hangman GUI In-Reply-To: References: Message-ID: On 12/12/11 05:49, Aswin Shan wrote: Please use a sensible subject line in your postings. It will help people find the thread and encourage those with appropriate skills to read it. > I need help in creating a GUI for my python code to program a Hangman. I > have programmed a working code of Hangman, but I need to make it to a > proper program with GUI. The first thing you need to do is restructure it to separate out the logic from the UI. Then modify it to be event driven. Then choose a GUI framework (like Tkinter or wxPython) to actually build the GUI bit. > import random; > import time; > correct_guesses = ['-', ' '] > guessed_letters = [] > def Input_Error(input): > if input.isdigit() == True: > print "Input Error. \nIt's Hangman. Your secret word only includes > letters. " > while input.isdigit() == False: > input = raw_input('Guess a letter: ') > if len(input)>1: > print 'Only enter one guess at a time' You need to remove all the print statements since they won't work in a GUI. return strings instead so that the GUI framework can call the function and then display the result in the GUI. > def Get_Random_Word(): > global word > word_list = [] > for line in open('dictionary.txt'): > word_list=line.split() > wordno=random.randint(0, len(word_list) -1) > word= word_list[wordno] > print word > return word Same here, remove the print. I assume in this case its only for debugging anyhow! > def displayBoard(): > display = [] > i = 0 > while i < len(word): > if word[i] in correct_guesses: > display.append(word[i]) > if word[i] not in correct_guesses: > display.append('_ ') > i +=1 > for w in display: > print w, O)bviously this will need to be rewritten using the GUI framework of your choice. > def play(): This will dissappear and be replaced by events from the GUI. > global player_guess > global guess > player_guess = (raw_input('\nGuess a letter: ')).lower() > Input_Error(player_guess) > guess = 0 > while guess < 9: > print guess > if player_guess.lower() in guessed_letters: > print "You have guessed this letter already" > elif player_guess in word: > guessed_letters.append(player_guess) So this will be replaced by a user typing a value into a field (or selecting a letter from a set of buttons?) and as a result calling an event handler to check for errors. Then checking valid inputs for an outcome... > correct_guesses.append(player_guess) > elif player_guess not in word and player_guess.isdigit()== False: You don't need the isdigit since you already checked that in Input_Error() above > guessed_letters.append(player_guess) > print 'wrong' > guess += 1 > if len(correct_guesses)-2 == len(word): > print word > print 'Congratulation, you guessed the word correctly in', guess, 'guesses.' > break > if guess == 8: > break And this stuff will all be replaced with code that updates results fields or labels/diagrams on the GUI. > displayBoard() This will happen automatically when the board changes. > player_guess = (raw_input('\nGuess another letter: ')).lower() > Input_Error(player_guess) > def Welcome(): > print """ | | | | /\ | ___ \ / _____) ___ \ /\ | ___ \ > | |__ | | / \ | | | | / ___| | _ | | / \ | | | | > | __)| |/ /\ \| | | | | (___) || || |/ /\ \| | | | > | | | | |__| | | | | \____/| || || | |__| | | | | > |_| |_|______|_| |_|\_____/|_||_||_|______|_| |_| > Welcome to Hangman v1.0 > Rules: > 1. You will have 8 chances to guess the letters correctly. > 2. For each wrong guess one chance will be decremented. > 3. If you guess the same word again, the chances will not be decremented. > Good luck.""" > print "Generating your secret word..." > time.sleep(3) And this will be built uinto a welcome window/splash-screen. > I also find trouble with the some hangman pic which I have provided > below. You should probably use images in the GUI version rather than draw the picture using ASCII art... You can find more info on event driven coding in my tutor under that heading. And you can get basic info on GUI programming in the tutor too. If you can find a dead-tree version of my tutorial (library?) it has a chapter with a Tkinter version of hangman as an example program. HTH. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Dec 11 17:45:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Dec 2011 16:45:19 +0000 Subject: [Tutor] best book for OOP In-Reply-To: References: Message-ID: On 11/12/11 14:49, surya k wrote: > > I'm reading "Core Python Programming" - Chun.. > Currently, I am studying OOP in it.. and I feel there is > something I am missing in that while studying. > Actually I am from C.. so, no idea of OOP. > Could you tell me the best, simple, easy to understand book!! My personal favourite starter book is OOP by Timothy Budd. I'm not sure if its still in print but the first edition in particular introduced the concepts of OOP to non OOP programmers very well in a variety of programming languages. You might get a copy via your local library... Two other options with rather kore design focus and theoretcical rigour are: Object Oriented Analysis and Design with Applications by Grady Booch (1st edition) Classic text on OO Design with code and case studies realized in 5 different OOP languages (Smalltalk, Object Pascal, C++, Lisp, ADA) Explains why OOP is important and how to ise it effectively. Also introsduces Booch's OOD notation which was paret of the core that evolved into UML. Object Oriented Software Contruction by Bertrand Meyer (2nd edition) Highly recommendeed, possibly the best OOP book ever written. Unfortunately all in Eiffel, a very powerful and elegant language that virtually nobody actually uses! But the explanations of concepts are brilliant. If you understand this book from cover to cover you will be an OOP guru. Finally there is Bruce Eckel's ever popular pair: "Thinking In Java/C++" But frankly these are more likely to lead to bad habits for the Python programmerr because C++ and Java share a very narrow view of OOP which does not align well with Pythons more dynamic approach. Otherwise there are lots of web tutorials. Try cetus links. Or you could just try the OOP topic in my tutorial... :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Sun Dec 11 18:04:15 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 12 Dec 2011 01:04:15 +0800 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On Mon, Dec 12, 2011 at 1:49 PM, Aswin Shan wrote: > Hi! > I need help in creating a GUI for my python code to program a Hangman. I > have programmed a working code of Hangman, but I need to make it to a proper > program with GUI. please help. > The code is given below: > > import random; > import time; > > correct_guesses = ['-', ' '] > guessed_letters = [] > > > def Input_Error(input): > ??????? if input.isdigit() == True: > ??????????? print "Input Error. \nIt's Hangman. Your secret word only > includes letters. " > ??????????? while input.isdigit() == False: > ??????????????? input = raw_input('Guess a letter: ') > ??????? if len(input)>1: > ??????????? print 'Only enter one guess at a time' > > def Get_Random_Word(): > ??? global word > ??? word_list = [] > ??? for line in open('dictionary.txt'): > ??????? word_list=line.split() > ??? wordno=random.randint(0, len(word_list) -1) > ??? word= word_list[wordno] > ??? print word > ??? return word > > def displayBoard(): > ??? display = [] > ??? i = 0 > ??? while i < len(word): > ??????? if word[i] in correct_guesses: > ??????????? display.append(word[i]) > ??????? if word[i] not in correct_guesses: > ??????????? display.append('_ ') > ??????? i +=1 > ??? for w in display: > ??????? print w, > > def play(): > ??? global player_guess > ??? global guess > ??? player_guess = (raw_input('\nGuess a letter: ')).lower() > ??? Input_Error(player_guess) > ??? guess = 0 > ??? while guess < 9: > ??????? print guess > ??????? if player_guess.lower() in guessed_letters: > ??????????? print "You have guessed this letter already" > ??????? elif player_guess in word: > ??????????? guessed_letters.append(player_guess) > ??????????? correct_guesses.append(player_guess) > ??????? elif player_guess not in word and player_guess.isdigit()== False: > ??????????? guessed_letters.append(player_guess) > ??????????? print 'wrong' > ??????????? guess += 1 > ??????? if len(correct_guesses)-2 == len(word): > ??????????? print word > ??????????? print 'Congratulation, you guessed the word correctly in', > guess, 'guesses.' > ??????????? break > ??????? if guess == 8: > ??????????? break > ??????? displayBoard() > ??????? player_guess = (raw_input('\nGuess another letter: ')).lower() > ??????? Input_Error(player_guess) > > def Welcome(): > ??????? print """??????? | |?? | |? /\? |? ___ \ / _____)? ___ \?? /\? | > ___ \ > ??????? | |__ | | /? \ | |?? | | /? ___| | _ | | /? \ | |?? | | > ??????? |? __)| |/ /\ \| |?? | | | (___) || || |/ /\ \| |?? | | > ??????? | |?? | | |__| | |?? | | \____/| || || | |__| | |?? | | > ??????? |_|?? |_|______|_|?? |_|\_____/|_||_||_|______|_|?? |_| > > ????????????????????? Welcome to Hangman v1.0 > > Rules: > 1. You will have 8 chances to guess the letters correctly. > 2. For each wrong guess one chance will be decremented. > 3. If you guess the same word again, the chances will not be decremented. > > Good luck.""" > ??????? print "Generating your secret word..." > ??????? time.sleep(3) > > > > Welcome() > Get_Random_Word() > displayBoard() > play() > > > I also find trouble with the some hangman pic which I have provided below. I > shows a EOL Error. > def Answer_Feedback(w_count): > ??? if w_count==1: > ??????? print """ > ? +---+ > ? |?? | > ????? | > ????? | > ????? | > ????? | > ========= > Wrong!? """ > > ??? elif w_count == 2: > ??????? print """ > ? +---+ > ? |?? | > ? O?? | > ????? | > ????? | > ????? | > ========= > Wrong!? """ > ??? elif w_count == 3: > ??????? print """ > ? +---+ > ? |?? | > ? O?? | > ? |?? | > ????? | > ????? | > ========= > Wrong!? """ > ??? elif w_count == 4: > ??????? print """ > ? +---+ > ? |?? | > ? O?? | > /|?? | > ????? | > ????? | > ========= > Wrong!? """ > ??? elif w_count == 5: > ??????? print """ > ? +---+ > ? |?? | > ? O?? | > /|?? | > ????? | > ????? | > ========= > Wrong!"""" Here you used 4-" > ??? elif w_count == 6: > ??????? print """ > ? +---+ > ? |?? | > ? O?? | > /|\? | > ????? | > ????? | > ========= > Wrong!""" > ??? elif w_count == 7: > ??????? print """ > ? +---+ > ? |?? | > ? O?? | > /|\? | > /??? | > ????? | > ========= > Wrong! """ > ??? elif w_count == 8: > ??????? print """ > ? _______ > ? |???? | > ? |???? O > ? |?? ^-|-^ > ? |???? | > ? |???? | > _|__? / \ > > You lost!!! """ > > > > > > Thank you thanks for the help. > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From lie.1296 at gmail.com Sun Dec 11 18:25:42 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 12 Dec 2011 04:25:42 +1100 Subject: [Tutor] return, why do I need it? In-Reply-To: References: Message-ID: On 12/12/2011 01:38 AM, Pete O'Connell wrote: > Hi I have been writing python code for a while now and I never return > anything within any of my functions, I just (eg.) print stuff or make > directories or update a log or what have you. When I look at other > people's code they are always returning in their functions and I was > wondering if someone could give me an example of when I would absolutely > have to return something. The thing I don't like about returning is that > when I unindent a function and try to run the code to inspect parts of > it for debugging I always have to alter the code so as not to get the > "return not inside a function error", so I will change the word > "return" to "print" and in many cases that's the way I leave it. Anyone > have any thoughts on this? Functions returning a value is much more reusable than functions printing the value directly. For example, if you later decided that you want to store the calculation result in a file or display it in GUI or if you want to reuse the result for further calculation, you do not need to modify the function; you just need to modify the caller. And if you decided to create a GUI for your command line app, you can easily reuse functions returning a value but not when it printed them directly. From lie.1296 at gmail.com Sun Dec 11 18:52:40 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 12 Dec 2011 04:52:40 +1100 Subject: [Tutor] how to return an object generated during a python threading code In-Reply-To: References: Message-ID: On 12/11/2011 03:46 AM, Massimo Di Stefano wrote: > Hi All, > > Trying to read the documentation, i'm looking on how to use " > threading.Lock() " and its methods "acquire() and release()" that seems > to be the solution to my issue > > ... but i'm really far to understand how to implement it in my example code. You can call the .join() of the download threads in the main thread, so the main thread will wait until all download threads has finished downloading before inspecting lista. ... # spawn the download threads threads = [] for k in sitecodelist: get_data = download(k,lista) get_data.start() threads.append(get_data) # wait until all download threads finishes for th in threads: th.join() # now that all download threads has finished, start processing lista ... Alternatively, you can use a threading.Queue instead of a list for lista, to ensure thread safety without having to deal with (explicit) locking. From sunil.techspk at gmail.com Sun Dec 11 19:28:19 2011 From: sunil.techspk at gmail.com (Sunil Tech) Date: Sun, 11 Dec 2011 23:58:19 +0530 Subject: [Tutor] Need Explanation... In-Reply-To: References: <4EE38CD3.6000704@pearwood.info> Message-ID: *Thank you all...* *for your previous time. :) * On Sun, Dec 11, 2011 at 2:56 PM, Alan Gauld wrote: > On 11/12/11 03:23, Lie Ryan wrote: > > If returning 'self' is the default expected behavior, it would cause >> inconsistencies with respect to immutable types. For example, `5 >> .__add__(2)`, one could expect it to return 5 instead of 7. >> > > That's not a case where default behaviour would be invoked. > I'm talking about where None is currently returned. Returning None in the > above case would make arithmetic impossible. > > In "modifying" immutables you have to return the modified value, that > wouldn't change. And the same applies in Smalltalk, you only return self as > a default value in those situations where there is no specific return value > required (as Steve put it, for a "procedure like" function). > > It just makes those procedure like functions more usable IMHO. > > > While I liked the attraction of "fluent interface" of being able to >> easily chain function calls, it is inherently more inconsistent than >> what Python are doing. >> > > I disagree. > > However there are so many Smalltalk like features in Python that I'm sure > Guido was well aware of returning self as an option and he obviously > deliberately chose not to. So he presumably felt the gains were outweighed > by the negatives. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sun Dec 11 19:45:13 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 11 Dec 2011 12:45:13 -0600 Subject: [Tutor] return, why do I need it? In-Reply-To: References: Message-ID: On Dec 11, 2011 8:41 AM, "Pete O'Connell" wrote: > > Hi I have been writing python code for a while now and I never return anything within any of my functions, I just (eg.) print stuff or make directories or update a log or what have you. When I look at other people's code they are always returning in their functions and I was wondering if someone could give me an example of when I would absolutely have to return something. The thing I don't like about returning is that when I unindent a function and try to run the code to inspect parts of it for debugging I always have to alter the code so as not to get the "return not inside a function error", so I will change the word "return" to "print" and in many cases that's the way I leave it. Anyone have any thoughts on this? > No one has mentioned it so far, but the interactive interpreter is what you should use for debugging short code snippets. I always program with two windows open - one with my editor and one with the interpreter. This lets me try out short bits of code without running my whole program. Hth, Wayne > Thanks > Pete > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From thudfoo at gmail.com Sun Dec 11 19:48:40 2011 From: thudfoo at gmail.com (xDog Walker) Date: Sun, 11 Dec 2011 10:48:40 -0800 Subject: [Tutor] best book for OOP In-Reply-To: References: Message-ID: <201112111048.41053.thudfoo@gmail.com> On Sunday 2011 December 11 08:45, Alan Gauld wrote: > On 11/12/11 14:49, surya k wrote: > > Finally there is Bruce Eckel's ever popular pair: "Thinking In Java/C++" > But frankly these are more likely to lead to bad habits for the Python > programmerr because C++ and Java share a very narrow view of OOP which > does not align well with Pythons more dynamic approach. > Bruce has written one specifically for Python: Thinking In Python http://www.mindview.net/Books/TIPython -- I have seen the future and I am not in it. From robert.sjoblom at gmail.com Sun Dec 11 19:53:54 2011 From: robert.sjoblom at gmail.com (=?utf-8?Q?Robert_Sj=C3=B6blom?=) Date: Sun, 11 Dec 2011 19:53:54 +0100 Subject: [Tutor] return, why do I need it? In-Reply-To: References: Message-ID: <03479459-19E4-4629-967E-A73034AE6C5A@gmail.com> > On 12/12/2011 01:38 AM, Pete O'Connell wrote: >> Hi I have been writing python code for a while now and I never return >> anything within any of my functions, I just (eg.) print stuff or make >> directories or update a log or what have you. When I look at other >> people's code they are always returning in their functions and I was >> wondering if someone could give me an example of when I would absolutely >> have to return something. The thing I don't like about returning is that >> when I unindent a function and try to run the code to inspect parts of >> it for debugging I always have to alter the code so as not to get the >> "return not inside a function error", so I will change the word >> "return" to "print" and in many cases that's the way I leave it. Anyone >> have any thoughts on this? I don't think recursion would work very well without return values. For a simple example: def factor(a): if a == 0: return 1 else: return a * factor(a-1) This isn't a very good way to handle factorization, but it shows recursion somewhat well. From cranky.frankie at gmail.com Sun Dec 11 20:17:46 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Sun, 11 Dec 2011 14:17:46 -0500 Subject: [Tutor] best book for OOP Message-ID: surya k wrote: <> This book: http://www.amazon.com/Python-Programming-Absolute-Beginner-3rd/dp/1435455002/ref=sr_1_1?ie=UTF8&qid=1323630959&sr=8-1 has a really gentle, easy to follow OOP section, and he includes lots of programs where you can see how the classes and methods make sense (simple video games). I really found this book helpful. I just finished reading it for the second time! -- Frank L. "Cranky Frankie" Palmeri Risible Riding Raconteur & Writer ?How you do anything is how you do everything.? - from Alabama Crimson Tide training room From shtlor at yahoo.com Sun Dec 11 23:30:16 2011 From: shtlor at yahoo.com (shawn taylor) Date: Sun, 11 Dec 2011 14:30:16 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <1323642616.91585.YahooMailNeo@web45214.mail.sp1.yahoo.com> How do I do this Password Generator For this assignment, you will generate usernames and passwords for your school. The passwords have to be secure and based on information provided by the parents at registration. 1) Write a program that will prompt the user for FirstName LastName IDNumber BirthDay 2) generate the student?s username and password. 3) Test to see if the password and username works. RULES FOR GENERATING PASSWORD AND USERNAME The username is fairly straightforward it is composed of the student?s initials follow by the idnumber Username = + + The password is much more difficult. Step 1 ? pick the middle letter of the student?s first name. Step 2 ? pick the middle letter of the student?s last name. Step 3 ? Add all the digits in the student?s birthday. Keep adding until you get a single digit. Step 4 ? Add all the digits in the student?s idNumber. Keep adding until you get a single digit. Step 5 ? Multiply the month * day * year and divide by 17. Step 6 ? Multiply the first 2 digits of the idNumber by the last 3 digits of the idNumber / 7 Step 7 ? Multiply Step 5 by Step6 Step 8 ? Combine into a password Password = Concatenate ( + + + + ) -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Mon Dec 12 01:30:56 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 12 Dec 2011 01:30:56 +0100 Subject: [Tutor] (no subject) In-Reply-To: <1323642616.91585.YahooMailNeo@web45214.mail.sp1.yahoo.com> References: <1323642616.91585.YahooMailNeo@web45214.mail.sp1.yahoo.com> Message-ID: On Sun, Dec 11, 2011 at 11:30 PM, shawn taylor wrote: > How do I do this > > > Password Generator > For this assignment, you will generate usernames and passwords for your > school. The passwords have to be secure and based on information provided by > the parents at registration. > 1) Write a program that will prompt the user for > FirstName LastName IDNumber BirthDay > 2) generate the student?s username and password. > 3) Test to see if the password and username works. > RULES FOR GENERATING PASSWORD AND USERNAME > The username is fairly straightforward it is composed of the student?s > initials follow by the idnumber > Username = + + > > The password is much more difficult. > Step 1 ? pick the middle letter of the student?s first name. > Step 2 ? pick the middle letter of the student?s last name. > Step 3 ? Add all the digits in the student?s birthday. Keep adding until you > get a single digit. > Step 4 ? Add all the digits in the student?s idNumber. Keep adding until you > get a single digit. > Step 5 ? Multiply the month * day * year and divide by 17. > Step 6 ? Multiply the first 2 digits of the idNumber by the last 3 digits of > the idNumber / 7 > Step 7 ? Multiply Step 5 by Step6 > Step 8 ? Combine into a password > Password = Concatenate ( + + + + ) > This list is not here to do your homework. If you give it your best shot and come back and show us some code, with some specific questions of where you're having trouble there's a ton of people here who'd be quite happy to help you. But just copy-pasting your assignment here and adding the words "how do I do this" shows so little willingness to put in even the tiniest amount of effort that frankly, I find it rude and offensive. Hugo From alan.gauld at btinternet.com Mon Dec 12 01:46:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Dec 2011 00:46:05 +0000 Subject: [Tutor] best book for OOP In-Reply-To: <201112111048.41053.thudfoo@gmail.com> References: <201112111048.41053.thudfoo@gmail.com> Message-ID: On 11/12/11 18:48, xDog Walker wrote: >> Finally there is Bruce Eckel's ever popular pair: "Thinking In Java/C++" >> But frankly these are more likely to lead to bad habits for the Python >> programmerr because C++ and Java share a very narrow view of OOP which >> does not align well with Pythons more dynamic approach. >> > > Bruce has written one specifically for Python: Thinking In Python > > http://www.mindview.net/Books/TIPython Yes but when I looked at an early draft online it was a very different kind of book to his Java/C++ books. And I haven't looked at the finished version so can't recommend (or not) with any confidence. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Dec 12 01:56:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Dec 2011 00:56:02 +0000 Subject: [Tutor] (no subject) In-Reply-To: <1323642616.91585.YahooMailNeo@web45214.mail.sp1.yahoo.com> References: <1323642616.91585.YahooMailNeo@web45214.mail.sp1.yahoo.com> Message-ID: On 11/12/11 22:30, shawn taylor wrote: > How do I do this Read the assignment, it tells you exacvtly what you need to do. Now which bit of it do you not understand? Can you do step 1 - read the name, id and birthday? Can you generate the user name? As a hint you might want to write some helper functions to: getInitials(first,last) getMiddleLetter(aString) addDigits(aNumber) > > > Password Generator > For this assignment, you will generate usernames and passwords for your > school. The passwords have to be secure and based on information > provided by the parents at registration. > 1) Write a program that will prompt the user for > FirstName LastName IDNumber BirthDay > 2) generate the student?s username and password. > 3) Test to see if the password and username works. > RULES FOR GENERATING PASSWORD AND USERNAME > The username is fairly straightforward it is composed of the student?s > initials follow by the idnumber > Username = + + > > The password is much more difficult. > Step 1 ? pick the middle letter of the student?s first name. > Step 2 ? pick the middle letter of the student?s last name. > Step 3 ? Add all the digits in the student?s birthday. Keep adding until > you get a single digit. This is a bit confusing since I always get a single digit at the first digit? And if the student was born on the 9/9/1999 the total is more than one digit. So should we then sum the digits of the total? ie. 9/9/1999 -> 46 -> 10 -> 1? It's a badly worded requirement. > Step 4 ? Add all the digits in the student?s idNumber. Keep adding until > you get a single digit. Same problem here > Step 5 ? Multiply the month * day * year and divide by 17. > Step 6 ? Multiply the first 2 digits of the idNumber by the last 3 > digits of the idNumber / 7 > Step 7 ? Multiply Step 5 by Step6 > Step 8 ? Combine into a password > Password = Concatenate ( + + + + ) Ask a specific questuion and you will get specific help. Show us some code that you've written and you will get more help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Mon Dec 12 02:28:21 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 12 Dec 2011 02:28:21 +0100 Subject: [Tutor] (no subject) In-Reply-To: <1323651604.66626.YahooMailNeo@web45207.mail.sp1.yahoo.com> References: <1323642616.91585.YahooMailNeo@web45214.mail.sp1.yahoo.com> <1323651604.66626.YahooMailNeo@web45207.mail.sp1.yahoo.com> Message-ID: On Mon, Dec 12, 2011 at 2:00 AM, shawn taylor wrote: > I find it rude and offensive that you would make the assumption that this is > my homework, this is not my homework but a study guide for my final tomorrow > that I have no idea how to do. I have been working on this all day and this > was my last resort for finding help. I am new to python and my teacher has > taught us very little and expects us to be able to do this.??Thanks a lot > I'm probably going to my final, resulting in me failing the semester. > Alright, if it really isn't your homework, I'm sorry I made that assumption. However, since it starts with "in this assignment" and you had no further explanation, I don't really think it was an unfair assumption to make. You could've explained to us where the problem came from. You could have been a little more polite. After all you are asking us to take our personal time to help you. A please and thank you never hurt anyone. I could tell you how to do that assignment, but you'll learn very little from just reading my code. The best way to learn how to program is to just do it. As I said, if you get stuck and come to us with specific questions we'll be more than happy to help you. Alan has already stepped up and given you some pointers (he's really a much more patient person than I am most of the time ;) But he's keeping it kinda vague because really, your question is kinda vague too. Everything you need to do is right there in the assignment. So what do you already know, and what do you need help with? Be specific! Hugo P.S. make sure to CC the list so they know what's going on too. keeps discussion central. From bulent.arikan at gmail.com Mon Dec 12 07:00:51 2011 From: bulent.arikan at gmail.com (Bulent Arikan) Date: Mon, 12 Dec 2011 08:00:51 +0200 Subject: [Tutor] Running a script! Message-ID: Dear List, I am an absolute beginner to programming and Python. I have Python 2.6.5 and 3.2 running on Mac OS 10.6.8 Snow Leopard. I have self-help books but the problem I am having is not described in any of them. The answer may be too obvious though. I am using IDLE: I figured that I could call Idle by typing its name on the Terminal instead of launching it from the Applications ?WOW! big step ;)) When I save a script as (.py) document, I do not know how to 'run' it since the IDLE (2.6 or 3.2) menus do not have RUN option (as they describe in the books I have). I understand that I may have to type a command to run the script on the Terminal but I could not find a specific command. It also seemed strange to me that there was not a shortcut in Mac OS to run scripts unlike Windows. Thank you for your time and help, -- B?LENT -------------- next part -------------- An HTML attachment was scrubbed... URL: From das.mm.mm at gmail.com Mon Dec 12 07:26:28 2011 From: das.mm.mm at gmail.com (David Smith) Date: Mon, 12 Dec 2011 06:26:28 +0000 Subject: [Tutor] Running a script! In-Reply-To: References: Message-ID: <6F440ED4-BC58-4310-B0C4-61DC48379A62@gmail.com> If I have understood you correctly you are looking at the Python Shell. On this window choose File then New Window this will open a script window albeit without any code. This window will have a Run menu and within this menu there is a Run Module item which is what I think you are looking for. I hope this helps. Dax On 12 Dec 2011, at 06:00, Bulent Arikan wrote: > Dear List, > > I am an absolute beginner to programming and Python. I have Python 2.6.5 and 3.2 running on Mac OS 10.6.8 Snow Leopard. I have self-help books but the problem I am having is not described in any of them. The answer may be too obvious though. I am using IDLE: I figured that I could call Idle by typing its name on the Terminal instead of launching it from the Applications ?WOW! big step ;)) When I save a script as (.py) document, I do not know how to 'run' it since the IDLE (2.6 or 3.2) menus do not have RUN option (as they describe in the books I have). I understand that I may have to type a command to run the script on the Terminal but I could not find a specific command. It also seemed strange to me that there was not a shortcut in Mac OS to run scripts unlike Windows. > > Thank you for your time and help, > > -- > B?LENT > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wescpy at gmail.com Mon Dec 12 07:54:50 2011 From: wescpy at gmail.com (wesley chun) Date: Sun, 11 Dec 2011 22:54:50 -0800 Subject: [Tutor] best book for OOP In-Reply-To: References: Message-ID: what do you think you are missing? is there something in the book that you don't/can't understand? those of us on the list may be able to help you out... sometimes humans are better at explaining things than just books. :-) best regards, --wesley On Sun, Dec 11, 2011 at 6:49 AM, surya k wrote: > > I'm reading "Core Python Programming" - Chun.. > Currently, I am studying OOP in it.. and I feel there is something I am missing in that while studying. Actually I am from C.. so, no idea of OOP. > Could you tell me the best, simple, easy to understand book!! -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 ? ? http://withdjango.com wesley.chun : wescpy-gmail.com : @wescpy/+wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From das.mm.mm at gmail.com Mon Dec 12 08:57:16 2011 From: das.mm.mm at gmail.com (David Smith) Date: Mon, 12 Dec 2011 07:57:16 +0000 Subject: [Tutor] Visual and audible system bell Message-ID: Dear list In a terminal window python3.2 at the command gives me Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> then >>>> print ("\a") triggers a visual and audible bell as set in Terminal window preferences. However >>>> print ("\a") and pressing Enter in a Python Shell window or including print ("\a") input ("\n\nPress the enter key to exit.") results in neither a visible nor an audible system bell. Any suggestions? Mac OS X 10.7.2 Terminal 2.2.1(299) Python 3.2 Tk 8.5 Dax From alan.gauld at btinternet.com Mon Dec 12 09:18:51 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Dec 2011 08:18:51 +0000 Subject: [Tutor] Visual and audible system bell In-Reply-To: References: Message-ID: On 12/12/11 07:57, David Smith wrote: > In a terminal window >>>>> print ("\a") > > triggers a visual and audible bell as set in Terminal window preferences. > > However > >>>>> print ("\a") > and pressing Enter in a Python Shell window > results in neither a visible nor an audible system bell. I assume the second case means an IDLE window? If so then its not surprising because IDLE does not use the Terminal settings. It is its own Terminal. And IDLE intercepts many of the standard control keys etc. In general this is a good thing since IDLE is trying to make debugging and testing code as easy as possible so it prevents premature exit from IDLE. But occasionally it stops things happening the way you want. In this case no bell. (It is worth perusing the IDLE config settings, it may be possible to change this, but I suspect its more deeply embedded in the code than that) The only way round it is probably to just test your code by running it in a Terminal and just use IDLE for editing and debugging. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tvssarma.omega9 at gmail.com Mon Dec 12 09:46:08 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Mon, 12 Dec 2011 14:16:08 +0530 Subject: [Tutor] best book for OOP In-Reply-To: References: Message-ID: > Object Oriented Analysis and Design with Applications > by Grady Booch (1st edition) > Classic text on OO Design with code and case studies realized in 5 different OOP languages (Smalltalk, Object Pascal, C++, Lisp, ADA) > Explains why OOP is important and how to ise it effectively. Also introsduces Booch's OOD notation which was paret of the core that evolved into UML. > +1 Used this book in an OOAD course and was very good. -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Mon Dec 12 11:56:36 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 12 Dec 2011 11:56:36 +0100 Subject: [Tutor] (no subject) In-Reply-To: <1323658602.23744.YahooMailNeo@web45211.mail.sp1.yahoo.com> References: <1323642616.91585.YahooMailNeo@web45214.mail.sp1.yahoo.com> <1323651604.66626.YahooMailNeo@web45207.mail.sp1.yahoo.com> <1323658602.23744.YahooMailNeo@web45211.mail.sp1.yahoo.com> Message-ID: On Mon, Dec 12, 2011 at 3:56 AM, shawn taylor wrote: > firstname = raw_input ("Enter your first name ") > lastname = raw_input ("Enter your last name ") > idnumber = raw_input ("Enter your id number ") > birthday = raw_input ("Enter your birthday mm/dd/yyyy ") > username1 = firstname[0] + lastname[0] + idnumber > > print ("Your username is ") + username1 > > midltr = firstname[len(firstname) / 2] > midltrlastnm = lastname[len(lastname)??/ 2] > > on = int (birthday[0]) > tw = int (birthday[1]) > th = int (birthday[3]) > fr = int (birthday[4]) > fv = int (birthday[6]) > sx = int (birthday[7]) > sv = int (birthday[8]) > eg = int (birthday[9]) > > num = str (on + tw + th + fr + fv + sx + sv + et) > > while num > 10: > > > print num > > I'm trying to add all the digits in the birthday and keep adding till i get > a single digit and I'm stuck > anything would help thanks alright, well, you've got all the basic ideas that you need in there, it's just a matter of combining them in the right way. The basic component is the while loop you have, you want to keep adding the digits while there's more than two of them: while num > 10: #add digits there is a slight error in there (what happens if the number comes out to exactly ten? is that what should happen?), but I'll leave it in for you to find. Another problem is that the while loop wants to check the num variable, but it doesn't actually exist until the bottom of the loop. What we do have at the top of the loop is the birthday variable, but that has some pesky '/' characters in there that we don't really want. I suggest the first thing you do is remove those slashes. (hint: the str class has a replace() method. Google it and see if you can figure out how to use it for this purpose). no_slashes_birthday = # use replace here in someway on the birthday? num = int(no_slashes_birthday) while num > 10: #add digits that's enough for basic setup of the while loop. Now, to add the digits. First thing we'll need to do is separate our number out into digits. There's a nifty trick with the division and modulo operators that can get us individual digits[1], but I don't want to convolute the essence of this example with math. So here's a simpler way: leave your number as a string! As you've already figured out, it's easy to get characters in a string, and you can convert them to integers individually again. Ok, so we don't do num = int(no_slashes_birthday), but just num = no_slashes_birthday. Now we can get at the digits. All we need to do now is convert them all into integers and add them together inside the loop, and the loop will repeat it as necessary. The general structure is "for every digit in num, convert digit to integer and add digit to total." If you learn to state problems in this way, the necessary code should flow out from it almost automatically. We can already see that we'll need a for loop here, and a variable called total with a sensible starting value[2]. See if you can figure it out. We're almost done here. at the end of the loop we've got a variable called total, with our added digits. But the point of a loop is to run multiple times, and our loop wants to have this total in a variable called num, and it wants it to be a string so we can get at the individual digits again. So we want to take the integer from total, convert it back to a string, and put it in the num variable, right at the end of the loop. That way it can run over and over until we have only one digit left: no_slashes_birthday = # use replace here in someway on the birthday? num = no_slashes_birthday while num > 10: # for every digit, convert digit to int and add to total # convert total back to string and put it in num for the next iteration if you fill in the blanks you'll be almost done. There is one problem though, and it's in the condition of the while loop. The statement "while num > 10" makes no sense at all, because num, despite its name, is not a number but a string. Now *we* know that there are characters representing a number inside the string, but the computer doesn't care which characters represent a number and it shouldn't, because you've chosen to store it as a string. So for all it cares you might as well be asking if "hello" > 10, which very obviously doesn't make sense. See if you can find a way around this (hint: the requirement was "keep going while we have more than 1 digit." strings can't be compared to numbers, but they do have a length). And with that, you should be able to get it working. Good luck, and if you have any trouble come back here. Hugo P.S.: I wrote this as soon as I woke up. Hopefully this reaches you in time for you finals, though I fear the worst. In any case, (stating the obvious) it might be a good idea to start studying a little earlier next time ;) Programming isn't learned in a day. From bulent.arikan at gmail.com Mon Dec 12 11:59:36 2011 From: bulent.arikan at gmail.com (Bulent Arikan) Date: Mon, 12 Dec 2011 12:59:36 +0200 Subject: [Tutor] Tutor Digest, Vol 94, Issue 44 In-Reply-To: References: Message-ID: Thank you Dax! That was it! Now I can run the script. Cheers, Bulent On Mon, Dec 12, 2011 at 12:57 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Running a script! (Bulent Arikan) > 2. Re: Running a script! (David Smith) > 3. Re: best book for OOP (wesley chun) > 4. Visual and audible system bell (David Smith) > 5. Re: Visual and audible system bell (Alan Gauld) > 6. Re: best book for OOP (Sarma Tangirala) > 7. Re: (no subject) (Hugo Arts) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 12 Dec 2011 08:00:51 +0200 > From: Bulent Arikan > To: tutor at python.org > Subject: [Tutor] Running a script! > Message-ID: > > > Content-Type: text/plain; charset="windows-1252" > > Dear List, > > I am an absolute beginner to programming and Python. I have Python 2.6.5 > and 3.2 running on Mac OS 10.6.8 Snow Leopard. I have self-help books but > the problem I am having is not described in any of them. The answer may be > too obvious though. I am using IDLE: I figured that I could call Idle by > typing its name on the Terminal instead of launching it from the > Applications ?WOW! big step ;)) When I save a script as (.py) document, I > do not know how to 'run' it since the IDLE (2.6 or 3.2) menus do not have > RUN option (as they describe in the books I have). I understand that I may > have to type a command to run the script on the Terminal but I could not > find a specific command. It also seemed strange to me that there was not a > shortcut in Mac OS to run scripts unlike Windows. > > Thank you for your time and help, > > -- > B?LENT > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111212/c0d85f7e/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Mon, 12 Dec 2011 06:26:28 +0000 > From: David Smith > To: tutor at python.org > Subject: Re: [Tutor] Running a script! > Message-ID: <6F440ED4-BC58-4310-B0C4-61DC48379A62 at gmail.com> > Content-Type: text/plain; charset=windows-1252 > > > If I have understood you correctly you are looking at the Python Shell. > > On this window choose File then New Window this will open a script window > albeit without any code. This window will have a Run menu and within this > menu there is a Run Module item which is what I think you are looking for. > I hope this helps. > > Dax > > On 12 Dec 2011, at 06:00, Bulent Arikan wrote: > > > Dear List, > > > > I am an absolute beginner to programming and Python. I have Python 2.6.5 > and 3.2 running on Mac OS 10.6.8 Snow Leopard. I have self-help books but > the problem I am having is not described in any of them. The answer may be > too obvious though. I am using IDLE: I figured that I could call Idle by > typing its name on the Terminal instead of launching it from the > Applications ?WOW! big step ;)) When I save a script as (.py) document, I > do not know how to 'run' it since the IDLE (2.6 or 3.2) menus do not have > RUN option (as they describe in the books I have). I understand that I may > have to type a command to run the script on the Terminal but I could not > find a specific command. It also seemed strange to me that there was not a > shortcut in Mac OS to run scripts unlike Windows. > > > > Thank you for your time and help, > > > > -- > > B?LENT > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------ > > Message: 3 > Date: Sun, 11 Dec 2011 22:54:50 -0800 > From: wesley chun > To: surya k > Cc: Python Tutor > Subject: Re: [Tutor] best book for OOP > Message-ID: > > > Content-Type: text/plain; charset=ISO-8859-1 > > what do you think you are missing? is there something in the book that > you don't/can't understand? those of us on the list may be able to > help you out... sometimes humans are better at explaining things than > just books. :-) > > best regards, > --wesley > > > > On Sun, Dec 11, 2011 at 6:49 AM, surya k wrote: > > > > I'm reading "Core Python Programming" - Chun.. > > Currently, I am studying OOP in it.. and I feel there is something I am > missing in that while studying. Actually I am from C.. so, no idea of OOP. > > Could you tell me the best, simple, easy to understand book!! > > > -- > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Python Web Development with Django", Addison Wesley, (c) 2009 > ? ? http://withdjango.com > > wesley.chun : wescpy-gmail.com : @wescpy/+wescpy > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > > > ------------------------------ > > Message: 4 > Date: Mon, 12 Dec 2011 07:57:16 +0000 > From: David Smith > To: tutor at python.org > Subject: [Tutor] Visual and audible system bell > Message-ID: > Content-Type: text/plain; charset=us-ascii > > Dear list > > In a terminal window > > python3.2 > > at the command gives me > > Python 3.2 (r32:88452, Feb 20 2011, 11:12:31) > [GCC 4.2.1 (Apple Inc. build 5664)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> > > then > > >>>> print ("\a") > > triggers a visual and audible bell as set in Terminal window preferences. > > However > > >>>> print ("\a") > > and pressing Enter in a Python Shell window > > or including > > print ("\a") > input ("\n\nPress the enter key to exit.") > > results in neither a visible nor an audible system bell. > > Any suggestions? > > Mac OS X 10.7.2 > Terminal 2.2.1(299) > Python 3.2 > Tk 8.5 > > Dax > > > > > > ------------------------------ > > Message: 5 > Date: Mon, 12 Dec 2011 08:18:51 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Visual and audible system bell > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 12/12/11 07:57, David Smith wrote: > > > In a terminal window > >>>>> print ("\a") > > > > triggers a visual and audible bell as set in Terminal window preferences. > > > > However > > > >>>>> print ("\a") > > and pressing Enter in a Python Shell window > > results in neither a visible nor an audible system bell. > > I assume the second case means an IDLE window? > If so then its not surprising because IDLE does not use the Terminal > settings. It is its own Terminal. And IDLE intercepts many of the > standard control keys etc. In general this is a good thing since IDLE is > trying to make debugging and testing code as easy as possible so it > prevents premature exit from IDLE. But occasionally it stops things > happening the way you want. In this case no bell. (It is worth perusing > the IDLE config settings, it may be possible to change this, but I > suspect its more deeply embedded in the code than that) > > The only way round it is probably to just test your code by running it > in a Terminal and just use IDLE for editing and debugging. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Message: 6 > Date: Mon, 12 Dec 2011 14:16:08 +0530 > From: Sarma Tangirala > To: Alan Gauld > Cc: tutor at python.org > Subject: Re: [Tutor] best book for OOP > Message-ID: > > > Content-Type: text/plain; charset="iso-8859-1" > > > Object Oriented Analysis and Design with Applications > > by Grady Booch (1st edition) > > Classic text on OO Design with code and case studies realized in 5 > different OOP languages (Smalltalk, Object Pascal, C++, Lisp, ADA) > > Explains why OOP is important and how to ise it effectively. Also > introsduces Booch's OOD notation which was paret of the core that evolved > into UML. > > > > +1 > Used this book in an OOAD course and was very good. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20111212/eac5f1e9/attachment-0001.html > > > > ------------------------------ > > Message: 7 > Date: Mon, 12 Dec 2011 11:56:36 +0100 > From: Hugo Arts > To: shawn taylor > Cc: *tutor python > Subject: Re: [Tutor] (no subject) > Message-ID: > > > Content-Type: text/plain; charset=UTF-8 > > On Mon, Dec 12, 2011 at 3:56 AM, shawn taylor wrote: > > firstname = raw_input ("Enter your first name ") > > lastname = raw_input ("Enter your last name ") > > idnumber = raw_input ("Enter your id number ") > > birthday = raw_input ("Enter your birthday mm/dd/yyyy ") > > username1 = firstname[0] + lastname[0] + idnumber > > > > print ("Your username is ") + username1 > > > > midltr = firstname[len(firstname) / 2] > > midltrlastnm = lastname[len(lastname)??/ 2] > > > > on = int (birthday[0]) > > tw = int (birthday[1]) > > th = int (birthday[3]) > > fr = int (birthday[4]) > > fv = int (birthday[6]) > > sx = int (birthday[7]) > > sv = int (birthday[8]) > > eg = int (birthday[9]) > > > > num = str (on + tw + th + fr + fv + sx + sv + et) > > > > while num > 10: > > > > > > print num > > > > I'm trying to add all the digits in the birthday and keep adding till i > get > > a single digit and I'm stuck > > anything would help thanks > > alright, well, you've got all the basic ideas that you need in there, > it's just a matter of combining them in the right way. The basic > component is the while loop you have, you want to keep adding the > digits while there's more than two of them: > > while num > 10: > #add digits > > there is a slight error in there (what happens if the number comes out > to exactly ten? is that what should happen?), but I'll leave it in for > you to find. Another problem is that the while loop wants to check the > num variable, but it doesn't actually exist until the bottom of the > loop. What we do have at the top of the loop is the birthday variable, > but that has some pesky '/' characters in there that we don't really > want. I suggest the first thing you do is remove those slashes. (hint: > the str class has a replace() method. Google it and see if you can > figure out how to use it for this purpose). > > no_slashes_birthday = # use replace here in someway on the birthday? > num = int(no_slashes_birthday) > while num > 10: > #add digits > > that's enough for basic setup of the while loop. Now, to add the > digits. First thing we'll need to do is separate our number out into > digits. There's a nifty trick with the division and modulo operators > that can get us individual digits[1], but I don't want to convolute > the essence of this example with math. So here's a simpler way: leave > your number as a string! As you've already figured out, it's easy to > get characters in a string, and you can convert them to integers > individually again. > > Ok, so we don't do num = int(no_slashes_birthday), but just num = > no_slashes_birthday. Now we can get at the digits. All we need to do > now is convert them all into integers and add them together inside the > loop, and the loop will repeat it as necessary. The general structure > is "for every digit in num, convert digit to integer and add digit to > total." If you learn to state problems in this way, the necessary code > should flow out from it almost automatically. We can already see that > we'll need a for loop here, and a variable called total with a > sensible starting value[2]. See if you can figure it out. > > We're almost done here. at the end of the loop we've got a variable > called total, with our added digits. But the point of a loop is to run > multiple times, and our loop wants to have this total in a variable > called num, and it wants it to be a string so we can get at the > individual digits again. So we want to take the integer from total, > convert it back to a string, and put it in the num variable, right at > the end of the loop. That way it can run over and over until we have > only one digit left: > > no_slashes_birthday = # use replace here in someway on the birthday? > num = no_slashes_birthday > while num > 10: > # for every digit, convert digit to int and add to total > # convert total back to string and put it in num for the next iteration > > if you fill in the blanks you'll be almost done. There is one problem > though, and it's in the condition of the while loop. The statement > "while num > 10" makes no sense at all, because num, despite its name, > is not a number but a string. Now *we* know that there are characters > representing a number inside the string, but the computer doesn't care > which characters represent a number and it shouldn't, because you've > chosen to store it as a string. So for all it cares you might as well > be asking if "hello" > 10, which very obviously doesn't make sense. > See if you can find a way around this (hint: the requirement was "keep > going while we have more than 1 digit." strings can't be compared to > numbers, but they do have a length). > > And with that, you should be able to get it working. Good luck, and if > you have any trouble come back here. > > Hugo > > P.S.: I wrote this as soon as I woke up. Hopefully this reaches you in > time for you finals, though I fear the worst. In any case, (stating > the obvious) it might be a good idea to start studying a little > earlier next time ;) Programming isn't learned in a day. > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 94, Issue 44 > ************************************* > -- B?LENT ARIKAN, PhD Senior Research Fellow Research Center for Anatolian Civilizations Ko? University ?stiklal Caddesi No: 181 Merkez Han Beyo?lu - ISTANBUL TURKEY 34433 (+ 90) 212-393-6036 -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Mon Dec 12 12:42:03 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 12 Dec 2011 12:42:03 +0100 Subject: [Tutor] Running a script! Message-ID: On 12 December 2011 11:59, Bulent Arikan wrote: > Thank you Dax! That was it! Now I can run the script. > > Cheers, > Bulent You don't have to submit the entire digest when you're replying; trim it down to what you're actually replying to. Also, please avoid posting your reply on top -- it makes it difficult to find (and to keep track of who says what when). -- best regards, Robert S. From james.homme at highmark.com Mon Dec 12 13:08:52 2011 From: james.homme at highmark.com (Homme, James) Date: Mon, 12 Dec 2011 12:08:52 +0000 Subject: [Tutor] Need Explanation... In-Reply-To: References: Message-ID: Hi, Alan said: Because app() returns the result of append(). But append() returns None, since it modifies the list in place. This is one of the few features of Python I dislike. It would not have been difficult to make these modifier methods return the thing modified. This style would then allow chained methods. We do it with strings: "foobar is a string".rstrip('ing').upper() because strings are immutable. But we could have done it with other sequence types too. Sadly we didn't and history/tradition leaves us with these counterintuitive modifiers that return None. It catches everybody out at some point... Is that the same problem with using the len function on sequences and open on files, or is it different? Thanks. Jim -----Original Message----- From: tutor-bounces+james.homme=highmark.com at python.org [mailto:tutor-bounces+james.homme=highmark.com at python.org] On Behalf Of Alan Gauld Sent: Saturday, December 10, 2011 4:16 AM To: tutor at python.org Subject: Re: [Tutor] Need Explanation... On 10/12/11 07:41, sunil tech wrote: > /def app(x):/ > / return x.append(100)/ > / > /p = app(a)/ > / > /now list holds appended value [1,2,3,100]/ > /but p is empty... why it is?/ Because app() returns the result of append(). But append() returns None, since it modifies the list in place. This is one of the few features of Python I dislike. It would not have been difficult to make these modifier methods return the thing modified. This style would then allow chained methods. We do it with strings: "foobar is a string".rstrip('ing').upper() because strings are immutable. But we could have done it with other sequence types too. Sadly we didn't and history/tradition leaves us with these counterintuitive modifiers that return None. It catches everybody out at some point... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ________________________________ This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. From eire1130 at gmail.com Mon Dec 12 13:40:26 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 12 Dec 2011 07:40:26 -0500 Subject: [Tutor] Need Explanation... In-Reply-To: References: Message-ID: <4298C478-936C-4B1B-9841-EE18AC5625B1@gmail.com> Sent from my iPad On Dec 12, 2011, at 7:08 AM, "Homme, James" wrote: > Hi, > Alan said: > Because app() returns the result of append(). > But append() returns None, since it modifies the list in place. > > This is one of the few features of Python I dislike. It would not have been difficult to make these modifier methods return the thing modified. > This style would then allow chained methods. > > We do it with strings: > > "foobar is a string".rstrip('ing').upper() > > because strings are immutable. But we could have done it with other sequence types too. Sadly we didn't and history/tradition leaves us with these counterintuitive modifiers that return None. It catches everybody out at some point... > > > Is that the same problem with using the len function on sequences and open on files, or is it different? > > Thanks. > > Jim But a python list is mutable. I'm hardly an expert, but the idea is you are modifying the list. Why would you create another copy of the same list via a return statement? At it's fundamentals python is really an object oriented language. When you use append, extend, pop, sort, etc on the list you retain the object but change some of the attributes stored in the object. Your string example isn't analogous because they are, as you noted, immutable. I don't see this as a weakness but a strength. It cuts back on confusion and extraneous variables. Your example of Len also doesn't apply. It isn't modifying anything. It's returning the length of the list, in this case. You change nothing. Open, if I recall, creates a file object in the same way class A: a = A() creates an instance of A. But like I said I'm not an expert. > -----Original Message----- > From: tutor-bounces+james.homme=highmark.com at python.org [mailto:tutor-bounces+james.homme=highmark.com at python.org] On Behalf Of Alan Gauld > Sent: Saturday, December 10, 2011 4:16 AM > To: tutor at python.org > Subject: Re: [Tutor] Need Explanation... > > On 10/12/11 07:41, sunil tech wrote: > >> /def app(x):/ >> / return x.append(100)/ >> / >> /p = app(a)/ >> / >> /now list holds appended value [1,2,3,100]/ >> /but p is empty... why it is?/ > > Because app() returns the result of append(). > But append() returns None, since it modifies the list in place. > > This is one of the few features of Python I dislike. It would not have > been difficult to make these modifier methods return the thing modified. > This style would then allow chained methods. > > We do it with strings: > > "foobar is a string".rstrip('ing').upper() > > because strings are immutable. But we could have done it with other > sequence types too. Sadly we didn't and history/tradition leaves us with > these counterintuitive modifiers that return None. It catches everybody > out at some point... > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ________________________________ > > This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kabakve_13 at hotmail.com Mon Dec 12 13:40:30 2011 From: kabakve_13 at hotmail.com (John De) Date: Mon, 12 Dec 2011 14:40:30 +0200 Subject: [Tutor] Remove python modules Message-ID: Hi, I want to build python-2.7.2 and omit some modules that I don't need in order to create a smaller Python interpreter. Am I able to do this? Any recommendations? Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From cranky.frankie at gmail.com Mon Dec 12 15:01:28 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Mon, 12 Dec 2011 09:01:28 -0500 Subject: [Tutor] pygame blinking text Message-ID: My Python presentation is just about complete. As a nice ending I want to do a pygame program that displays the group's .jpg, with the words "Thank You!" blinking, say on for a second and off for a second. Unfortunatley, I can't get the works to blink, but I can get them to appear for a short time: from livewires import games, color games.init(screen_width = 640, screen_height = 480, fps = 50) bg_image = games.load_image("AEMUG640x480.JPG", transparent = False) games.screen.background = bg_image ty_message = games.Message(value = "Thank You!", size = 100, color = color.red, x = games.screen.width/2, y = games.screen.height/2, lifetime = 100, after_death = 0) games.screen.add(ty_message) games.screen.mainloop() I tried putting the ty_message block in a WHILE TRUE loop, and that didn't work. Then I tried the same with the games.screen.add(ty_message) line and that didn't work either. I think what might work is if I can find a way to delete the ty_message and readd it, over and over in a loop with a delay, bu: games.screen.delete(ty_message) doesn't work - delete is not a valid method. Is there any way to get blinking text with pygame? This is not a deal breaker, but I thought the blinking text would be neat. -- Frank L. "Cranky Frankie" Palmeri From ramit.prasad at jpmorgan.com Mon Dec 12 16:19:11 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 12 Dec 2011 15:19:11 +0000 Subject: [Tutor] return, why do I need it? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740729CF@SCACMX008.exchad.jpmchase.net> >No one has mentioned it so far, but the interactive interpreter is what you should use for debugging short code snippets. I always program with two windows open - one with my editor and one with the interpreter. This lets me try out short bits of code without running my whole program. +1 Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Mon Dec 12 18:43:39 2011 From: timomlists at gmail.com (Timo) Date: Mon, 12 Dec 2011 18:43:39 +0100 Subject: [Tutor] pygame blinking text In-Reply-To: References: Message-ID: <4EE63D4B.3040109@gmail.com> Op 12-12-11 15:01, Cranky Frankie schreef: > My Python presentation is just about complete. As a nice ending I want > to do a pygame program that displays the group's .jpg, with the words > "Thank You!" blinking, say on for a second and off for a second. > Unfortunatley, I can't get the works to blink, but I can get them to > appear for a short time: > > from livewires import games, color Looks like you're not using pygame, but livewires. Why not try their mailinglist, I bet their knowledge is better than this *Python beginners* list. Cheers, Timo > > games.init(screen_width = 640, screen_height = 480, fps = 50) > > bg_image = games.load_image("AEMUG640x480.JPG", transparent = False) > games.screen.background = bg_image > > > ty_message = games.Message(value = "Thank You!", > size = 100, > color = color.red, > x = games.screen.width/2, > y = games.screen.height/2, > lifetime = 100, > after_death = 0) > > games.screen.add(ty_message) > > games.screen.mainloop() > > > > I tried putting the ty_message block in a WHILE TRUE loop, and that > didn't work. Then I tried the same with the > games.screen.add(ty_message) line and that didn't work either. I think > what might work is if I can find a way to delete the ty_message and > readd it, over and over in a loop with a delay, bu: > > games.screen.delete(ty_message) > > doesn't work - delete is not a valid method. > > Is there any way to get blinking text with pygame? This is not a deal > breaker, but I thought the blinking text would be neat. > From rail.shafigulin at gmail.com Mon Dec 12 20:46:40 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Mon, 12 Dec 2011 14:46:40 -0500 Subject: [Tutor] timedelta, difference calculation Message-ID: i found something interesting during the timedate difference calculation import datetime import time def main(): mydatetime = datetime.datetime.now() time.sleep(1) mydatetime2 = datetime.datetime.now() diff = mydatetime - mydatetime2 print(diff) if __name__ == '__main__': main() if you run this code the result you get will be -1 day, 23:59:59 at least that is what i'm getting. i was expecting to get -1 second. diff object is of type timedelta. this kind of objects represent duration, at least that is what i understood from the documentation ( http://docs.python.org/release/3.1.3/library/datetime.html#timedelta-objects). so, is this a bug in the timedelta implementation or is it me not understanding documentation properly? any help is appreciated. ps. i'm using python 3.1 on a windows xp machine. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Dec 12 20:57:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Dec 2011 19:57:44 +0000 Subject: [Tutor] Need Explanation... In-Reply-To: <4298C478-936C-4B1B-9841-EE18AC5625B1@gmail.com> References: <4298C478-936C-4B1B-9841-EE18AC5625B1@gmail.com> Message-ID: James H wrote: >> Is that the same problem with using the len function on sequences > and open on files, or is it different? I don't think so. I'm not sure which problem you are referring to with these? Neither return None... > But a python list is mutable. I'm hardly an expert, but the idea is > you are modifying the list. Why would you create another copy of > the same list via a return statement? You wouldn't you'd return the same, now-modified, object. James R wrote: > I don't see this as a weakness but a strength. > It cuts back on confusion and extraneous variables. It creates confusion too. Look at how many posts we get because people try to do things like: mylist = mylist.sort() Actually it can introduce extraneous variables because you need a temp to hold the modified list while you perform the extra operations. With method chaining you do it all on one line. Now the good news is that in Python you can use one variable to hold both the intermediate list and the final result, so its not often a new variable just a double use of a single one. I suspect the value of this is only apparent if you have used Smalltalk :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From james.homme at highmark.com Mon Dec 12 21:33:01 2011 From: james.homme at highmark.com (Homme, James) Date: Mon, 12 Dec 2011 20:33:01 +0000 Subject: [Tutor] Need Explanation... In-Reply-To: References: <4298C478-936C-4B1B-9841-EE18AC5625B1@gmail.com> Message-ID: Hi Alan, I'm sorry. I'm coming pretty much from Cobol and freaking out about OO, so my questions may not be coming from a familiar place. I think I was referring partly to the idea that, for example, len and open are built in functions, whereas append is part of a list. I just am now to the place in Python where I understand some things about making classes and using them, but not a lot more. If I'm unintentionally implying anything else, I'm unaware of what it might be. I've used classes on purpose when I was working with LotusScript in my Lotus Notes development work, and I know that I have used them in other programming areas, but I've only recently purposely begun to get over the hump of learning to make them and really try to understand how they work. My programming knowledge is all over the place, since I have no formal computer science training. Thanks for your patience. Jim -----Original Message----- From: tutor-bounces+james.homme=highmark.com at python.org [mailto:tutor-bounces+james.homme=highmark.com at python.org] On Behalf Of Alan Gauld Sent: Monday, December 12, 2011 2:58 PM To: tutor at python.org Subject: Re: [Tutor] Need Explanation... James H wrote: >> Is that the same problem with using the len function on sequences > and open on files, or is it different? I don't think so. I'm not sure which problem you are referring to with these? Neither return None... > But a python list is mutable. I'm hardly an expert, but the idea is > you are modifying the list. Why would you create another copy of > the same list via a return statement? You wouldn't you'd return the same, now-modified, object. James R wrote: > I don't see this as a weakness but a strength. > It cuts back on confusion and extraneous variables. It creates confusion too. Look at how many posts we get because people try to do things like: mylist = mylist.sort() Actually it can introduce extraneous variables because you need a temp to hold the modified list while you perform the extra operations. With method chaining you do it all on one line. Now the good news is that in Python you can use one variable to hold both the intermediate list and the final result, so its not often a new variable just a double use of a single one. I suspect the value of this is only apparent if you have used Smalltalk :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ________________________________ This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. From steve at pearwood.info Mon Dec 12 21:39:57 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 13 Dec 2011 07:39:57 +1100 Subject: [Tutor] pygame blinking text In-Reply-To: References: Message-ID: <4EE6669D.2090802@pearwood.info> Cranky Frankie wrote: [...] > Is there any way to get blinking text with pygame? This is not a deal > breaker, but I thought the blinking text would be neat. To punish your users for completing the game? Ha ha only serious. -- Steven From lie.1296 at gmail.com Mon Dec 12 22:14:28 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 13 Dec 2011 08:14:28 +1100 Subject: [Tutor] timedelta, difference calculation In-Reply-To: References: Message-ID: On 12/13/2011 06:46 AM, rail shafigulin wrote: > i found something interesting during the timedate difference calculation > > import datetime > import time > > def main(): > mydatetime = datetime.datetime.now() > time.sleep(1) > mydatetime2 = datetime.datetime.now() > diff = mydatetime - mydatetime2 > > print(diff) > > if __name__ == '__main__': > main() > > if you run this code the result you get will be > -1 day, 23:59:59 > > at least that is what i'm getting. > > i was expecting to get -1 second. diff object is of type timedelta. this > kind of objects represent duration, at least that is what i understood > from the documentation > (http://docs.python.org/release/3.1.3/library/datetime.html#timedelta-objects). > so, is this a bug in the timedelta implementation or is it me not > understanding documentation properly? It's due to timedelta normalization; in timedelta object only the day part is ever negative, you never had negative hour, minute, or second. The `-1 day, 23:59:59` means to subtract 1 day, then add 23:59:59; therefore giving us -1 second. It is documented behavior, although perhaps hinted too subtly, from the docs: """ Note that normalization of negative values may be surprising at first. For example, >>> from datetime import timedelta >>> d = timedelta(microseconds=-1) >>> (d.days, d.seconds, d.microseconds) (-1, 86399, 999999) """ From lie.1296 at gmail.com Mon Dec 12 22:45:06 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 13 Dec 2011 08:45:06 +1100 Subject: [Tutor] pygame blinking text In-Reply-To: References: Message-ID: On 12/13/2011 01:01 AM, Cranky Frankie wrote: > I tried putting the ty_message block in a WHILE TRUE loop, and that > didn't work. Then I tried the same with the > games.screen.add(ty_message) line and that didn't work either. I think > what might work is if I can find a way to delete the ty_message and > readd it, over and over in a loop with a delay, bu: This is a common problem when people start GUI/graphics programming; once you enter the GUI mainloop, you're no longer in control of the program flow. Instead the mainloop will process events and callbacks; therefore if you want a blinking text, you had to arrange such that your blinker function will be called every second. In pygame, you can do the following: #!/usr/bin/env python import pygame # initialize pygame, this must be called before # doing anything with pygame pygame.init() # create a screen screen = pygame.display.set_mode((400, 400)) # setup the text font = pygame.font.Font(None, 36) text = font.render("Hello World", True, (100, 100, 100)) display = True # the main loop while pygame.time.get_ticks() < 10000: # run the program for 10 seconds # empty the screen screen.fill((255, 255, 255)) display = not display # draw the text to the screen only if display is True if display: screen.blit(text, (100, 100)) # update the actual screen pygame.display.flip() # wait for half second pygame.time.wait(500) You can do this in pygame since pygame do not provide a mainloop. I took a quick glance at livewires, their main loop implementation is very simple; however it discards all events except for mouse, keyboard, and the quit event. In typical game engine, you usually will register an event to the event handler to be executed every second that will draw/undraw the text. However, in livewires event handling system you can't do that. Therefore, if you want to do it, you'd have to override the event handling method in the Screen class. However, for a quick hack, I think you can abuse the after_death= parameter; you can register a function that will games.screen.add() a Message, then after_death, it registers an invisible message which registers a Message after its death which registers the visible message after death which ... . In short, the following (I haven't tested it, although I think it should work): stop = False def add_visible_ty(): if stop: return message = games.Message( value = "Thank You!", size = 100, color = color.red, x = games.screen.width/2, y = games.screen.height/2, lifetime = 500, after_death = add_invisible_ty ) games.screen.add(message) def add_invisible_ty(): if stop: return message = games.Message( value = "", size = 100, color = color.red, x = games.screen.width/2, y = games.screen.height/2, lifetime = 500, after_death = add_visible_ty ) games.screen.add(message) > games.screen.delete(ty_message) > > doesn't work - delete is not a valid method. There are two rendering style for graphics programming; one is called the "retained mode", in which the libraries retain a complete model of the objects to be rendered and graphic calls do not directly cause actual rendering but instead update an internal model, the other is the "immediate mode" in which graphic calls directly cause rendering of graphics objects to the display. pygame falls into the latter; pygame do not keep track of objects that it has drawn on screen, therefore if you need to "delete" an object from the screen, you'd need to redraw the whole screen except the object you had deleted. At the very least, you'd need to redraw the part of the screen that had changed due to the deletion. livewires falls into the former; in livewires there is an internal object that represent each screen object and it keep tracks of which objects and which part of the screen that are "dirty". From ramit.prasad at jpmorgan.com Mon Dec 12 23:14:23 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 12 Dec 2011 22:14:23 +0000 Subject: [Tutor] pygame blinking text In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4740737D8@SCACMX008.exchad.jpmchase.net> >This is a common problem when people start GUI/graphics programming; >once you enter the GUI mainloop, you're no longer in control of the >program flow. Instead the mainloop will process events and callbacks; >therefore if you want a blinking text, you had to arrange such that your >blinker function will be called every second. Since you are using livewires, you can subclass games.Timer and then create an instance of that subclass at the end and then have the tick function check for some Boolean value and either hide or show the text. I am not familiar with livewires or pygame, so I hope that helps. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From timomlists at gmail.com Tue Dec 13 12:10:46 2011 From: timomlists at gmail.com (Timo) Date: Tue, 13 Dec 2011 12:10:46 +0100 Subject: [Tutor] timedelta, difference calculation In-Reply-To: References: Message-ID: <4EE732B6.5060003@gmail.com> Op 12-12-11 20:46, rail shafigulin schreef: > i found something interesting during the timedate difference calculation > > import datetime > import time > > def main(): > mydatetime = datetime.datetime.now() > time.sleep(1) > mydatetime2 = datetime.datetime.now() > diff = mydatetime - mydatetime2 Lie Ryan explains how to read the output below, but you made a little error here. Let's have a little example: >>> x1 = 1 >>> x2 = x1 + 1 >>> print(x1 - x2) -1 >>> print(x2 - x1) 1 So you should substract mydatetime from mydatetime2, not the other way around. Cheers, Timo > > print(diff) > > if __name__ == '__main__': > main() > > if you run this code the result you get will be > -1 day, 23:59:59 > > at least that is what i'm getting. > > i was expecting to get -1 second. diff object is of type timedelta. > this kind of objects represent duration, at least that is what i > understood from the documentation > (http://docs.python.org/release/3.1.3/library/datetime.html#timedelta-objects). > so, is this a bug in the timedelta implementation or is it me not > understanding documentation properly? > > any help is appreciated. > > ps. i'm using python 3.1 on a windows xp machine. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kaixiluo at gmail.com Tue Dec 13 21:39:08 2011 From: kaixiluo at gmail.com (Kaixi Luo) Date: Tue, 13 Dec 2011 21:39:08 +0100 Subject: [Tutor] A shorter way to initialize a list? Message-ID: Hello, I want to create a list of lists of lists (listB) from a list of lists (listA). Below there's a snippet of my code: list1 = [[] for i in range(9)] # some code here... listA = [[] for i in range(3)] count = 0 for i in range(3): for j in range(3): listB[i].append(listA[count]) count+=1 My question is: is there any alternative way I can initialize listB without resorting to using 2 loops? I'm learning Python coming from a C++ background. So far, I've found that Python is an amazingly concise and expressive language. I just want to make sure I'm not being badly influenced by my old C++ habits. Cheers, Kaixi -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Dec 13 22:09:34 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 13 Dec 2011 13:09:34 -0800 Subject: [Tutor] A shorter way to initialize a list? In-Reply-To: References: Message-ID: On 12/13/2011 12:39 PM Kaixi Luo said... > Hello, > > I want to create a list of lists of lists (listB) from a list of lists > (listA). Below there's a snippet of my code: > > list1 = [[] for i in range(9)] Should this be listB? > > # some code here... > > listA = [[] for i in range(3)] > count = 0 > for i in range(3): > for j in range(3): > listB[i].append(listA[count]) ... if not, where's this come from? Emile > count+=1 > > My question is: is there any alternative way I can initialize listB > without resorting to using 2 loops? > > I'm learning Python coming from a C++ background. So far, I've found > that Python is an amazingly concise and expressive language. I just want > to make sure I'm not being badly influenced by my old C++ habits. > > Cheers, > > Kaixi > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From ramit.prasad at jpmorgan.com Wed Dec 14 00:07:08 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 13 Dec 2011 23:07:08 +0000 Subject: [Tutor] A shorter way to initialize a list? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474074CE1@SCACMX008.exchad.jpmchase.net> From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Kaixi Luo Sent: Tuesday, December 13, 2011 2:39 PM To: tutor at python.org Subject: [Tutor] A shorter way to initialize a list? Hello, I want to create a list of lists of lists (listB) from a list of lists (listA). Below there's a snippet of my code: list1 = [[] for i in range(9)] # some code here... listA = [[] for i in range(3)] count = 0 for i in range(3): ??? for j in range(3): ??????? listB[i].append(listA[count]) ??????? count+=1 My question is: is there any alternative way I can initialize listB without resorting to using 2 loops? ======================================== I do not understand the double loop. listA is only of length 3, so it will fail as soon as count=3 (when i=1,j=0). listA only has 3 sublists and listB has 9. I am not sure how you are trying to append them and frankly I can guess half a dozen various reasons that seem equally plausible to me. If they are both supposed to be the same size then you should check copy.deepcopy which will make new objects (versus just references) for every sublist (or any object for that matter ) in the original list. Otherwise you will need to be aware that appending a sublist from listA to listB will mean that if you modify a sublist in listA it will modify the corresponding sublist of listB and vice-versa. If you clarified what you are trying to do (or better yet gave sample results), I could help you better. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Wed Dec 14 00:25:04 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 14 Dec 2011 10:25:04 +1100 Subject: [Tutor] A shorter way to initialize a list? In-Reply-To: References: Message-ID: <4EE7DED0.9050907@pearwood.info> Kaixi Luo wrote: > Hello, > > I want to create a list of lists of lists (listB) from a list of lists > (listA). Below there's a snippet of my code: > > list1 = [[] for i in range(9)] > > # some code here... > > listA = [[] for i in range(3)] > count = 0 > for i in range(3): > for j in range(3): > listB[i].append(listA[count]) > count+=1 I'm afraid that I don't know what you are trying to do here, because your snippet doesn't work. So I have to *guess* what you're actually trying to do. My guess is that you have a list of lists, and you want to copy it. Here's one way, using a slice over the entire list. >>> listA = [[1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5]] >>> listB = listA[:] # like listA[0:5] listA and listB are now independent lists, but the sublists are shared: >>> listA.append(None) # modify listA, and listB is unchanged >>> listB [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] >>> listA[0].append(None) # but modify a shared sublist >>> listB # and listB sees the same change [[1, None], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] If that's not the behaviour you want, you need to make copies of the inner lists too: >>> listA = [[1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5]] >>> listB = [inner[:] for inner in listA] >>> >>> listA.append(None) >>> listA[0].append(None) >>> listB [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] That's easy enough when listA is a nested list of lists one level deep, but if it contains a mix of lists and scalars, or multiple levels, you should use the copy module to do the copying: import copy listB = copy.deepcopy(listA) How do you create a two-dimensional array? The basic technique is with a nested list comprehension: >>> [[2**j for j in range(4)] for i in range(i)] [[1, 2, 4, 8], [1, 2, 4, 8], [1, 2, 4, 8], [1, 2, 4, 8], [1, 2, 4, 8]] This is equivalent to: listA = [] for i in range(5): listB = [] for j in range(4): listB.append(2**j) listA.append(listB) only slightly shorter :) If all you need is a two-dimension array of numbers 0...n, use the range() built-in to generate the inner lists: >>> [list(range(4)) for i in range(5)] [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] The call to list() is needed in Python 3, where range() returns a lazy iterator; in Python 2, it returns a list and you don't need to call list() (but it doesn't hurt if you do). -- Steven From kaixiluo at gmail.com Wed Dec 14 00:26:02 2011 From: kaixiluo at gmail.com (Kaixi Luo) Date: Wed, 14 Dec 2011 00:26:02 +0100 Subject: [Tutor] A shorter way to initialize a list? In-Reply-To: References: Message-ID: On Tue, Dec 13, 2011 at 10:09 PM, Emile van Sebille wrote: > On 12/13/2011 12:39 PM Kaixi Luo said... > > Hello, >> >> I want to create a list of lists of lists (listB) from a list of lists >> (listA). Below there's a snippet of my code: >> >> list1 = [[] for i in range(9)] >> > > Should this be listB? > > > >> # some code here... >> >> listA = [[] for i in range(3)] >> count = 0 >> for i in range(3): >> for j in range(3): >> listB[i].append(listA[count]) >> > > ... if not, where's this come from? > > Emile > > > count+=1 >> >> My question is: is there any alternative way I can initialize listB >> without resorting to using 2 loops? >> >> I'm learning Python coming from a C++ background. So far, I've found >> that Python is an amazingly concise and expressive language. I just want >> to make sure I'm not being badly influenced by my old C++ habits. >> >> Cheers, >> >> Kaixi >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Uh, sorry. I made some very bad typos there. It should be: listA = [[] for i in range(9)] # some code here... listB = [[] for i in range(3)] count = 0 for i in range(3): for j in range(3): listB[i].append(listA[count]) count+=1 Kaixi -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Wed Dec 14 00:28:54 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Tue, 13 Dec 2011 23:28:54 +0000 Subject: [Tutor] Fwd: A shorter way to initialize a list? In-Reply-To: References: Message-ID: Forgot to reply all... ---------- Forwarded message ---------- From: Rich Lovely Date: 13 December 2011 23:17 Subject: Re: [Tutor] A shorter way to initialize a list? To: Kaixi Luo On 13 December 2011 20:39, Kaixi Luo wrote: > Hello, > > I want to create a list of lists of lists (listB) from a list of lists > (listA). Below there's a snippet of my code: > > list1 = [[] for i in range(9)] > > # some code here... > > listA = [[] for i in range(3)] > count = 0 > for i in range(3): > ??? for j in range(3): > ??????? listB[i].append(listA[count]) > ??????? count+=1 > > My question is: is there any alternative way I can initialize listB without > resorting to using 2 loops? > > I'm learning Python coming from a C++ background. So far, I've found that > Python is an amazingly concise and expressive language. I just want to make > sure I'm not being badly influenced by my old C++ habits. > > Cheers, > > Kaixi > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I think it should read: listA = [[] for i in range(9)] # some code here... listB = [[] for i in range(3)] count = 0 for i in range(3): ? ?for j in range(3): ? ? ? ?listB[i].append(listA[count]) ? ? ? ?count+=1 So, you're partitioning list A into three, so [1,2,3,4,5,6,7,8,9] becomes [[1,2,3],[4,5,6].[7,8,9]] The easy way to do that is with slice notation; >>> lst = [1,2,3,4,5,6,7,8,9] >>> lst[0:3] listB=[[] for i in range(3)] for i, lst in enumerate(listB): ? ?startIndex = i*3 ? ?lst.extend(listA[startIndex:startIndex+3]) This uses extend, which is the equivalent of your inner loop, and also uses a more "pythonic" style; iterating over the list itself, or, if you need numbers, an enumeration of the list, which returns a list (or an iterable in python3) of (index, item) tuples. There might be another way using fancy iterators, but that's something for a latter email. -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T.? Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 By the way, the fancy iterator method is; from itertools import izip it = iter(listA) listB = [[] for i in range(3)] for b, i in izip(listB, izip(it, it, it)): b.extend(i) (Sorry, I enjoy this sort of thing a little too much.) -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T.? Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 From emile at fenx.com Wed Dec 14 01:05:25 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 13 Dec 2011 16:05:25 -0800 Subject: [Tutor] A shorter way to initialize a list? In-Reply-To: References: Message-ID: On 12/13/2011 3:26 PM Kaixi Luo said... > Uh, sorry. I made some very bad typos there. It should be: > > listA = [[] for i in range(9)] > > # some code here... > > listB = [[] for i in range(3)] > count = 0 > for i in range(3): > for j in range(3): > listB[i].append(listA[count]) > count+=1 > This yields listB as [[[], [], []], [[], [], []], [[], [], []]] So, the trick will be that each list element be unique. If you're not careful, you'll get the same list elements. For example, listB = [[[]]*3]*3 appears to yield the same result until you append to one of the elements and discover one of the common early gotcha's: >>> listB[1][1].append(1) >>> print listB [[[1], [1], [1]], [[1], [1], [1]], [[1], [1], [1]]] To avoid this, each list container needs to be added separately, which means that the two loops will be required. You can express it as a single statement using list comprehensions: >>> listB = [ [ [] for ii in range(3) ] for jj in range(3) ] >>> listB [[[], [], []], [[], [], []], [[], [], []]] >>> listB[1][1].append(1) >>> listB [[[], [], []], [[], [1], []], [[], [], []]] HTH, Emile From alan.gauld at btinternet.com Wed Dec 14 01:28:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Dec 2011 00:28:57 +0000 Subject: [Tutor] A shorter way to initialize a list? In-Reply-To: References: Message-ID: On 13/12/11 20:39, Kaixi Luo wrote: > I want to create a list of lists of lists (listB) from a list of lists > (listA). Below there's a snippet of my code: > > listA = [[] for i in range(9)] > listB = [[] for i in range(3)] So list A containds 9 empty lists And list B contains 3 empty lists > count = 0 > for i in range(3): > for j in range(3): > listB[i].append(listA[count]) > count+=1 And you want to add the 9 empty lists in A to the 3 empty lists in B to get a structure like: listB = [ [ [],[],[] ], [ [],[],[] ], [ [],[],[] ] ] Is that it? And in more general terms you want to create a list of len(B) sublists each of which holds len(A)/len(B) elements from A? lets call the sizes La and Lb Result = [ {...} for n in range(0,La,Lb)] where {...} = listA[n:n+Lb] So for your example: >>> A = [ [n] for n in range(9) ] >>> A [[0], [1], [2], [3], [4], [5], [6], [7], [8]] >>> B = [ A[n:n+3] for n in range(0,9,3) ] >>> B [ [[0], [1], [2]], [[3], [4], [5]], [[6], [7], [8]]] The numbers just to help see which list goes where... Now I could have miusunderstood. Is that what you want? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From suryak at live.com Wed Dec 14 15:13:34 2011 From: suryak at live.com (surya k) Date: Wed, 14 Dec 2011 19:43:34 +0530 Subject: [Tutor] where I am going wrong? Message-ID: This is a project Euler puzzle.?http://projecteuler.net/problem=30 I applied brute force way and here is my code k=0for p in range(1,10):? ? for q in range(0,10):? ? ? ? for r in range(0,10):? ? ? ? ? ? for s in range(0,10):? ? ? ? ? ? ? ? for t in range(0,10):? ? ? ? ? ? ? ? ?n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1)? ? ? ? ? ? ? ? ?if n == \? ? ? ? ? ? ? ? ? ? ?p**5 + q**5 + r**5 + s**5 + t**5:? ? ? ? ? ? ? ? ? ? ? ? print n? ? ? ? ? ? ? ? ? ? ? ? k+=nprint k My answer:?240559 But its showing the answer as wrong!!. I used the same method on the example puzzle and it worked. From waynejwerner at gmail.com Wed Dec 14 15:25:53 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 14 Dec 2011 08:25:53 -0600 Subject: [Tutor] where I am going wrong? In-Reply-To: References: Message-ID: On Wed, Dec 14, 2011 at 8:13 AM, surya k wrote: > > This is a project Euler puzzle. http://projecteuler.net/problem=30 > I applied brute force way and here is my code > k=0for p in range(1,10): for q in range(0,10): for r in > range(0,10): for s in range(0,10): for t in > range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) + > (t*1) if n == \ p**5 + q**5 + r**5 + > s**5 + t**5: print n > k+=nprint k > My answer: 240559 > But its showing the answer as wrong!!. > I used the same method on the example puzzle and it worked. Your email client broke the formatting - you should probably use plain-text or a pastebin. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From suryak at live.com Wed Dec 14 15:29:24 2011 From: suryak at live.com (surya k) Date: Wed, 14 Dec 2011 19:59:24 +0530 Subject: [Tutor] where I am going wrong? In-Reply-To: References: , Message-ID: ________________________________ > From: waynejwerner at gmail.com > Date: Wed, 14 Dec 2011 08:25:53 -0600 > Subject: Re: [Tutor] where I am going wrong? > To: suryak at live.com > CC: tutor at python.org > > On Wed, Dec 14, 2011 at 8:13 AM, surya k > > wrote: > > This is a project Euler > puzzle. http://projecteuler.net/problem=30 > I applied brute force way and here is my code > k=0for p in range(1,10): for q in range(0,10): for r in > range(0,10): for s in range(0,10): for t in > range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) > + (t*1) if n == \ p**5 + q**5 + > r**5 + s**5 + t**5: print n > k+=nprint k > My answer: 240559 > But its showing the answer as wrong!!. > I used the same method on the example puzzle and it worked. > > Your email client broke the formatting - you should probably use > plain-text or a pastebin. > > -Wayne This is a project Euler puzzle.?http://projecteuler.net/problem=30 I applied brute force way and here is my codek=0for p in range(1,10):? ??? ? for q in range(0,10):? ? ? ??? ? ? ? ? for r in range(0,10):? ? ? ? ? ??? ? ? ? ? ? ? ? ?for s in range(0,10):? ? ? ? ? ? ? ??? ? ? ? ? ? ? ? ? ? ? ? ?for t in range(0,10):? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?if n == p**5 + q**5 + r**5 + s**5 + t**5: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?k+=nprint kMy answer:?240559But its showing the answer as wrong!!. I used the same method on the example puzzle and it worked.? From __peter__ at web.de Wed Dec 14 16:03:02 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 14 Dec 2011 16:03:02 +0100 Subject: [Tutor] where I am going wrong? References: Message-ID: surya k wrote: > This is a project Euler puzzle. http://projecteuler.net/problem=30 > I applied brute force way and here is my codek=0for p in range(1,10): > for q in range(0,10): for r in range(0,10): > for s in range(0,10): > for t in range(0,10): > n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) > if n == p**5 + q**5 + r**5 + s**5 + t**5: > k+=nprint kMy answer: Suraya, you did it again. Your python code is formatted into a complete mess. If you don't follow Wayne's advice and post readable plaintext you'll consume a lot of goodwill quickly. > 240559But its showing the answer as wrong!!. I used the same method on the > example puzzle and it worked. Hint: you assume that all partial results have 5 digits, but they may have fewer or more. For example you are missing >>> 4**5+1**5+5**5+0**5 4150 From suryak at live.com Wed Dec 14 16:32:55 2011 From: suryak at live.com (surya k) Date: Wed, 14 Dec 2011 21:02:55 +0530 Subject: [Tutor] where I am going wrong? In-Reply-To: References: , , Message-ID: ---------------------------------------- > From: suryak at live.com > To: waynejwerner at gmail.com > CC: tutor at python.org > Subject: RE: [Tutor] where I am going wrong? > Date: Wed, 14 Dec 2011 19:59:24 +0530 > > > > > ________________________________ > > From: waynejwerner at gmail.com > > Date: Wed, 14 Dec 2011 08:25:53 -0600 > > Subject: Re: [Tutor] where I am going wrong? > > To: suryak at live.com > > CC: tutor at python.org > > > > On Wed, Dec 14, 2011 at 8:13 AM, surya k > > > wrote: > > > > This is a project Euler > > puzzle. http://projecteuler.net/problem=30 > > I applied brute force way and here is my code > > k=0for p in range(1,10): for q in range(0,10): for r in > > range(0,10): for s in range(0,10): for t in > > range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) > > + (t*1) if n == \ p**5 + q**5 + > > r**5 + s**5 + t**5: print n > > k+=nprint k > > My answer: 240559 > > But its showing the answer as wrong!!. > > I used the same method on the example puzzle and it worked. > > > > Your email client broke the formatting - you should probably use > > plain-text or a pastebin. > > > > -Wayne This is a project Euler puzzle. http://projecteuler.net/problem=30I applied brute force way and here is my codek=0for p in range(1,10): for q in range(0,10): for r in range(0,10): for s in range(0,10): for t in range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) if n == p**5 + q**5 + r**5 + s**5 + t**5: k+=n print kMy answer: 240559But its showing the answer as wrong!!.I used the same method on the example puzzle and it worked. -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Dec 14 16:39:53 2011 From: d at davea.name (Dave Angel) Date: Wed, 14 Dec 2011 10:39:53 -0500 Subject: [Tutor] where I am going wrong? In-Reply-To: References: , Message-ID: <4EE8C349.8060004@davea.name> On 12/14/2011 09:29 AM, surya k wrote: > > > ________________________________ >> From: waynejwerner at gmail.com >> Date: Wed, 14 Dec 2011 08:25:53 -0600 >> Subject: Re: [Tutor] where I am going wrong? >> To: suryak at live.com >> CC: tutor at python.org >> >> On Wed, Dec 14, 2011 at 8:13 AM, surya k >> > wrote: >> >> This is a project Euler >> puzzle. http://projecteuler.net/problem=30 >> I applied brute force way and here is my code >> k=0for p in range(1,10): for q in range(0,10): for r in >> range(0,10): for s in range(0,10): for t in >> range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) >> + (t*1) if n == \ p**5 + q**5 + >> r**5 + s**5 + t**5: print n >> k+=nprint k >> My answer: 240559 >> But its showing the answer as wrong!!. >> I used the same method on the example puzzle and it worked. >> >> Your email client broke the formatting - you should probably use >> plain-text or a pastebin. >> >> -Wayne > This is a project Euler puzzle. http://projecteuler.net/problem=30 > I applied brute force way and here is my codek=0for p in range(1,10): for q in range(0,10): for r in range(0,10): for s in range(0,10): for t in range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) if n == p**5 + q**5 + r**5 + s**5 + t**5: k+=nprint kMy answer: 240559But its showing the answer as wrong!!. > I used the same method on the example puzzle and it worked. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The new copy you posted was just as bad. Please tell your email program not to reformat your text. With Thunderbird, I do that by telling it to use plain-text format for any message that goes to the domain: python.org. It's under File->preferences->Composition->General->Send Options. First section "Convert the message to plain text" and second section, under PlainTextDomain, add python.org I tried to reflow the source. But 59 columns of indentation is pretty wild. So I also changed indentation, and maybe got it right. Your code assumes all the numbers it will find will be 5 digit numbers, which is a strange assumption. When I try it with **4, I get zero as the result. All the numbers for that case happen to be exactly 4 digits, while you have 5 nested loops. There's no reason to presuppose the number of digits. I therefore changed the p range to 0,10, and the if statement to exclude the solution for 0 and 1. I also added a global called exp, so we can run it unchanged on either 4 or 5. exp = 4 k=0 for p in range(0,10): for q in range(0,10): for r in range(0,10): for s in range(0,10): for t in range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) if n == p**exp + q**exp + r**exp + s**exp + t**exp and p>1: k+=n print "one part", n print k This still doesn't get the right answer, because it misses at least one number that has more than 5 digits. If you just want to get on with it, you could nest several more for-loops. But you can readily put a coarse upper limit on the largest match, by trying something like 10* 9**5. See how big that is, and if it's less than 10 digits long, you have an upper limit. Now you know how many loops you need. There are other approaches that don't require you to make a large number of nested loops. One is to use recursion. Another is to just iterate through the integers (n), then use str() and list() to turn it into a bunch of digits, which you then raise to the appropriate power in a simple loop. -- DaveA From james.homme at highmark.com Wed Dec 14 16:48:29 2011 From: james.homme at highmark.com (Homme, James) Date: Wed, 14 Dec 2011 15:48:29 +0000 Subject: [Tutor] Tuple: Am I Understanding This Correctly? Message-ID: Hi, My learning style likes a lot of words in plain English. Here is some code. Am I explaining how this works correctly? # Make a tuple to simplify putting in the prompts below. # This makes it so that you don't have to type out the whole thing every time you want to use these strings. # The variables were defined above. finish = (user_name, prompt) likes = raw_input("Do you like me %s?\n%s" % finish) # Use the tuple repeatedly when asking other questions. Thanks. Jim Jim Homme, Usability Services, Phone: 412-544-1810. ________________________________ This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Wed Dec 14 16:51:51 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Wed, 14 Dec 2011 16:51:51 +0100 Subject: [Tutor] where I am going wrong? In-Reply-To: References: Message-ID: surya k wrote: > This is a project Euler puzzle. http://projecteuler.net/problem=30 > I applied brute force way and here is my codek=0for p in range(1,10): for q in range(0,10): for r in range(0,10): for s in range(0,10): for t in range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) if n == p**5 + q**5 + r**5 + s**5 + t**5: k+=nprint kMy answer: 240559But its showing the answer as wrong!!. > I used the same method on the example puzzle and it worked. Your formatting is still broken, here's how I suspect you want it to look: k=0 for p in range(1,10): for q in range(0,10): for r in range(0,10): for s in range(0,10): for t in range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) + t if n == p**5 + q**5 + r**5 + s**5 + t**5: #print(n) k += n print(k) What Peter said is very important too. I very much doubt you'll find the solution with those loops. -- best regards, Robert S. From suryak at live.com Wed Dec 14 17:52:09 2011 From: suryak at live.com (surya k) Date: Wed, 14 Dec 2011 22:22:09 +0530 Subject: [Tutor] where I am going wrong? In-Reply-To: <4EE8C349.8060004@davea.name> References: , , <4EE8C349.8060004@davea.name> Message-ID: > Date: Wed, 14 Dec 2011 10:39:53 -0500 > From: d at davea.name > To: suryak at live.com > CC: waynejwerner at gmail.com; tutor at python.org > Subject: Re: [Tutor] where I am going wrong? > > On 12/14/2011 09:29 AM, surya k wrote: > > > > > > ________________________________ > >> From: waynejwerner at gmail.com > >> Date: Wed, 14 Dec 2011 08:25:53 -0600 > >> Subject: Re: [Tutor] where I am going wrong? > >> To: suryak at live.com > >> CC: tutor at python.org > >> > >> On Wed, Dec 14, 2011 at 8:13 AM, surya k > >> > wrote: > >> > >> This is a project Euler > >> puzzle. http://projecteuler.net/problem=30 > >> I applied brute force way and here is my code > >> k=0for p in range(1,10): for q in range(0,10): for r in > >> range(0,10): for s in range(0,10): for t in > >> range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) > >> + (t*1) if n == \ p**5 + q**5 + > >> r**5 + s**5 + t**5: print n > >> k+=nprint k > >> My answer: 240559 > >> But its showing the answer as wrong!!. > >> I used the same method on the example puzzle and it worked. > >> > >> Your email client broke the formatting - you should probably use > >> plain-text or a pastebin. > >> > >> -Wayne > > This is a project Euler puzzle. http://projecteuler.net/problem=30 > > I applied brute force way and here is my codek=0for p in range(1,10): for q in range(0,10): for r in range(0,10): for s in range(0,10): for t in range(0,10): n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) if n == p**5 + q**5 + r**5 + s**5 + t**5: k+=nprint kMy answer: 240559But its showing the answer as wrong!!. > > I used the same method on the example puzzle and it worked. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > The new copy you posted was just as bad. Please tell your email program > not to reformat your text. With Thunderbird, I do that by telling it > to use plain-text format for any message that goes to the domain: > python.org. It's under File->preferences->Composition->General->Send > Options. First section "Convert the message to plain text" and second > section, under PlainTextDomain, add python.org > > I tried to reflow the source. But 59 columns of indentation is pretty > wild. So I also changed indentation, and maybe got it right. > > Your code assumes all the numbers it will find will be 5 digit numbers, which is a strange assumption. When I try it with **4, I get zero as the result. All the numbers for that case happen to be exactly 4 digits, while you have 5 nested loops. There's no reason to presuppose the number of digits. > I therefore changed the p range to 0,10, and the if statement to exclude the solution for 0 and 1. > I also added a global called exp, so we can run it unchanged on either 4 or 5. > > > > exp = 4 > k=0 > for p in range(0,10): > for q in range(0,10): > for r in range(0,10): > for s in range(0,10): > for t in range(0,10): > n = (p*10000)+ (q*1000) + (r*100) + (s*10) + (t*1) > if n == p**exp + q**exp + r**exp + s**exp + t**exp and p>1: > k+=n > print "one part", n > print k > > This still doesn't get the right answer, because it misses at least one > number that has more than 5 digits. > > If you just want to get on with it, you could nest several more > for-loops. But you can readily put a coarse upper limit on the largest > match, by trying something like 10* 9**5. See how big that is, and if > it's less than 10 digits long, you have an upper limit. Now you know how > many loops you need. > > There are other approaches that don't require you to make a large number > of nested loops. One is to use recursion. Another is to just iterate > through the integers (n), then use str() and list() to turn it into a > bunch of digits, which you then raise to the appropriate power in a > simple loop. > > > -- > > DaveA > Thanks Dave for putting that much effort.Actually, I was using "plane text" format.. I wonder what went wrong! So, regarding the program, you assumed it correctly. Let me do it again as you said.. I'll let you know if there is any problem Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Dec 14 19:25:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Dec 2011 18:25:33 +0000 Subject: [Tutor] Tuple: Am I Understanding This Correctly? In-Reply-To: References: Message-ID: On 14/12/11 15:48, Homme, James wrote: > Am I explaining how this works correctly? You are not really explaining *how* it works, just saying what it does. What you are doing is sensible iff you have many places where the tuple is useful. In the specific case I'd personally just create the tuple at the point of use: > finish = (user_name, prompt) > likes = raw_input("Do you like me %s?\n%s" % finish) likes = raw_input("Do you like me %s?\n%s" % (user_name, prompt)) Since it saves the reader referring back to the definition of finish (which is an odd nanme for user/prompt data IMHO). > # Use the tuple repeatedly when asking other questions. But, if you are using the tuple repeatedly then it starts to make sense. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Gokul.Santhirakumaran at christiedigital.com Wed Dec 14 22:15:38 2011 From: Gokul.Santhirakumaran at christiedigital.com (Santhirakumaran, Gokul) Date: Wed, 14 Dec 2011 21:15:38 +0000 Subject: [Tutor] ctype exceptions.ValueError for function call Message-ID: <52784758373D504EB891CD133621A25B0AA51582@cktexmb01.cds.int> Hi, I'm trying to use a SDK(dll file) with python ctypes to take measurement from a spectrometer. I some how got the deceive connected and took the measurement , but when I try to call one of its calculation function I'm getting the "exceptions.ValueError: Procedure probably called with not enough arguments (8 bytes missing)" error. I believe I have called the function with proper arguments and data types. I would really appreciate some help. The Function: mydll = ctypes.windll.LoadLibrary("D:\\WILD2\\tools\\WildVerification\\lib\\jeti_core.dll") device = ctypes.c_int() dvError = mydll.JETI_OpenDevice(0,ctypes.byref(device)) X_value = ctypes.c_float() Y_value = ctypes.c_float() Z_value = ctypes.c_float() dvError = mydll.JETI_CalcXYZ(device,ctypes.byref(X_value),ctypes.byref(Y_value),ctypes.byref(Z_value)) Function Documentation: 3.112 JETI_CalcXYZ This function returns the calculated tristimulus XYZ. 3.112.1 Prototype DWORD JETI_CalcXYZ (DWORD dwDevice, FLOAT *fX, FLOAT *fY, FLOAT *fZ) 3.112.2 Parameters Input Name Type Description Call dwDevice DWORD Handle to a device as By value returned by JETI_OpenDevice fX FLOAT* pointer to a variable By reference where the tristimulus X will be stored fY FLOAT * pointer to a variable By reference where the tristimulus Y will be stored fZ FLOAT * pointer to a variable By reference where the tristimulus Z will be stored - Gokul Santhirakumaran Electrical Engineer(Co-op) CHRISTIE 809 Wellington St. N. Kitchener, ON, Canada N2G 4Y7 PH: +1 519-744-8005 x7313 www.christiedigital.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From beetlebane at gmail.com Wed Dec 14 23:41:24 2011 From: beetlebane at gmail.com (rog capp) Date: Wed, 14 Dec 2011 17:41:24 -0500 Subject: [Tutor] while loops Message-ID: # Guess my number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is to high, to low # or right on the money import random print("\tWelcome to 'Guess My Number'!") print("I'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") # set the initial values the_number = random.randint(1,100) guess = int(input("Take a guess: ")) tries = 1 # Guessing loop while guess != the_number: if guess > the_number: print("Lowere...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 print("good job") input("\n\nPress the enter key to exit.") This is a program from "Python for the absulute beginner(which I am). End of the chapter is a challenge that asks me to limit the number of guesses the player gets. If he/she fails to guess the number after a certain number of attempts then it displays a message about his failure.It needs to be a while loop cause it the topic I'm at.Can anyone give me some help on where to put the loop.When i put it in with the "if guess>the_number" loop, the program either prints higher or lower continuously(continuous loop I imagine) or it gives me the answer whether its right or wrong after a couple guesses.Any help will be appreciated. From steve at pearwood.info Wed Dec 14 23:55:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 15 Dec 2011 09:55:43 +1100 Subject: [Tutor] while loops In-Reply-To: References: Message-ID: <4EE9296F.80304@pearwood.info> rog capp wrote: [...] > # Guessing loop > while guess != the_number: > if guess > the_number: > print("Lowere...") > else: > print("Higher...") > guess = int(input("Take a guess: ")) > tries += 1 > > print("good job") > input("\n\nPress the enter key to exit.") > > > > This is a program from "Python for the absulute beginner(which I am). > End of the chapter is a challenge that asks me to limit the number of > guesses the player gets. > If he/she fails to guess the number after a certain number of attempts > then it displays a message > about his failure.It needs to be a while loop cause it the topic I'm > at.Can anyone give me some help You need a counter to count how many guesses are made. You already have a variable counting the number of tries, so you are half-way there. The loop condition currently is: while guess != the_number or in English: "while the guess is not equal to the number: loop" Still in English, you want to change the condition to: "while the guess is not equal to the number and the number of tries is less than the maximum number of tries: loop" Translate that loop condition from English to Python, and you've got it. Then, once you have the loop fixed, the final change needed is to change the message printed at the end, outside the loop. Currently it unconditionally prints "good job". You need to change that to only print "good job" if the guess is equal to the number, otherwise print something else. -- Steven From d at davea.name Thu Dec 15 00:03:51 2011 From: d at davea.name (Dave Angel) Date: Wed, 14 Dec 2011 18:03:51 -0500 Subject: [Tutor] while loops In-Reply-To: References: Message-ID: <4EE92B57.5000601@davea.name> On 12/14/2011 05:41 PM, rog capp wrote: > # Guess my number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know if the guess is to high, to low > # or right on the money > > import random > > print("\tWelcome to 'Guess My Number'!") > print("I'm thinking of a number between 1 and 100.") > print("Try to guess it in as few attempts as possible.\n") > > # set the initial values > the_number = random.randint(1,100) > guess = int(input("Take a guess: ")) > tries = 1 > > # Guessing loop > while guess != the_number: > > if guess> the_number: > print("Lowere...") > else: > print("Higher...") > > guess = int(input("Take a guess: ")) > tries += 1 > > print("good job") > > input("\n\nPress the enter key to exit.") > > > > This is a program from "Python for the absulute beginner(which I am). > End of the chapter is a challenge that asks me to limit the number of > guesses the player gets. > If he/she fails to guess the number after a certain number of attempts > then it displays a message > about his failure.It needs to be a while loop cause it the topic I'm > at.Can anyone give me some help > on where to put the loop.When i put it in with the "if > guess>the_number" loop, the program either > prints higher or lower continuously(continuous loop I imagine) or it > gives me the answer whether its > right or wrong after a couple guesses.Any help will be appreciated. > _ You already have a while-loop. So add another condition to it: while guess != answer and tries< 10: then outside the loop, write an if-test conditional on whether guess == number If so, tell him good job, if not, tell him he took too many tries. -- DaveA From alan.gauld at btinternet.com Thu Dec 15 00:07:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Dec 2011 23:07:43 +0000 Subject: [Tutor] while loops In-Reply-To: References: Message-ID: On 14/12/11 22:41, rog capp wrote: > # Guessing loop > while guess != the_number: > > if guess> the_number: > else: > > guess = int(input("Take a guess: ")) > tries += 1 > > If he/she fails to guess the number after a certain number of attempts > then it displays a message about his failure.It needs to be a while > loop cause it the topic I'm at. > Can anyone give me some help on where to put the loop. You already have one. Look at the code above, see the while? You do not need another one. And you are already counting how many times round the loop you go. So all you need to do is use that counter to stop the while loop when it reaches a given value. Currently the loop stops when guess == the_number You would like it to also stop when your counter reaches the limit. Do you know how to do that? Have a go and tell us how you get on. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Dec 15 00:11:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Dec 2011 23:11:31 +0000 Subject: [Tutor] ctype exceptions.ValueError for function call In-Reply-To: <52784758373D504EB891CD133621A25B0AA51582@cktexmb01.cds.int> References: <52784758373D504EB891CD133621A25B0AA51582@cktexmb01.cds.int> Message-ID: On 14/12/11 21:15, Santhirakumaran, Gokul wrote: > Hi, > > I?m trying to use a SDK(dll file) with python ctypes to take measurement > from a spectrometer. This list is for people learning the Python language. ctypes is a little advanced for most readers. You are more likely to get help on the ctypes mailing list. ctypes-users at lists.sourceforge.net https://lists.sourceforge.net/lists/listinfo/ctypes-users Or On the gmane news server under: gmane.comp.python.ctypes But you might get lucky and somebody here knows enough ctypes to answer you.... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Wed Dec 14 23:48:11 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 14 Dec 2011 22:48:11 +0000 Subject: [Tutor] while loops In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474075F71@SCACMX008.exchad.jpmchase.net> -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of rog capp Sent: Wednesday, December 14, 2011 4:41 PM To: tutor at python.org Subject: [Tutor] while loops # Guess my number # # The computer picks a random number between 1 and 100 # The player tries to guess it and the computer lets # the player know if the guess is to high, to low # or right on the money import random print("\tWelcome to 'Guess My Number'!") print("I'm thinking of a number between 1 and 100.") print("Try to guess it in as few attempts as possible.\n") # set the initial values the_number = random.randint(1,100) guess = int(input("Take a guess: ")) tries = 1 # Guessing loop while guess != the_number: if guess > the_number: print("Lowere...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 print("good job") input("\n\nPress the enter key to exit.") This is a program from "Python for the absulute beginner(which I am). End of the chapter is a challenge that asks me to limit the number of guesses the player gets. If he/she fails to guess the number after a certain number of attempts then it displays a message about his failure.It needs to be a while loop cause it the topic I'm at.Can anyone give me some help on where to put the loop.When i put it in with the "if guess>the_number" loop, the program either prints higher or lower continuously(continuous loop I imagine) or it gives me the answer whether its right or wrong after a couple guesses.Any help will be appreciated. ============================================================= If you want to stop after a certain number of attempts, then your loop should compare the number of tries (you are storing this correctly) against the number of max allowed attempts (you are not storing this part so that needs to be done first). You can use the current loop, just change the conditions (this part is second)d. Hopefully that makes sense to you. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From baumgarten.sean at gmail.com Thu Dec 15 01:28:05 2011 From: baumgarten.sean at gmail.com (Sean Baumgarten) Date: Wed, 14 Dec 2011 16:28:05 -0800 Subject: [Tutor] Installing Python and modules Message-ID: Hello, I'm wondering if someone could walk me step-by-step through installing Python and some third-party modules. I've never used Python or other programming languages before, but I'm just trying to install it so I can run a simple script. I'm running Mac OSX 10.6.8. Here's the instructions in the ReadMe file for the script: "Developed for Python v2.6.6, you must have matplotlib, csv, and scipy modules downloaded. The complete python package (including all modules) are available through Enthought.com, which is free for academic institutions. Otherwise, downloading python and individual modules is free through sourceforge.net. If using version < 2.6.6, you may need to 'import math'. NOTE: If you download python and the modules separately (not as a package), it may be possible that you need the Numpy module instead of the csv module. There is no need to change the import statements in the script for either case." The thing that was causing me the most trouble was figuring out how to install the modules. For example, from what I read it sounded like in order to install the Numpy and Scipy modules I had to first install other modules or tools like distutil, virtualenv, and pip, but even after doing that I couldn't get Numpy and Scipy to install. I was also confused about whether I should use v.2.6.6 or whether I could/should use 2.7.2. Thanks, Sean -------------- next part -------------- An HTML attachment was scrubbed... URL: From beetlebane at gmail.com Thu Dec 15 03:15:15 2011 From: beetlebane at gmail.com (rog capp) Date: Wed, 14 Dec 2011 21:15:15 -0500 Subject: [Tutor] Tutor Digest, Vol 94, Issue 53 In-Reply-To: References: Message-ID: On Wed, Dec 14, 2011 at 6:03 PM, wrote: > Send Tutor mailing list submissions to > ? ? ? ?tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > ? ? ? ?http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > ? ? ? ?tutor-request at python.org > > You can reach the person managing the list at > ? ? ? ?tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > ? 1. Re: Tuple: Am I Understanding This Correctly? (Alan Gauld) > ? 2. ctype exceptions.ValueError for function call > ? ? ?(Santhirakumaran, Gokul) > ? 3. while loops (rog capp) > ? 4. Re: while loops (Steven D'Aprano) > ? 5. Re: while loops (Dave Angel) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 14 Dec 2011 18:25:33 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Tuple: Am I Understanding This Correctly? > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 14/12/11 15:48, Homme, James wrote: >> ?Am I explaining how this works correctly? > > You are not really explaining *how* it works, just saying what it does. > What you are doing is sensible iff you have many places where the tuple > is useful. In the specific case I'd personally just create the tuple at > the point of use: > >> finish = (user_name, prompt) >> likes = raw_input("Do you like me %s?\n%s" % finish) > > likes = raw_input("Do you like me %s?\n%s" % (user_name, prompt)) > > Since it saves the reader referring back to the definition > of finish (which is an odd nanme for user/prompt data IMHO). > >> # Use the tuple repeatedly when asking other questions. > > But, if you are using the tuple repeatedly then it starts > to make sense. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > ------------------------------ > > Message: 2 > Date: Wed, 14 Dec 2011 21:15:38 +0000 > From: "Santhirakumaran, Gokul" > ? ? ? ? > To: "'tutor at python.org'" > Subject: [Tutor] ctype exceptions.ValueError for function call > Message-ID: > ? ? ? ?<52784758373D504EB891CD133621A25B0AA51582 at cktexmb01.cds.int> > Content-Type: text/plain; charset="us-ascii" > > Hi, > > I'm trying to use a SDK(dll file) with python ctypes to take measurement from a spectrometer. I some how got the deceive connected and took the measurement , but when I try to call one of its calculation function I'm getting ?the "exceptions.ValueError: Procedure probably called with not enough arguments (8 bytes missing)" error. > > I believe I have called the function with proper arguments and data types. I would really appreciate some help. > > The Function: > > mydll = ctypes.windll.LoadLibrary("D:\\WILD2\\tools\\WildVerification\\lib\\jeti_core.dll") > device = ctypes.c_int() > dvError = mydll.JETI_OpenDevice(0,ctypes.byref(device)) > > X_value = ctypes.c_float() > Y_value = ctypes.c_float() > Z_value = ctypes.c_float() > > dvError = mydll.JETI_CalcXYZ(device,ctypes.byref(X_value),ctypes.byref(Y_value),ctypes.byref(Z_value)) > > Function Documentation: > > 3.112 JETI_CalcXYZ > This function returns the calculated tristimulus XYZ. > 3.112.1 Prototype > DWORD JETI_CalcXYZ (DWORD dwDevice, FLOAT *fX, FLOAT *fY, FLOAT *fZ) > 3.112.2 Parameters > Input > Name ? ? ? ? ? ? ? Type ? ? ? ? ? ? ? ? ? ? ? ? ? ? Description ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Call > dwDevice ? ? ? ? ?DWORD ? ? ? ? ? ? ? ? ? ? ? Handle to a device as ? ? ? ? ? ? ? ?By value > returned by > JETI_OpenDevice > > fX ? ? ? ? ? ? ? ? ? ? FLOAT* ? ? ? ? ? ? ? ? ? ? ? ? pointer to a variable ? ? ? ? ? ? ? ? ? By reference > where the tristimulus X > will be stored > > fY ? ? ? ? ? ? ? ? ? ? FLOAT * ? ? ? ? ? ? ? ? ? ? ? ?pointer to a variable ? ? ? ? ? ? ? ? ? By reference > where the tristimulus Y > will be stored > > fZ ? ? ? ? ? ? ? ? ? ? FLOAT * ? ? ? ? ? ? ? ? ? ? ? ?pointer to a variable ? ? ? ? ? ? ? ? ? By reference > where the tristimulus Z > will be stored > > - > Gokul Santhirakumaran > Electrical Engineer(Co-op) > > CHRISTIE > 809 Wellington St. N. > Kitchener, ON, Canada N2G 4Y7 > PH: +1 519-744-8005 x7313 > www.christiedigital.com > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 3 > Date: Wed, 14 Dec 2011 17:41:24 -0500 > From: rog capp > To: tutor at python.org > Subject: [Tutor] while loops > Message-ID: > ? ? ? ? > Content-Type: text/plain; charset=ISO-8859-1 > > # Guess my number > # > # The computer picks a random number between 1 and 100 > # The player tries to guess it and the computer lets > # the player know ?if the guess is to high, to low > # or right on the money > > import random > > print("\tWelcome to 'Guess My Number'!") > print("I'm thinking of a number between 1 and 100.") > print("Try to guess it in as few attempts as possible.\n") > > # set the initial values > the_number = random.randint(1,100) > guess = int(input("Take a guess: ")) > tries = 1 > > # Guessing loop > while ?guess != the_number: > > ? ?if guess > the_number: > ? ? ? ?print("Lowere...") > ? ?else: > ? ? ? ?print("Higher...") > > ? ?guess = int(input("Take a guess: ")) > ? ?tries += 1 > > print("good job") > > input("\n\nPress the enter key to exit.") > > > > This is a program from "Python for the absulute beginner(which I am). > End of the chapter is a challenge that asks me to limit the number of > guesses the player gets. > If he/she fails to guess the number after a certain number of attempts > then it displays a message > about his failure.It needs to be a while loop cause it the topic I'm > at.Can anyone give me some help > on where to put the loop.When i put it in with the "if > guess>the_number" loop, the program either > prints higher or lower continuously(continuous loop I imagine) or it > gives me the answer whether its > right or wrong after a couple guesses.Any help will be appreciated. > > > ------------------------------ > > Message: 4 > Date: Thu, 15 Dec 2011 09:55:43 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] while loops > Message-ID: <4EE9296F.80304 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > rog capp wrote: > [...] >> # Guessing loop >> while ?guess != the_number: >> ? ? if guess > the_number: >> ? ? ? ? print("Lowere...") >> ? ? else: >> ? ? ? ? print("Higher...") >> ? ? guess = int(input("Take a guess: ")) >> ? ? tries += 1 >> >> print("good job") >> input("\n\nPress the enter key to exit.") >> >> >> >> This is a program from "Python for the absulute beginner(which I am). >> End of the chapter is a challenge that asks me to limit the number of >> guesses the player gets. >> If he/she fails to guess the number after a certain number of attempts >> then it displays a message >> about his failure.It needs to be a while loop cause it the topic I'm >> at.Can anyone give me some help > > You need a counter to count how many guesses are made. You already have a > variable counting the number of tries, so you are half-way there. > > The loop condition currently is: > > ? ? while guess != the_number > > or in English: > > ? ? "while the guess is not equal to the number: loop" > > Still in English, you want to change the condition to: > > ? ? "while the guess is not equal to the number and the number of > ? ? ?tries is less than the maximum number of tries: loop" > > Translate that loop condition from English to Python, and you've got it. > > Then, once you have the loop fixed, the final change needed is to change the > message printed at the end, outside the loop. Currently it unconditionally > prints "good job". You need to change that to only print "good job" if the > guess is equal to the number, otherwise print something else. > > > > -- > Steven > > > ------------------------------ > > Message: 5 > Date: Wed, 14 Dec 2011 18:03:51 -0500 > From: Dave Angel > To: rog capp > Cc: tutor at python.org > Subject: Re: [Tutor] while loops > Message-ID: <4EE92B57.5000601 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 12/14/2011 05:41 PM, rog capp wrote: >> # Guess my number >> # >> # The computer picks a random number between 1 and 100 >> # The player tries to guess it and the computer lets >> # the player know ?if the guess is to high, to low >> # or right on the money >> >> import random >> >> print("\tWelcome to 'Guess My Number'!") >> print("I'm thinking of a number between 1 and 100.") >> print("Try to guess it in as few attempts as possible.\n") >> >> # set the initial values >> the_number = random.randint(1,100) >> guess = int(input("Take a guess: ")) >> tries = 1 >> >> # Guessing loop >> while ?guess != the_number: >> >> ? ? ?if guess> ?the_number: >> ? ? ? ? ?print("Lowere...") >> ? ? ?else: >> ? ? ? ? ?print("Higher...") >> >> ? ? ?guess = int(input("Take a guess: ")) >> ? ? ?tries += 1 >> >> print("good job") >> >> input("\n\nPress the enter key to exit.") >> >> >> >> This is a program from "Python for the absulute beginner(which I am). >> End of the chapter is a challenge that asks me to limit the number of >> guesses the player gets. >> If he/she fails to guess the number after a certain number of attempts >> then it displays a message >> about his failure.It needs to be a while loop cause it the topic I'm >> at.Can anyone give me some help >> on where to put the loop.When i put it in with the "if >> guess>the_number" loop, the program either >> prints higher or lower continuously(continuous loop I imagine) or it >> gives me the answer whether its >> right or wrong after a couple guesses.Any help will be appreciated. >> _ > You already have a while-loop. ?So add another condition to it: > ? ? ? ?while guess != answer ? and tries< 10: > > then outside the loop, write an if-test conditional on whether guess == > number > > If so, tell him good job, if not, tell him he took too many tries. > > -- > > DaveA > > > > ------------------------------ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 94, Issue 53 > ************************************* while guess != the_number and tries < 5: if guess > the_number: print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 if guess == the_number: print("good job the number was, " , the_number) print("it took you" , tries," tries.") else: print("Sorry you took to many tries") THANKS Steve and Dave got it working now. roGca From ramit.prasad at jpmorgan.com Thu Dec 15 07:39:26 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 15 Dec 2011 06:39:26 +0000 Subject: [Tutor] Tutor Digest, Vol 94, Issue 53 In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47407652C@SCACMX008.exchad.jpmchase.net> > > End of Tutor Digest, Vol 94, Issue 53 > ************************************* while guess != the_number and tries < 5: if guess > the_number: print("Lower...") else: print("Higher...") guess = int(input("Take a guess: ")) tries += 1 if guess == the_number: print("good job the number was, " , the_number) print("it took you" , tries," tries.") else: print("Sorry you took to many tries") THANKS Steve and Dave got it working now. roGca =================================================== Please reply and change the digest subject to the original subject or relevant subject if new. While you did an excellent job not top-posting it would also be good if you trimmed out the irrelevant sections from your reply. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Thu Dec 15 09:09:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Dec 2011 08:09:08 +0000 Subject: [Tutor] Tutor Digest, Vol 94, Issue 53 In-Reply-To: References: Message-ID: Please use a sensible subject line in future. Pleae trim any excess material from the post, specifically do NOT post the entire digest to the list. We've already seen it! On 15/12/11 02:15, rog capp wrote: > On Wed, Dec 14, 2011 at 6:03 PM, wrote: >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> http://mail.python.org/mailman/listinfo/tutor >> or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >> You can reach the person managing the list at >> tutor-owner at python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Thu Dec 15 09:43:34 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 15 Dec 2011 00:43:34 -0800 (PST) Subject: [Tutor] ctype exceptions.ValueError for function call In-Reply-To: References: <52784758373D504EB891CD133621A25B0AA51582@cktexmb01.cds.int> Message-ID: <1323938614.50261.YahooMailNeo@web110710.mail.gq1.yahoo.com> Hi, ? Nice! Did not know there was a ctypes mailing list. Another thing: I found (but did not yet test) this program:http://www.nirsoft.net/utils/dll_export_viewer.html The screenshot looks promising. At least one is able to tell which functions in a dll are exported (and can therefore be called using ctypes). Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ >________________________________ >From: Alan Gauld >To: tutor at python.org >Sent: Thursday, December 15, 2011 12:11 AM >Subject: Re: [Tutor] ctype exceptions.ValueError for function call > >On 14/12/11 21:15, Santhirakumaran, Gokul wrote: >> Hi, >> >> I?m trying to use a SDK(dll file) with python ctypes to take measurement >> from a spectrometer. > >This list is for people learning the Python language. >ctypes is a little advanced for most readers. You are >more likely to get help on the ctypes mailing list. > >ctypes-users at lists.sourceforge.net >https://lists.sourceforge.net/lists/listinfo/ctypes-users > >Or >On the gmane news server under: >gmane.comp.python.ctypes > >But you might get lucky and somebody here knows enough >ctypes to answer you.... > >-- >Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lina.lastname at gmail.com Thu Dec 15 17:52:46 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 16 Dec 2011 00:52:46 +0800 Subject: [Tutor] how to print the match middle part out Message-ID: Hi, For following: aaa model 0 bbb acb model 1 ccc How can I set regexp1 as "model 0" and end "model 1" so the final print out will be: model 0 bbb acb above is a very simple example, Thanks for any advice, Best, From rail.shafigulin at gmail.com Thu Dec 15 18:52:39 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Thu, 15 Dec 2011 12:52:39 -0500 Subject: [Tutor] timedelta, difference calculation In-Reply-To: References: Message-ID: On Mon, Dec 12, 2011 at 4:14 PM, Lie Ryan wrote: > On 12/13/2011 06:46 AM, rail shafigulin wrote: > >> i found something interesting during the timedate difference calculation >> >> import datetime >> import time >> >> def main(): >> mydatetime = datetime.datetime.now() >> time.sleep(1) >> mydatetime2 = datetime.datetime.now() >> diff = mydatetime - mydatetime2 >> >> print(diff) >> >> if __name__ == '__main__': >> main() >> >> if you run this code the result you get will be >> -1 day, 23:59:59 >> >> at least that is what i'm getting. >> >> i was expecting to get -1 second. diff object is of type timedelta. this >> kind of objects represent duration, at least that is what i understood >> from the documentation >> (http://docs.python.org/**release/3.1.3/library/** >> datetime.html#timedelta-**objects >> ). >> so, is this a bug in the timedelta implementation or is it me not >> understanding documentation properly? >> > > It's due to timedelta normalization; in timedelta object only the day part > is ever negative, you never had negative hour, minute, or second. The `-1 > day, 23:59:59` means to subtract 1 day, then add 23:59:59; therefore giving > us -1 second. > > It is documented behavior, although perhaps hinted too subtly, from the > docs: > > """ > Note that normalization of negative values may be surprising at first. For > example, > > >>> from datetime import timedelta > >>> d = timedelta(microseconds=-1) > >>> (d.days, d.seconds, d.microseconds) > (-1, 86399, 999999) > """ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Thanks. You are right about the "subtle" documentation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Thu Dec 15 18:57:29 2011 From: timomlists at gmail.com (Timo) Date: Thu, 15 Dec 2011 18:57:29 +0100 Subject: [Tutor] how to print the match middle part out In-Reply-To: References: Message-ID: <4EEA3509.6060708@gmail.com> Op 15-12-11 17:52, lina schreef: > Hi, > > For following: > > aaa > model 0 > bbb > acb > model 1 > ccc > > > How can I set regexp1 as "model 0" and end "model 1" > > so the final print out will be: > > model 0 > bbb > acb Just iterate over the lines (file or string) and retrieve the lines from the wanted line, until the line you're not interested in anymore. something like this: data = """aaa model 0 bbb acb model 1 ccc""" result = [] first_reached = False for line in data.split('\n'): if line == 'model 0': first_reached = True if line == 'model 1': break if first_reached: result.append(line) print result Cheers, Timo > > above is a very simple example, > > Thanks for any advice, > > Best, > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Thu Dec 15 19:04:01 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Dec 2011 05:04:01 +1100 Subject: [Tutor] how to print the match middle part out In-Reply-To: References: Message-ID: <4EEA3691.5060705@pearwood.info> lina wrote: > Hi, > > For following: > > aaa > model 0 > bbb > acb > model 1 > ccc > > > How can I set regexp1 as "model 0" and end "model 1" In English, we have a saying "When all you have is a hammer, everything looks like a nail". Don't make the mistake of thinking that regexes are your hammer. In my opinion, this example is best solved with a filter function, not a regex. Here is a simple example: def filter_lines(lines, start, end): lines = iter(lines) # Skip lines before matching start. for line in lines: if line == start: yield line break # Show lines after matching start, but before matching end. for line in lines: if line == end: break yield line text = """aaa model 0 bbb acb model 1 ccc """ And the output: py> for line in filter_lines(text.split('\n'), 'model 0', 'model 1'): ... print line ... model 0 bbb acb -- Steven From cranky.frankie at gmail.com Thu Dec 15 19:54:31 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Thu, 15 Dec 2011 13:54:31 -0500 Subject: [Tutor] pygame blinking text Message-ID: First of all let me thank Timo, Lie Ryan, and Ramit, for their constructive answers to my pygame/livewires blinking text question. I wasn't able to use any of their suggestions, but I finally figured out a method to get blinking text in a simple pygame program. What I realized was that since it let's you put a background image on the screen, then all I had to do was create another background image with the text I wanted to blink on it, then simply use an animation object to quickly cycle the images, and there you go, blinking text. I'm sure there's a way to do this that's better, but all I'm trying to do here is display a blinking "Thank You!" message at the end of my Python presentation, using this little trick as a way to show the beginnings of game programming. I'm not trying to write an actual game, just using this to show a little bit of pygame as an example of the different things you can do in Python. Here's what I wound up with: # thank_you.py # Demonstrates creating an animation from livewires import games games.init(screen_width = 640, screen_height = 480, fps = 50) screen_image = games.load_image("AEMUG640x480.JPG", transparent = 0) games.screen.background = screen_image screen_file = ["AEMUG640x480TY.JPG", "AEMUG640x480.JPG"] screen_refresh = games.Animation(images = screen_file, x = games.screen.width/2, y = games.screen.height/2, n_repeats = 0, repeat_interval = 50) games.screen.add(screen_refresh) games.screen.mainloop() -- Frank L. "Cranky Frankie" Palmeri From waitmeforever at hotmail.com Thu Dec 15 20:09:55 2011 From: waitmeforever at hotmail.com (Yang Chun-Kai) Date: Fri, 16 Dec 2011 03:09:55 +0800 Subject: [Tutor] Localhost client-server simple ssl socket test program problems Message-ID: Hello,everyone!! I am writing a simple ssl client-server test program on my personal laptop. And I encounter some problems with my simple programs. Please give me some helps.-------------------------------------------------------------------------------------------------------------------------------------------------------- My server code: import socketimport sslbindsocket = socket.socket()bindsocket.bind(('127.0.0.1', 1234))bindsocket.listen(5)print 'server is waiting for connection...'newsocket, fromaddr = bindsocket.accept()print 'start ssl socket...'connstream = ssl.wrap_socket(newsocket, server_side=True, certfile="/etc/home/ckyang/PHA/testsslsocket/mypha.crt", keyfile="/etc/home/ckyang/PHA/testsslsocket/mypha.key", ssl_version=ssl.PROTOCOL_SSLv23)data = connstream.read()print 'connected from address', fromaddrprint 'received data as', repr(data)connstream.close() My client code: import socketimport ssls = socket.socket(socket.AF_INET, socket.SOCK_STREAM)ssl_sock = ssl.wrap_socket(s, ca_certs="/home/ckyang/PHA/testsslsocket/myCA.crt", cert_reqs=ssl.CERT_REQUIRED)ssl_sock.connect(("127.0.0.1", 1234))ssl_sock.write("hello")ssl_sock.close() -----------------------------------------------------------------------------------------------------------------------------------------------------------Server side error: File "views.py", line 17, in connstream = ssl.wrap_socket(newsocket, server_side=True, certfile="/etc/home/ckyang/PHA/testsslsocket/mypha.crt", keyfile="/etc/home/ckyang/PHA/testsslsocket/mypha.key", ssl_version=ssl.PROTOCOL_SSLv23) File "/usr/lib/python2.7/ssl.py", line 344, in wrap_socket ciphers=ciphers) File "/usr/lib/python2.7/ssl.py", line 119, in __init__ ciphers)ssl.SSLError: [Errno 336265218] _ssl.c:347: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib Client side error: File "client.py", line 10, in ssl_sock.connect(("127.0.0.1", 1234)) File "/usr/lib/python2.7/ssl.py", line 299, in connect self.do_handshake() File "/usr/lib/python2.7/ssl.py", line 283, in do_handshake self._sslobj.do_handshake()socket.error: [Errno 104] Connection reset by peer ------------------------------------------------------------------------------------------------------------------------------------------------------------So what is wrong with my code? The codes are so simple and so much like python official site sample demonstration, but I still cant get it work, so frustrating. Seems the problem happened on server side then cause client side cant connect well, is that right? My platform is ubuntu, with openssl 0.9.8 and python 2.7. All certificates and keys self-signed by openssl for test convenience. This is the site for referrence : http://andyjeffries.co.uk/articles/x509-encrypted-authenticated-socket-ruby-client Or should I need a real certificate issued by a real CA to let things work? Any tips or suggestions welcomed, thank you very much~ Good day. Kay -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettnaxel at gmail.com Thu Dec 15 20:24:37 2011 From: rhettnaxel at gmail.com (Alexander) Date: Thu, 15 Dec 2011 14:24:37 -0500 Subject: [Tutor] Localhost client-server simple ssl socket test program problems In-Reply-To: References: Message-ID: 2011/12/15 Yang Chun-Kai > Hello,everyone!! > > I am writing a simple ssl client-server test program on my personal laptop. > > And I encounter some problems with my simple programs. > > Please give me some helps. > > -------------------------------------------------------------------------------------------------------------------------------------------------------- > > My server code: > > import socket > import ssl > bindsocket = socket.socket() > bindsocket.bind(('127.0.0.1', 1234)) > bindsocket.listen(5) > print 'server is waiting for connection...' > newsocket, fromaddr = bindsocket.accept() > print 'start ssl socket...' > connstream = ssl.wrap_socket(newsocket, server_side=True, > certfile="/etc/home/ckyang/PHA/testsslsocket/mypha.crt", > keyfile="/etc/home/ckyang/PHA/testsslsocket/mypha.key", > ssl_version=ssl.PROTOCOL_SSLv23) > data = connstream.read() > print 'connected from address', fromaddr > print 'received data as', repr(data) > connstream.close() > > My client code: > > import socket > import ssl > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > ssl_sock = ssl.wrap_socket(s, > ca_certs="/home/ckyang/PHA/testsslsocket/myCA.crt", > cert_reqs=ssl.CERT_REQUIRED) > ssl_sock.connect(("127.0.0.1", 1234)) > ssl_sock.write("hello") > ssl_sock.close() > > > ----------------------------------------------------------------------------------------------------------------------------------------------------------- > Server side error: > > File "views.py", line 17, in & lt;module> > connstream = ssl.wrap_socket(newsocket, server_side=True, > certfile="/etc/home/ckyang/PHA/testsslsocket/mypha.crt", > keyfile="/etc/home/ckyang/PHA/testsslsocket/mypha.key", > ssl_version=ssl.PROTOCOL_SSLv23) > File "/usr/lib/python2.7/ssl.py", line 344, in wrap_socket > ciphers=ciphers) > File "/usr/lib/python2.7/ssl.py", line 119, in __init__ > ciphers) > ssl.SSLError: [Errno 336265218] _ssl.c:347: error:140B0002:SSL > routines:SSL_CTX_use_PrivateKey_file:system lib > > Client side error: > > File "client.py", line 10, in > ssl_sock.connect(("127.0.0.1", 1234)) > File "/usr/lib/python2.7/ssl.py", line 299, in connect** > self.do_handshake() > File "/usr/lib/python2.7/ssl.py", line 283, in do_handshake > self._sslobj.do_handshake() > socket.error: [Errno 104] Connection reset by peer > > > ------------------------------------------------------------------------------------------------------------------------------------------------------------ > So what is wrong with my code? > > The codes are so simple and so much like python official site sample > demonstration, but I still cant get it work, so frustrating. > > Seems the problem happened on server side then cause client side cant > connect well, is that right? > > ** > My platform is ubuntu, with openssl 0.9.8 and python 2.7. > > All certificates and keys self-signed by openssl for test convenience. > > This is the site for referrence : > http://andyjeffries.co.uk/articles/x509-encrypted-authenticated-socket-ruby-client > > Or should I need a real certificate issued by a real CA to let things work? > > Any tips or suggestions welcomed, thank you very much~ > > Good day. > > Kay > > ** > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > You're trying to connect to the same port on localhost as a client and a server? I don't know for certain but I don't think that should work. Two computers? -- Alexander 7D9C597B -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Thu Dec 15 20:59:29 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 15 Dec 2011 20:59:29 +0100 Subject: [Tutor] timeit() help Message-ID: So, it turns out that my ISP blocked Project Euler, so instead of working on my next problem, I polished Problem 4 a bit: >A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 ? 99. >Find the largest palindrome made from the product of two 3-digit numbers. Those who don't want spoilers should look away. While it's perfectly fine to brute-force this (what I initially did) with two for-loops, I wanted to make a better version. Here's the code: First something to check whether a number is a palindrome: def is_palindrome(number): number = str(number) return number == number[::-1] Then the crunching part: def biggest(): big_x, big_y, max_seen = 0, 0, 0 for x in range(999, 99, -1): for y in range(x, 99, -1): #so we don't double count if x*y < max_seen: continue #since we're decreasing if is_palindrome(x*y): big_x, big_y, max_seen = x, y, x*y return big_x, big_y, max_seen However, I got to thinking... If we assume that the palindrome starts with 9, it must end with 9 (I think that's a fair assumption, really -- but it could come back and bite me I suppose). That means that the only values for the third digit in each of the two factors would have to be 1, 3, 7 or 9 (1 * 9, 3 * 3, 7 * 7 or 9 * 1). If we check for this condition before checking whether a number is palindromic, we ought to cut down on the numbers checked by, oh, I don't know... half, at least? (it turns out that it's more: 405450 values, only 64980 have 1, 3, 7 or 9 in the end), so in order to avoid checking some 340,000 numbers, I wrote a third function: def check_value(number1, number2): number1, number2 = str(number1), str(number2) return number1[-1] in "1379" and number2[-1] in "1379" Putting this one inside the biggest() function, the final biggest() function looks like this: def biggest(): big_x, big_y, max_seen = 0, 0, 0 for x in range(999, 99, -1): for y in range(x, 99, -1): #so we don't double count if check_value(x, y): #we ignore all numbers that doesn't end in 1379 if x*y < max_seen: continue #since we're decreasing if is_palindrome(x*y): big_x, big_y, max_seen = x, y, x*y return big_x, big_y, max_seen My biggest problem now is that I don't know how to measure any changes in efficiency. I know that the functions are working perfectly fine as-is, and I shouldn't really optimize without a need to, but I'm mostly curious as to whether the check_value() function is worth it or not. To this I thought I'd use timeit(), but I can't for the life of me work out how it works. At all. I've tried using it from the command prompt, from the interpreter and in the code itself and it just doesn't work. Or, it might very well work but it doesn't actually time anything for me. It's very frustrating, but I feel like I'm too stupid to read the official documentation for it (that is, I might understand the words in the documentation, but I can't get it to work). Please help? -- best regards, Robert S. From Calle_Python at live.se Thu Dec 15 22:09:20 2011 From: Calle_Python at live.se (Calle) Date: Thu, 15 Dec 2011 22:09:20 +0100 Subject: [Tutor] [TUTOR]Code Deciphering Message-ID: Hi! I was wondering, how do you use Python to decipher codes? It feels like it should be pretty simple, but I haven't found any tutorials about it yet. Have a nice day! // Calle From robert.sjoblom at gmail.com Thu Dec 15 22:34:41 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 15 Dec 2011 22:34:41 +0100 Subject: [Tutor] [TUTOR]Code Deciphering In-Reply-To: References: Message-ID: > I was wondering, how do you use Python to decipher codes? It feels like it > should be pretty simple, but I haven't found any tutorials about it yet. What kind of codes? Or do you mean ciphers? Generally speaking, a code represent letters or numbers in transmitting a message. In other words, a code deals with phrases and sentences or whole words. Example "steal the cabbage at dawn" could mean "kill the king on wednesday". A cipher deals with letters. It is a message written in letters in a predetermined code. This means that a cipher is a system of communication that uses letters instead of phrases. Examples being the standard Caesar cipher where "APPLE" might be written "BQQMB" (ie, shifted one letter to the right). -- best regards, Robert S. From rail.shafigulin at gmail.com Thu Dec 15 23:01:28 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Thu, 15 Dec 2011 17:01:28 -0500 Subject: [Tutor] modify values for object derived from datetime.datetime Message-ID: i writing some code to do device testing at my work. testing is related to date and time, so naturally i decided to create a class that inherits from datetime.datetime. main reason is that i need to add, subtract and compare datetime objects and datetime.datetime allows me to do that. here is the code: class LTime(datetime.datetime): TOLERANCE = 10 def __new__(self, year, month, day, *args): if year == 0: year = 2000 return super().__new__(self, year, month, day, *args) def modify(self): self = self.replace(2012, 12, 12) print(self) def main(): mytime = LTime.now() mytime.modify() print(mytime) if __name__ == '__main__': main() the problem that i see is that i'm not able to modify date and time because it seems that those attributes are immutable. another problem that i see is in the modify() routine. if you print mytime the date and time are still old. can anybody explain why this is happening and if it is even possible to achieve what i'm trying to achieve, which is to change self.date and self.time any help is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Calle_Python at live.se Thu Dec 15 23:37:49 2011 From: Calle_Python at live.se (Calle) Date: Thu, 15 Dec 2011 23:37:49 +0100 Subject: [Tutor] [TUTOR]Code Deciphering In-Reply-To: References: Message-ID: -----Ursprungligt meddelande----- From: Robert Sjoblom Sent: Thursday, December 15, 2011 10:34 PM To: Calle Cc: tutor at python.org Subject: Re: [Tutor] [TUTOR]Code Deciphering > I was wondering, how do you use Python to decipher codes? It feels like it > should be pretty simple, but I haven't found any tutorials about it yet. What kind of codes? Or do you mean ciphers? Generally speaking, a code represent letters or numbers in transmitting a message. In other words, a code deals with phrases and sentences or whole words. Example "steal the cabbage at dawn" could mean "kill the king on wednesday". A cipher deals with letters. It is a message written in letters in a predetermined code. This means that a cipher is a system of communication that uses letters instead of phrases. Examples being the standard Caesar cipher where "APPLE" might be written "BQQMB" (ie, shifted one letter to the right). -- best regards, Robert S. -------------------------------------------------- Hi! Sorry, I meant ciphers. How would a basic script for solving move-one-step-to-the-right ciphers look like? Have a nice day // Calle From stayvoid at gmail.com Thu Dec 15 23:52:26 2011 From: stayvoid at gmail.com (Stayvoid) Date: Fri, 16 Dec 2011 01:52:26 +0300 Subject: [Tutor] String formating Message-ID: Hey folks! What's the difference between these commands? print "%02d" % (12) print "%d" % (12) I know that "d" stands for decimal. What does "02" mean? Cheers! From robert.sjoblom at gmail.com Fri Dec 16 00:53:35 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Fri, 16 Dec 2011 00:53:35 +0100 Subject: [Tutor] [TUTOR]Code Deciphering In-Reply-To: References: Message-ID: On 15 December 2011 23:37, Calle wrote: > -----Ursprungligt meddelande----- From: Robert Sjoblom > Sent: Thursday, December 15, 2011 10:34 PM > To: Calle > Cc: tutor at python.org > Subject: Re: [Tutor] [TUTOR]Code Deciphering > > >> I was wondering, how do you use Python to decipher codes? It feels like it >> should be pretty simple, but I haven't found any tutorials about it yet. > > > What kind of codes? Or do you mean ciphers? Generally speaking, a code > represent letters or numbers in transmitting a message. In other > words, a code deals with phrases and sentences or whole words. Example > "steal the cabbage at dawn" could mean "kill the king on wednesday". > > A cipher deals with letters. It is a message written in letters in a > predetermined code. This means that a cipher is a system of > communication that uses letters instead of phrases. Examples being the > standard Caesar cipher where "APPLE" might be written "BQQMB" (ie, > shifted one letter to the right). > Sorry, I meant ciphers. How would a basic script for solving > move-one-step-to-the-right ciphers look like? Weeeell... There are different ways to solve that, but show us what you've come up with so far and we might be able to point you in the right direction. You won't learn anything by getting the answer posted and just copy-paste it for whatever (nefarious) use you need it; you'll learn a lot more if you work toward the solution yourself. I'll just point you in the direction of ASCII values for now. -- best regards, Robert S. From steve at pearwood.info Fri Dec 16 01:20:42 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Dec 2011 11:20:42 +1100 Subject: [Tutor] Localhost client-server simple ssl socket test program problems In-Reply-To: References: Message-ID: <4EEA8EDA.60106@pearwood.info> Can you please be more careful to use plain text and not "rich text" or HTML when posting code? Because it destroys the necessary formatting: Yang Chun-Kai wrote: [...] > My server code: > import socketimport sslbindsocket = socket.socket()bindsocket.bind(('127.0.0.1', 1234))bindsocket.listen(5)print 'server is waiting for connection...'newsocket, fromaddr = bindsocket.accept()print 'start ssl socket...'connstream = ssl.wrap_socket(newsocket, server_side=True, certfile="/etc/home/ckyang/PHA/testsslsocket/mypha.crt", keyfile="/etc/home/ckyang/PHA/testsslsocket/mypha.key", ssl_version=ssl.PROTOCOL_SSLv23)data = connstream.read()print 'connected from address', fromaddrprint 'received data as', repr(data)connstream.close() Thank you. -- Steven From steve at pearwood.info Fri Dec 16 01:35:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Dec 2011 11:35:43 +1100 Subject: [Tutor] [TUTOR]Code Deciphering In-Reply-To: References: Message-ID: <4EEA925F.5030405@pearwood.info> Calle wrote: > Hi! > > I was wondering, how do you use Python to decipher codes? It feels like > it should be pretty simple, but I haven't found any tutorials about it yet. This is not a tutorial, but you might find it useful: http://pypi.python.org/pypi/obfuscate/ -- Steven From steve at pearwood.info Fri Dec 16 01:46:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Dec 2011 11:46:30 +1100 Subject: [Tutor] String formating In-Reply-To: References: Message-ID: <4EEA94E6.80209@pearwood.info> Stayvoid wrote: > Hey folks! > > What's the difference between these commands? > > print "%02d" % (12) > > print "%d" % (12) > > I know that "d" stands for decimal. What does "02" mean? "0" means to use leading zeroes; "2" means to use 2 digits. Here's a better example: py> "%05d" % 12 '00012' More information here: http://docs.python.org/library/stdtypes.html#string-formatting-operations -- Steven From pierre.dagenais at ncf.ca Fri Dec 16 01:41:29 2011 From: pierre.dagenais at ncf.ca (pierre dagenais) Date: Thu, 15 Dec 2011 19:41:29 -0500 Subject: [Tutor] Test - please ignore Message-ID: <4EEA93B9.3020900@ncf.ca> From alan.gauld at btinternet.com Fri Dec 16 04:40:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Dec 2011 03:40:18 +0000 Subject: [Tutor] [TUTOR]Code Deciphering In-Reply-To: References: Message-ID: On 15/12/11 23:53, Robert Sjoblom wrote: > you'll learn a lot more if you work toward the solution yourself. I'll > just point you in the direction of ASCII values for now. You might find the ord() function useful too... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Fri Dec 16 06:13:07 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 16 Dec 2011 00:13:07 -0500 Subject: [Tutor] where I am going wrong? Message-ID: <4EEAD363.8070709@gmail.com> Suggestions for potentially simpler and more efficient code. Create a ruple of the 5th powers of the 10 digits and look them up (should be faster than recomputing the 5th power each time) (0, 1, 16, ... ) Instead of trying all permutations of digits, use combinations. 12345 will yield the same sum-of-5th-powers as 23154. Compute the sum then see if it is composed of the source digits. -- Bob Gailer 919-636-4239 Chapel Hill NC From geonyoro at gmail.com Fri Dec 16 06:31:20 2011 From: geonyoro at gmail.com (George Nyoro) Date: Fri, 16 Dec 2011 02:31:20 -0300 Subject: [Tutor] Localhost client-server simple ssl socket test program problems Message-ID: >You're trying to connect to the same port on >localhost as a client and a >server? I don't know for certain but I don't >think that should work. >Two computers? -- >Alexander it should work. I did short tutorial on this like a month ago and it worked. The only difference is that in mine it didn't have the part below which is the source of the problem. Also, in mine, I used "send" and "recv" though I doubt this makes any difference. > ssl_sock = ssl.wrap_socket(s, > ca_certs="/home/ckyang/PHA/testsslsocket/ myCA.crt", > cert_reqs=ssl.CERT_REQUIRED) > ssl_sock.connect(("127.0.0.1", 1234)) From geonyoro at gmail.com Fri Dec 16 06:31:34 2011 From: geonyoro at gmail.com (George Nyoro) Date: Fri, 16 Dec 2011 02:31:34 -0300 Subject: [Tutor] Localhost client-server simple ssl socket test program problems Message-ID: >You're trying to connect to the same port on >localhost as a client and a >server? I don't know for certain but I don't >think that should work. >Two computers? -- >Alexander it should work. I did short tutorial on this like a month ago and it worked. The only difference is that in mine it didn't have the part below which is the source of the problem. Also, in mine, I used "send" and "recv" though I doubt this makes any difference. > ssl_sock = ssl.wrap_socket(s, > ca_certs="/home/ckyang/PHA/testsslsocket/ myCA.crt", > cert_reqs=ssl.CERT_REQUIRED) > ssl_sock.connect(("127.0.0.1", 1234)) On 15/12/2011, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: Localhost client-server simple ssl socket test program > problems (Alexander) > 2. timeit() help (Robert Sjoblom) > 3. [TUTOR]Code Deciphering (Calle) > 4. Re: [TUTOR]Code Deciphering (Robert Sjoblom) > 5. modify values for object derived from datetime.datetime > (rail shafigulin) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 15 Dec 2011 14:24:37 -0500 > From: Alexander > To: Yang Chun-Kai > Cc: python-list at python.org, tutor at python.org > Subject: Re: [Tutor] Localhost client-server simple ssl socket test > program problems > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > 2011/12/15 Yang Chun-Kai > >> Hello,everyone!! >> >> I am writing a simple ssl client-server test program on my personal >> laptop. >> >> And I encounter some problems with my simple programs. >> >> Please give me some helps. >> >> -------------------------------------------------------------------------------------------------------------------------------------------------------- >> >> My server code: >> >> import socket >> import ssl >> bindsocket = socket.socket() >> bindsocket.bind(('127.0.0.1', 1234)) >> bindsocket.listen(5) >> print 'server is waiting for connection...' >> newsocket, fromaddr = bindsocket.accept() >> print 'start ssl socket...' >> connstream = ssl.wrap_socket(newsocket, server_side=True, >> certfile="/etc/home/ckyang/PHA/testsslsocket/mypha.crt", >> keyfile="/etc/home/ckyang/PHA/testsslsocket/mypha.key", >> ssl_version=ssl.PROTOCOL_SSLv23) >> data = connstream.read() >> print 'connected from address', fromaddr >> print 'received data as', repr(data) >> connstream.close() >> >> My client code: >> >> import socket >> import ssl >> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >> ssl_sock = ssl.wrap_socket(s, >> ca_certs="/home/ckyang/PHA/testsslsocket/myCA.crt", >> cert_reqs=ssl.CERT_REQUIRED) >> ssl_sock.connect(("127.0.0.1", 1234)) >> ssl_sock.write("hello") >> ssl_sock.close() >> >> >> ----------------------------------------------------------------------------------------------------------------------------------------------------------- >> Server side error: >> >> File "views.py", line 17, in & lt;module> >> connstream = ssl.wrap_socket(newsocket, server_side=True, >> certfile="/etc/home/ckyang/PHA/testsslsocket/mypha.crt", >> keyfile="/etc/home/ckyang/PHA/testsslsocket/mypha.key", >> ssl_version=ssl.PROTOCOL_SSLv23) >> File "/usr/lib/python2.7/ssl.py", line 344, in wrap_socket >> ciphers=ciphers) >> File "/usr/lib/python2.7/ssl.py", line 119, in __init__ >> ciphers) >> ssl.SSLError: [Errno 336265218] _ssl.c:347: error:140B0002:SSL >> routines:SSL_CTX_use_PrivateKey_file:system lib >> >> Client side error: >> >> File "client.py", line 10, in >> ssl_sock.connect(("127.0.0.1", 1234)) >> File "/usr/lib/python2.7/ssl.py", line 299, in connect** >> self.do_handshake() >> File "/usr/lib/python2.7/ssl.py", line 283, in do_handshake >> self._sslobj.do_handshake() >> socket.error: [Errno 104] Connection reset by peer >> >> >> ------------------------------------------------------------------------------------------------------------------------------------------------------------ >> So what is wrong with my code? >> >> The codes are so simple and so much like python official site sample >> demonstration, but I still cant get it work, so frustrating. >> >> Seems the problem happened on server side then cause client side cant >> connect well, is that right? >> >> ** >> My platform is ubuntu, with openssl 0.9.8 and python 2.7. >> >> All certificates and keys self-signed by openssl for test convenience. >> >> This is the site for referrence : >> http://andyjeffries.co.uk/articles/x509-encrypted-authenticated-socket-ruby-client >> >> Or should I need a real certificate issued by a real CA to let things >> work? >> >> Any tips or suggestions welcomed, thank you very much~ >> >> Good day. >> >> Kay >> >> ** >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > You're trying to connect to the same port on localhost as a client and a > server? I don't know for certain but I don't think that should work. > Two computers? > > > -- > Alexander > 7D9C597B > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 2 > Date: Thu, 15 Dec 2011 20:59:29 +0100 > From: Robert Sjoblom > To: Tutor - python List > Subject: [Tutor] timeit() help > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > So, it turns out that my ISP blocked Project Euler, so instead of > working on my next problem, I polished Problem 4 a bit: > >>A palindromic number reads the same both ways. The largest palindrome made >> from the product of two 2-digit numbers is 9009 = 91 ? 99. >>Find the largest palindrome made from the product of two 3-digit numbers. > > Those who don't want spoilers should look away. > > While it's perfectly fine to brute-force this (what I initially did) > with two for-loops, I wanted to make a better version. Here's the > code: > > First something to check whether a number is a palindrome: > def is_palindrome(number): > number = str(number) > return number == number[::-1] > > Then the crunching part: > > def biggest(): > big_x, big_y, max_seen = 0, 0, 0 > for x in range(999, 99, -1): > for y in range(x, 99, -1): #so we don't double count > if x*y < max_seen: continue #since we're decreasing > if is_palindrome(x*y): > big_x, big_y, max_seen = x, y, x*y > return big_x, big_y, max_seen > > However, I got to thinking... If we assume that the palindrome starts > with 9, it must end with 9 (I think that's a fair assumption, really > -- but it could come back and bite me I suppose). That means that the > only values for the third digit in each of the two factors would have > to be 1, 3, 7 or 9 (1 * 9, 3 * 3, 7 * 7 or 9 * 1). If we check for > this condition before checking whether a number is palindromic, we > ought to cut down on the numbers checked by, oh, I don't know... half, > at least? (it turns out that it's more: 405450 values, only 64980 have > 1, 3, 7 or 9 in the end), so in order to avoid checking some 340,000 > numbers, I wrote a third function: > > def check_value(number1, number2): > number1, number2 = str(number1), str(number2) > return number1[-1] in "1379" and number2[-1] in "1379" > > Putting this one inside the biggest() function, the final biggest() > function looks like this: > > def biggest(): > big_x, big_y, max_seen = 0, 0, 0 > for x in range(999, 99, -1): > for y in range(x, 99, -1): #so we don't double count > if check_value(x, y): #we ignore all numbers that > doesn't end in 1379 > if x*y < max_seen: continue #since we're decreasing > if is_palindrome(x*y): > big_x, big_y, max_seen = x, y, x*y > return big_x, big_y, max_seen > > My biggest problem now is that I don't know how to measure any changes > in efficiency. I know that the functions are working perfectly fine > as-is, and I shouldn't really optimize without a need to, but I'm > mostly curious as to whether the check_value() function is worth it or > not. To this I thought I'd use timeit(), but I can't for the life of > me work out how it works. At all. I've tried using it from the command > prompt, from the interpreter and in the code itself and it just > doesn't work. Or, it might very well work but it doesn't actually time > anything for me. It's very frustrating, but I feel like I'm too stupid > to read the official documentation for it (that is, I might understand > the words in the documentation, but I can't get it to work). Please > help? > > -- > best regards, > Robert S. > > > ------------------------------ > > Message: 3 > Date: Thu, 15 Dec 2011 22:09:20 +0100 > From: "Calle" > To: > Subject: [Tutor] [TUTOR]Code Deciphering > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > Hi! > > I was wondering, how do you use Python to decipher codes? It feels like it > should be pretty simple, but I haven't found any tutorials about it yet. > > Have a nice day! > // > Calle > > > > ------------------------------ > > Message: 4 > Date: Thu, 15 Dec 2011 22:34:41 +0100 > From: Robert Sjoblom > To: Calle > Cc: tutor at python.org > Subject: Re: [Tutor] [TUTOR]Code Deciphering > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > >> I was wondering, how do you use Python to decipher codes? It feels like it >> should be pretty simple, but I haven't found any tutorials about it yet. > > What kind of codes? Or do you mean ciphers? Generally speaking, a code > represent letters or numbers in transmitting a message. In other > words, a code deals with phrases and sentences or whole words. Example > "steal the cabbage at dawn" could mean "kill the king on wednesday". > > A cipher deals with letters. It is a message written in letters in a > predetermined code. This means that a cipher is a system of > communication that uses letters instead of phrases. Examples being the > standard Caesar cipher where "APPLE" might be written "BQQMB" (ie, > shifted one letter to the right). > -- > best regards, > Robert S. > > > ------------------------------ > > Message: 5 > Date: Thu, 15 Dec 2011 17:01:28 -0500 > From: rail shafigulin > To: tutor at python.org > Subject: [Tutor] modify values for object derived from > datetime.datetime > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > i writing some code to do device testing at my work. testing is related to > date and time, so naturally i decided to create a class that inherits from > datetime.datetime. main reason is that i need to add, subtract and compare > datetime objects and datetime.datetime allows me to do that. here is the > code: > > class LTime(datetime.datetime): > TOLERANCE = 10 > > def __new__(self, year, month, day, *args): > if year == 0: > year = 2000 > > return super().__new__(self, year, month, day, *args) > > def modify(self): > self = self.replace(2012, 12, 12) > print(self) > > > def main(): > mytime = LTime.now() > mytime.modify() > print(mytime) > > if __name__ == '__main__': > main() > > the problem that i see is that i'm not able to modify date and time because > it seems that those attributes are immutable. another problem that i see is > in the modify() routine. if you print mytime the date and time are still > old. can anybody explain why this is happening and if it is even possible > to achieve what i'm trying to achieve, which is to change self.date and > self.time > > any help is appreciated. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 94, Issue 57 > ************************************* > From ajarncolin at gmail.com Fri Dec 16 09:29:30 2011 From: ajarncolin at gmail.com (col speed) Date: Fri, 16 Dec 2011 15:29:30 +0700 Subject: [Tutor] Baccarat code check. Message-ID: If anyone has the time, please have a look at the attached text file and let me know any comments on how to improve it. Thanks a lot Col -------------- next part -------------- A non-text attachment was scrubbed... Name: baccarat2.py Type: text/x-python Size: 7154 bytes Desc: not available URL: From steve at pearwood.info Fri Dec 16 11:02:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Dec 2011 21:02:30 +1100 Subject: [Tutor] timeit() help In-Reply-To: References: Message-ID: <4EEB1736.1020301@pearwood.info> Robert Sjoblom wrote: > So, it turns out that my ISP blocked Project Euler, so instead of > working on my next problem, I polished Problem 4 a bit: Your ISP blocked Project Euler???? More likely the site is just temporarily down, but if you're right, what on earth would they block Project Euler for??? > My biggest problem now is that I don't know how to measure any changes > in efficiency. I know that the functions are working perfectly fine > as-is, and I shouldn't really optimize without a need to, but I'm > mostly curious as to whether the check_value() function is worth it or > not. To this I thought I'd use timeit(), but I can't for the life of > me work out how it works. It would help if you show us what you have tried, and the result you get, rather than just give us a vague "it doesn't work". But for what it's worth, here's some examples of using timeit. Is the built-in sum() function faster than one I write myself? I want to test this at the interactive interpreter, so I use the Timer class from the timeit module. Normally you will give Timer two arguments: the first is the code to be timed, the second is the setup code. The setup code gets run once per test; the code to be timed can be run as many times as you like. >>> def my_sum(numbers): ... total = 0 ... for x in numbers: ... total += x ... return x ... >>> from timeit import Timer >>> t1 = Timer('sum(mylist)', 'mylist = [2*i + 5 for i in range(100)]') >>> t2 = Timer('my_sum(mylist)', ... 'from __main__ import my_sum; mylist = [2*i + 5 for i in range(100)]') Notice that Timer takes strings to represent the code you want to time. That sometimes requires a little indirect dance to get your functions for testing. In the interactive interpreter you can use the "from __main__ import WHATEVER" trick to have that work. Now that we have two Timers, t1 and t2, we can run the tests to compare. The absolute minimum necessary is this: >>> t1.timeit() 2.916867971420288 >>> t2.timeit() 11.48215913772583 This calls the setup code once, then calls the timed code one million times and returns the time used. Three seconds to sum 100 numbers one million times isn't too bad. On my computer, the built-in sum seems to be about 4 times faster than my custom-made one. However, there is a catch: on modern computers, there are always other programs running, all the time, even when you can't see them: virus checkers, programs looking for updates, background scanners, all sorts of things. Maybe one of those programs just happened to start working while my_sum was being tested, and slowed the computer down enough to give a false result. Not very likely, not with such a big difference. But when timing two code snippets where the difference is only a matter of a few percent, it is very common to see differences from one test to another. Sometimes the slower one will seem speedier than the faster one, just because a virus scanner or cron job fired off at the wrong millisecond. We can help allow for this by doing more tests. Here I will increase the number of cycles from one million to two million, and pick the best out of five: >>> min( t1.repeat(number=2000000, repeat=5) ) 4.8857738971710205 >>> min( t2.repeat(number=2000000, repeat=5) ) 22.03256916999817 I think that's pretty clear: my hand-written sum function is about four and a half times slower than the built-in one. If a test seems to be going for ever, you can interrupt it with Ctrl-C. Here's another way to use timeit: from the command line. If you have Windows, you should use command.com or cmd.exe (or is it the other way around?). I'm using Linux, but the method is more or less identical. This time, I want to see what is the overhead of the "pass" statement. So I compare two code snippets, identical except one has "pass" after it: steve at runes:~$ python -m timeit -s "x = 42" "x += 1" 10000000 loops, best of 3: 0.0681 usec per loop steve at runes:~$ python -m timeit -s "x = 42" "x += 1; pass" 10000000 loops, best of 3: 0.0739 usec per loop "steve at runes:~$" is my prompt; you don't type that. You type everything starting from python to the end of the line. Notice that when called from the command line, timeit tries to be smart: it starts looping, doing the test over and over again until it has enough loops that the time taken is reasonable. Then it does it two more times, and prints the best of three. In this case, the overhead of a pass statement is about 0.006 microseconds on my computer. -- Steven From steve at pearwood.info Fri Dec 16 11:26:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 16 Dec 2011 21:26:23 +1100 Subject: [Tutor] modify values for object derived from datetime.datetime In-Reply-To: References: Message-ID: <4EEB1CCF.2010005@pearwood.info> rail shafigulin wrote: > i writing some code to do device testing at my work. testing is related to > date and time, so naturally i decided to create a class that inherits from > datetime.datetime. main reason is that i need to add, subtract and compare > datetime objects and datetime.datetime allows me to do that. here is the > code: > > class LTime(datetime.datetime): > TOLERANCE = 10 > > def __new__(self, year, month, day, *args): > if year == 0: > year = 2000 > return super().__new__(self, year, month, day, *args) By convention, the first argument of __new__ is normally spelled as "cls", short for class, because the instance hasn't been created yet. > def modify(self): > self = self.replace(2012, 12, 12) > print(self) The replace method creates a new datetime object. Just because you assign it to the name "self" doesn't mean you can change the existing datetime object. That is simply impossible: datetime objects are immutable, like ints. You might not quite understand why modifying immutable objects would be bad (which is why Python doesn't allow it). I can simulate the effect with this simple wrapper class: >>> class Mutable: ... def __init__(self, value): ... self.value = value ... def __str__(self): ... return str(self.value) ... __repr__ = __str__ ... def add(self, value): ... self.value += value ... >>> one = Mutable(1) # Pretend this is the int 1 >>> print(one) 1 >>> x = one >>> x.set(1) # pretend this was x += 1 >>> one # the int 1 has been modified in place 2 So if ints (and datetime objects) could be changed in place, you could never be sure what value a literal like 1 would have. Obviously this is useful in some situations, which is why we have mutable objects like lists. But datetime objects are not mutable, a design choice made by the creator of the module, so you cannot change it. So you have to change your design. Instead of writing code like this: today = LTime(2011, 12, 16) # ... # ... do stuff with today # ... today.modify(day=17) # fast forward in time to tomorrow # ... # ... do stuff with today, which is actually tomorrow # ... you need to change your code to be more like this: today = LTime(2011, 12, 16) # ... # ... do stuff with today # ... tomorrow = today.modify(day=17) # ... # ... do stuff with tomorrow # ... -- Steven From Calle_Python at live.se Fri Dec 16 12:19:58 2011 From: Calle_Python at live.se (Calle) Date: Fri, 16 Dec 2011 12:19:58 +0100 Subject: [Tutor] Tutor Digest, Vol 94, Issue 58 In-Reply-To: References: Message-ID: Message: 1 Date: Thu, 15 Dec 2011 23:37:49 +0100 From: "Calle" To: "Robert Sjoblom" Cc: tutor at python.org Subject: Re: [Tutor] [TUTOR]Code Deciphering Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original -----Ursprungligt meddelande----- From: Robert Sjoblom Sent: Thursday, December 15, 2011 10:34 PM To: Calle Cc: tutor at python.org Subject: Re: [Tutor] [TUTOR]Code Deciphering > I was wondering, how do you use Python to decipher codes? It feels like it > should be pretty simple, but I haven't found any tutorials about it yet. What kind of codes? Or do you mean ciphers? Generally speaking, a code represent letters or numbers in transmitting a message. In other words, a code deals with phrases and sentences or whole words. Example "steal the cabbage at dawn" could mean "kill the king on wednesday". A cipher deals with letters. It is a message written in letters in a predetermined code. This means that a cipher is a system of communication that uses letters instead of phrases. Examples being the standard Caesar cipher where "APPLE" might be written "BQQMB" (ie, shifted one letter to the right). -- best regards, Robert S. -------------------------------------------------- Hi! Sorry, I meant ciphers. How would a basic script for solving move-one-step-to-the-right ciphers look like? Have a nice day // Calle ------------------------------ ------------------------------ Message: 3 Date: Fri, 16 Dec 2011 00:53:35 +0100 From: Robert Sjoblom To: Calle Cc: tutor at python.org Subject: Re: [Tutor] [TUTOR]Code Deciphering Message-ID: Content-Type: text/plain; charset=ISO-8859-1 On 15 December 2011 23:37, Calle wrote: > -----Ursprungligt meddelande----- From: Robert Sjoblom > Sent: Thursday, December 15, 2011 10:34 PM > To: Calle > Cc: tutor at python.org > Subject: Re: [Tutor] [TUTOR]Code Deciphering > > >> I was wondering, how do you use Python to decipher codes? It feels like >> it >> should be pretty simple, but I haven't found any tutorials about it yet. > > > What kind of codes? Or do you mean ciphers? Generally speaking, a code > represent letters or numbers in transmitting a message. In other > words, a code deals with phrases and sentences or whole words. Example > "steal the cabbage at dawn" could mean "kill the king on wednesday". > > A cipher deals with letters. It is a message written in letters in a > predetermined code. This means that a cipher is a system of > communication that uses letters instead of phrases. Examples being the > standard Caesar cipher where "APPLE" might be written "BQQMB" (ie, > shifted one letter to the right). > Sorry, I meant ciphers. How would a basic script for solving > move-one-step-to-the-right ciphers look like? Weeeell... There are different ways to solve that, but show us what you've come up with so far and we might be able to point you in the right direction. You won't learn anything by getting the answer posted and just copy-paste it for whatever (nefarious) use you need it; you'll learn a lot more if you work toward the solution yourself. I'll just point you in the direction of ASCII values for now. -- best regards, Robert S. ------------------------------------ Well, I don't really know where to begin. I tried looking at other peoples code and write something based on that, but it ended up being too similair to the original code... I could show you what I came up with using pseudo-code. Get the cipher from user. Use ord() to convert into numbers. Add number to a new string while at the same time making it into a letter using chr(). Repeat 25 times and print the results. Am I on the right track with this or should I re-think? // Calle From rail.shafigulin at gmail.com Fri Dec 16 15:18:33 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Fri, 16 Dec 2011 09:18:33 -0500 Subject: [Tutor] modify values for object derived from datetime.datetime In-Reply-To: <4EEB1CCF.2010005@pearwood.info> References: <4EEB1CCF.2010005@pearwood.info> Message-ID: On Fri, Dec 16, 2011 at 5:26 AM, Steven D'Aprano wrote: > rail shafigulin wrote: > >> i writing some code to do device testing at my work. testing is related to >> date and time, so naturally i decided to create a class that inherits from >> datetime.datetime. main reason is that i need to add, subtract and compare >> datetime objects and datetime.datetime allows me to do that. here is the >> code: >> >> class LTime(datetime.datetime): >> TOLERANCE = 10 >> >> def __new__(self, year, month, day, *args): >> if year == 0: >> year = 2000 >> return super().__new__(self, year, month, day, *args) >> > > > By convention, the first argument of __new__ is normally spelled as "cls", > short for class, because the instance hasn't been created yet. > > > > def modify(self): >> self = self.replace(2012, 12, 12) >> print(self) >> > > The replace method creates a new datetime object. Just because you assign > it to the name "self" doesn't mean you can change the existing datetime > object. That is simply impossible: datetime objects are immutable, like > ints. > > You might not quite understand why modifying immutable objects would be > bad (which is why Python doesn't allow it). I can simulate the effect with > this simple wrapper class: > > >>> class Mutable: > ... def __init__(self, value): > ... self.value = value > ... def __str__(self): > ... return str(self.value) > ... __repr__ = __str__ > ... def add(self, value): > ... self.value += value > ... > >>> one = Mutable(1) # Pretend this is the int 1 > >>> print(one) > 1 > >>> x = one > >>> x.set(1) # pretend this was x += 1 > >>> one # the int 1 has been modified in place > 2 > > So if ints (and datetime objects) could be changed in place, you could > never be sure what value a literal like 1 would have. > > Obviously this is useful in some situations, which is why we have mutable > objects like lists. But datetime objects are not mutable, a design choice > made by the creator of the module, so you cannot change it. > > So you have to change your design. Instead of writing code like this: > > > today = LTime(2011, 12, 16) > # ... > # ... do stuff with today > # ... > today.modify(day=17) # fast forward in time to tomorrow > # ... > # ... do stuff with today, which is actually tomorrow > # ... > > you need to change your code to be more like this: > > > today = LTime(2011, 12, 16) > # ... > # ... do stuff with today > # ... > tomorrow = today.modify(day=17) > # ... > # ... do stuff with tomorrow > # ... > > > > > -- > Steven > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Thanks for the explanation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Dec 16 15:52:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 17 Dec 2011 01:52:00 +1100 Subject: [Tutor] Tutor Digest, Vol 94, Issue 58 In-Reply-To: References: Message-ID: <4EEB5B10.6090708@pearwood.info> Calle wrote: > Message: 1 > Date: Thu, 15 Dec 2011 23:37:49 +0100 > From: "Calle" [...] I'm sorry, it is too hard for me to work out which parts are your comments, and which are quotations from older emails in the Digest. Please do not reply to multiple messages in a digest at once: each reply to a message should be in a separate email. Also, please edit the subject line to something more useful that "Re Tutor Digest". I recommend you change your mail settings and turn of Digest and go onto individual emails. It is MUCH easier to carry on a discussion that way. One last thing: "--" on a line on its own is the marker for "End Of Email", with only the user's signature below the line. When you comment below the End Of Email line, many common email programs will grey the text out and make it difficult or impossible to reply to your comment. Thank you. -- Steven From ramit.prasad at jpmorgan.com Fri Dec 16 18:22:54 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 16 Dec 2011 17:22:54 +0000 Subject: [Tutor] Baccarat code check. In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474077EFF@SCACMX008.exchad.jpmchase.net> > If anyone has the time, please have a look at the attached text file and let me know any comments on how to improve it. Not everyone on this list gets attachments. You are usually better off including short code in the email or a pastebin link. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- -----Original Message----- From: tutor-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:tutor-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of col speed Sent: Friday, December 16, 2011 2:30 AM To: Python Tutors Subject: [Tutor] Baccarat code check. Thanks a lot Col This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From memilanuk at gmail.com Fri Dec 16 19:08:57 2011 From: memilanuk at gmail.com (Monte Milanuk) Date: Fri, 16 Dec 2011 18:08:57 +0000 (UTC) Subject: [Tutor] sqlite3: turning on foreign key support thru python Message-ID: I'm setting up an sqlite3 database to use as a base for some programming stuff I want to work on. Currently using python 2.7, which appears to have a new enough version of sqlite (just barely) to support foreign keys. As I understand things, sqlite by default has foreign keys turned off, unless specifically compiled otherwise or until you turn on foreign keys using 'pragma foreign_keys=ON'. And it needs to be turned on for each connection too. So... just putzing around using the python interactive shell... import sqlite3 sqlite3.sqlite_version '3.6.21' conn = sqlite3.connect('contacts.db') conn.execute('pragma foreign_keys=ON') conn.execute('pragma foreign_keys') It appears I am able to successfully import sqlite3, its of a recent enough version to support foreign keys (> 3.6.19), I connected it to an existing database 'contacts.db', and when I execute the pragma statement to turn on foreign key support it returns a cursor object. Similarly, when I send a pragma statement to query the status of foreign key support, it returns a cursor object. Now for the stupid question(s): How do I tell if it succeeded (short of trying an operation that should be blocked by foreign keys)? How do I use that cursor object returned by the pragma query to tell if its a '1' (on) or a '0' (off) and verify the state? TIA, Monte From modulok at gmail.com Fri Dec 16 20:43:09 2011 From: modulok at gmail.com (Modulok) Date: Fri, 16 Dec 2011 12:43:09 -0700 Subject: [Tutor] sqlite3: turning on foreign key support thru python In-Reply-To: References: Message-ID: >> How do I tell if it succeeded (short of trying an operation that should be >> blocked by foreign keys)? How do I use that cursor object returned by the >> pragma query to tell if its a '1' (on) or a '0' (off) and verify the state? The cursor object contains the result set. It's a python generator object. (Or at least a generator interface.) You have to iterate over it in order to see the resulting rows which are stored as a tuple. Not all operations return a result row. (For example, conn.execute('pragma foreign_keys=ON' will return a cursor object, but it won't generate any result rows, as there were none returned by the database.) To see the result of your second command, do something like this:: rows = conn.execute('pragma foreign_keys') for r in rows: print r You'll then see something like this when foreign keys are turned on:: (1,) Or this when they're turned off:: (0,) Hope that helps. -Modulok- On 12/16/11, Monte Milanuk wrote: > I'm setting up an sqlite3 database to use as a base for some programming > stuff I > want to work on. Currently using python 2.7, which appears to have a new > enough > version of sqlite (just barely) to support foreign keys. > > As I understand things, sqlite by default has foreign keys turned off, > unless > specifically compiled otherwise or until you turn on foreign keys using > 'pragma > foreign_keys=ON'. And it needs to be turned on for each connection too. > > So... just putzing around using the python interactive shell... > > > import sqlite3 > sqlite3.sqlite_version > '3.6.21' > conn = sqlite3.connect('contacts.db') > conn.execute('pragma foreign_keys=ON') > > conn.execute('pragma foreign_keys') > > > > It appears I am able to successfully import sqlite3, its of a recent enough > version to support foreign keys (> 3.6.19), I connected it to an existing > database 'contacts.db', and when I execute the pragma statement to turn on > foreign key support it returns a cursor object. Similarly, when I send a > pragma > statement to query the status of foreign key support, it returns a cursor > object. > > Now for the stupid question(s): > > How do I tell if it succeeded (short of trying an operation that should be > blocked by foreign keys)? How do I use that cursor object returned by the > pragma query to tell if its a '1' (on) or a '0' (off) and verify the state? > > TIA, > > Monte > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From memilanuk at gmail.com Fri Dec 16 21:21:46 2011 From: memilanuk at gmail.com (Monte Milanuk) Date: Fri, 16 Dec 2011 12:21:46 -0800 Subject: [Tutor] sqlite3: turning on foreign key support thru python In-Reply-To: References: Message-ID: That helped immensely... I was trying some different things trying to get at the results, but it never occurred to me to try iterating over it. The bit about some objects being iterable and some not is good to know! Thanks, Monte On Fri, Dec 16, 2011 at 11:43 AM, Modulok wrote: > >> How do I tell if it succeeded (short of trying an operation that should > be > >> blocked by foreign keys)? How do I use that cursor object returned by > the > >> pragma query to tell if its a '1' (on) or a '0' (off) and verify the > state? > > > The cursor object contains the result set. It's a python generator object. > (Or > at least a generator interface.) You have to iterate over it in order to > see > the resulting rows which are stored as a tuple. Not all operations return a > result row. (For example, conn.execute('pragma foreign_keys=ON' will > return a > cursor object, but it won't generate any result rows, as there were > none returned by the database.) > > To see the result of your second command, do something like this:: > > rows = conn.execute('pragma foreign_keys') > for r in rows: > print r > > > You'll then see something like this when foreign keys are turned on:: > > (1,) > > Or this when they're turned off:: > > (0,) > > Hope that helps. > -Modulok- > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Calle_Python at live.se Fri Dec 16 21:37:57 2011 From: Calle_Python at live.se (Calle) Date: Fri, 16 Dec 2011 21:37:57 +0100 Subject: [Tutor] [TUTOR]Code Deciphering(Re-sent) Message-ID: On 15 December 2011 23:37, Calle wrote: >>>>I was wondering, how do you use Python to decipher codes? It feels like >>>>it should be pretty simple, but I haven't found any tutorials about it >>>>yet. >>> What kind of codes? Or do you mean ciphers? Generally speaking, a code >>> represent letters or numbers in transmitting a message. In other >>> words, a code deals with phrases and sentences or whole words. Example >>> "steal the cabbage at dawn" could mean "kill the king on wednesday". >>> >>> A cipher deals with letters. It is a message written in letters in a >>> predetermined code. This means that a cipher is a system of >>> communication that uses letters instead of phrases. Examples being the >>> standard Caesar cipher where "APPLE" might be written "BQQMB" (ie, >>> shifted one letter to the right). >>> >>> -- >>> best regards, >>> Robert S. > >Sorry, I meant ciphers. How would a basic script for solving >> move-one-step-to-the-right ciphers look like? >Weeeell... There are different ways to solve that, but show us what >you've come up with so far and we might be able to point you in the >right direction. You won't learn anything by getting the answer posted >and just copy-paste it for whatever (nefarious) use you need it; >you'll learn a lot more if you work toward the solution yourself. I'll >just point you in the direction of ASCII values for now. > >-- >best regards, >Robert S. Well, I don't really know where to begin. I tried looking at other peoples code and write something based on that, but it ended up being too similair to the original code... I could show you what I came up with using pseudo-code. Get the cipher from user. Use ord() to convert into numbers. Add number to a new string while at the same time making it into a letter using chr(). Repeat 25 times and print the results. Am I on the right track with this or should I re-think? // Calle From kellyadrian at hotmail.com Fri Dec 16 23:02:52 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Fri, 16 Dec 2011 22:02:52 +0000 Subject: [Tutor] reset password program Message-ID: Hi guys, i created a program that allows users to login using a password that i set at the top of the program. Among other things users are given the option to change their password. My questions is; Is it possible for me to make this new password stick, in other words when they shut down and log in again i am back to the original password.....the new password only works while the programming is running. I know why this is happening, what i don't know is what to do about it. I am new to python and programming so if you have any ideas... please keep them simple. thanks all, adrian -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Dec 16 23:13:04 2011 From: d at davea.name (Dave Angel) Date: Fri, 16 Dec 2011 17:13:04 -0500 Subject: [Tutor] reset password program In-Reply-To: References: Message-ID: <4EEBC270.6030501@davea.name> On 12/16/2011 05:02 PM, ADRIAN KELLY wrote: > Hi guys, > i created a program that allows users to login using a password that i set at the top of the program. > Among other things users are given the option to change their password. My questions is; > > Is it possible for me to make this new password stick, in other words when they shut down and > log in again i am back to the original password.....the new password only works while the programming > is running. I know why this is happening, what i don't know is what to do about it. > > I am new to python and programming so if you have any ideas... > > please keep them simple. > > thanks all, > adrian > Nothing in Python objects is persistent. If you want something to survive till the next run, you have to write it to something external, such as a file. If this is a serious program, with important passwords, you'll want to encrypt the file. If it's just casual, encode the file in some obscure way. But if it's a class assignment, then save it in a text file, in a directory you'll be able to find next time. That last point is important. The program directory may be read-only to that user. So you might not be able to store it there. One approach is to save it in the user's home directory, so for me, it might be /home/davea Convention is to start it with a leading period, so that the ls command won't show it by default. Another question is whether you want a different password per user, and if you might have more than one user logged into your machine at the same time. Hope this helped, -- DaveA From kellyadrian at hotmail.com Fri Dec 16 23:49:40 2011 From: kellyadrian at hotmail.com (ADRIAN KELLY) Date: Fri, 16 Dec 2011 22:49:40 +0000 Subject: [Tutor] reset password program In-Reply-To: <4EEBC270.6030501@davea.name> References: , <4EEBC270.6030501@davea.name> Message-ID: thanks dave, just tried writing to file for the first time def main(): outfile.write('Hello this is a test') outfile.close() main() error, globalname outfile is not defined, do i need to import function to get this working? > Date: Fri, 16 Dec 2011 17:13:04 -0500 > From: d at davea.name > To: kellyadrian at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] reset password program > > On 12/16/2011 05:02 PM, ADRIAN KELLY wrote: > > Hi guys, > > i created a program that allows users to login using a password that i set at the top of the program. > > Among other things users are given the option to change their password. My questions is; > > > > Is it possible for me to make this new password stick, in other words when they shut down and > > log in again i am back to the original password.....the new password only works while the programming > > is running. I know why this is happening, what i don't know is what to do about it. > > > > I am new to python and programming so if you have any ideas... > > > > please keep them simple. > > > > thanks all, > > adrian > > > Nothing in Python objects is persistent. If you want something to > survive till the next run, you have to write it to something external, > such as a file. > > If this is a serious program, with important passwords, you'll want to > encrypt the file. If it's just casual, encode the file in some obscure > way. But if it's a class assignment, then save it in a text file, in a > directory you'll be able to find next time. > > That last point is important. The program directory may be read-only to > that user. So you might not be able to store it there. One approach is > to save it in the user's home directory, so for me, it might be > /home/davea Convention is to start it with a leading period, so that > the ls command won't show it by default. Another question is whether > you want a different password per user, and if you might have more than > one user logged into your machine at the same time. > > Hope this helped, > > > > > > > > -- > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Dec 17 01:01:43 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 16 Dec 2011 16:01:43 -0800 Subject: [Tutor] reset password program In-Reply-To: References: , <4EEBC270.6030501@davea.name> Message-ID: On 12/16/2011 2:49 PM ADRIAN KELLY said... > thanks dave, > just tried writing to file for the first time > > def main(): > outfile.write('Hello this is a test') > outfile.close() > main() > > *error, globalname outfile is not defined, do i need to import function > to get this working?* No, but you do need to initialize outfile appropriately. The error (next time post the entire traceback please -- it provides the specifics you'll need to fix the bug) tells you that 'outfile is not defined' If you set outfile to a writable file object you'll get it going. Look at the 'open' documentation. HTH, Emile From tvssarma.omega9 at gmail.com Sat Dec 17 01:08:55 2011 From: tvssarma.omega9 at gmail.com (Sarma Tangirala) Date: Sat, 17 Dec 2011 05:38:55 +0530 Subject: [Tutor] reset password program In-Reply-To: References: <4EEBC270.6030501@davea.name> Message-ID: > thanks dave, > just tried writing to file for the first time > > def main(): > outfile.write('Hello this is a test') > outfile.close() > main() > > error, globalname outfile is not defined, do i need to import function to get this working? > > Fyi, you should check the python docs. They have a good introduction if this is the first time. Also its a good idea to use a try block incase the file does not exist and you have to do a bit of error handling. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Dec 17 01:51:18 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 17 Dec 2011 11:51:18 +1100 Subject: [Tutor] reset password program In-Reply-To: References: Message-ID: <4EEBE786.6090509@pearwood.info> ADRIAN KELLY wrote: > Hi guys, > i created a program that allows users to login using a password that i set at the top of the program. > Among other things users are given the option to change their password. My questions is; > > Is it possible for me to make this new password stick, in other words when they shut down and > log in again i am back to the original password.....the new password only works while the programming > is running. I know why this is happening, what i don't know is what to do about it. This will be *very* low security and so shouldn't be used for real passwords. # Read the user's password # ------------------------ try: password_file = open("my secret password.txt", "r") except (IOError, OSError): # password file doesn't exist, or is unreadable password = '' else: # password file does exist password = password_file.read() password_file.close() # Write the user's password # ------------------------- password_file = open("my secret password.txt", "w") password_file.write(password) password_file.close() Some improvements to think about, in order of least secure (easiest) to most secure (hardest). (1) "my secret password.txt" is a crappy name. Is there a better name? (2) Can you make the file hidden so users won't accidentally delete it? Hint: on Linux and Mac, you can hide a file by starting the name with a dot. How about Windows? (3) Can you make sure that the password file is only readable by the user? Hint: os.chmod function. You will need to investigate how it works. (4) Anyone who opens the password with a text editor will see the password in plain ordinary text. Can you obfuscate the password so it is harder to read? (5) Do you really need to store the *actual* password? It may be better to just store a hash of the password, and then compare hashes instead of actual passwords. Research "md5" and "sha" hashes and the hashlib library. (6) Even with hashes, breaking passwords is not difficult. Investigate the importance of "salting" the password so as to increase security. -- Steven From hugo.yoshi at gmail.com Sat Dec 17 02:08:53 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sat, 17 Dec 2011 02:08:53 +0100 Subject: [Tutor] reset password program In-Reply-To: References: <4EEBC270.6030501@davea.name> Message-ID: On Fri, Dec 16, 2011 at 11:49 PM, ADRIAN KELLY wrote: > thanks dave, > just tried writing to file for the first time > > def main(): > ?outfile.write('Hello this is a test') > ?outfile.close() > main() > > error, globalname outfile is not defined, do i need to import function to > get this working? > A lot of stuff is missing here. let's get back to basics. What is outfile? It's a variable. So, where does it come from? well, right now, you just sort of magically conjure it up out of nowhere, which is why python is complaining ("not defined" is the python telling you "you never told me what this thing is"). So, we want the variable outfile to point to a file object. Making a file object is very simple, just call the open() function. You don't have to import open(), it's a builtin, which means it's always available to you: outfile = open('file_name.txt', 'w') open takes two arguments. The first one is the filename, the second is the mode in which the file is to be opened. Basically, 'r' is for reading, 'w' for writing (this mode will delete existing data in the file, if any), and 'a' is appending. You can add a 'b' for opening in binary mode, and a '+' for opening the file for updating. Now we have a file object, and we can use the write() method on it as you have done above (make sure not to forget close(), it's good practice). That should get you started. There's a good bit of theory behind saving passwords securely (you don't usually want everyone to be able to open the file and read the passwords, basically), but I won't get into that right now. If you're ready for that, you might want to check out hashlib From robert.sjoblom at gmail.com Sat Dec 17 02:17:49 2011 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sat, 17 Dec 2011 02:17:49 +0100 Subject: [Tutor] reset password program In-Reply-To: <4EEBE786.6090509@pearwood.info> References: <4EEBE786.6090509@pearwood.info> Message-ID: > Some improvements to think about, in order of least secure (easiest) to most > secure (hardest). > > (1) "my secret password.txt" is a crappy name. Is there a better name? I'm going to go with "EULA.txt"; the reasons should be obvious. -- best regards, Robert S. From d at davea.name Sat Dec 17 10:40:21 2011 From: d at davea.name (Dave Angel) Date: Sat, 17 Dec 2011 04:40:21 -0500 Subject: [Tutor] Baccarat code check. In-Reply-To: References: Message-ID: <4EEC6385.1060905@davea.name> On 12/16/2011 03:29 AM, col speed wrote: > If anyone has the time, please have a look at the attached text file > and let me know any comments on how to improve it. > Thanks a lot > Col > I don't see any response for 24 hours, so I'd say that nobody has the time. However, you could have improved the odds substantially by giving us a clue what you were looking for. Is this a program that runs properly, correctly and quickly enough, and you just want advice on making the code cleaner and clearer? Or does the program run apparently normally, but gets the wrong results, and you need help fixing that? If so, tell us specifically what seems to be wrong: what happens when you run it, and what did you expect different? Or does the program die with some exception? in that case, tell us how to reproduce the symptom, and show us the full traceback when it dies. Or something else? .... I can only guess the first case is your supposed situation. So I'll look it over. I'm not running it, so all i can comment on is obvious bugs and stylistic errors. I also have to assume you're running it on a Linux type machine, with Python 2.7. I don't know baccarat, so I make mistakes on that account. First obvious problem is that each player has its own kitty. I don't know of any card game where that is done. But maybe in baccarat the word means something totally different. Naming difficulty, getPlayers() cannot reasonably be called more than once, so it's better named something like init_players(). In class Card, your final else clause looks like a good place for assert(). It'll never happen in production, but only till the program has passed its test suite. In placeBets(), there doesn't seem to be any indication of which person (name) is betting each time. That should probably be part of the prompt to raw_input. In (), the raw_input() that's assigned to standordraw, it doesn't include the player name in the prompt. This is even more important than the last, since only a few of the players will get prompted like this each round. hope that helps some. -- DaveA From __peter__ at web.de Sat Dec 17 10:49:54 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 17 Dec 2011 10:49:54 +0100 Subject: [Tutor] Baccarat code check. References: Message-ID: col speed wrote: > If anyone has the time, please have a look at the attached text file > and let me know any comments on how to improve it. At first glance the code looks good. I think you can move to the next level now ;) Are you using a version control system? If not, have a look at mercurial. Here's an introduction: http://hginit.com/ Once you've checked in the code you can start writing tests that verify the correctness of parts of it, see http://docs.python.org/library/unittest.html Don't be afraid to change your code to make it easier to test. That's called "refactoring" and usually improves the code quality. If something goes wrong you always have the previous version in the version control. How do you know you're done writing tests? There's a great tool that helps you measure what portion of your code is exercised by your tests: http://pypi.python.org/pypi/coverage Do you know the style guide for Python code (http://www.python.org/dev/peps/pep-0008/)? You should at least consider to follow it. Now to your actual code: I don't know Baccarat and haven't looked closely at your script. I think you should base your Card class on data rather than calculations. That will simplify it significantly: _cards = [ ("1", 1), ("2", 2), ("3", 3), ("4", 4), ("5", 5), ("6", 6), ("7", 7), ("8", 8), ("9", 9), ("10", 0), ("J", 0), ("Q", 0), ("K", 0), ("A", 1), ] class Card(object): def __init__(self, name, value): self.name = name self.value = value cards = [Card(n, v) for n, v in _cards] class Shoe(list): """A collection of 8 decks of cards""" def __init__(self): self[:] = cards*(4*8) random.shuffle(self) #... Once you have unittests in place you can try and replace your Card implementation with mine and see if your script continues to work correctly. Last and least: - I ran your script and got an UnboundLocalError (I'm sorry I didn't keep the traceback); there must be a code path in main() where last_card is undefined. Try to separate the program logic from the user interface. This makes it easier to identify and reproduce problems in the program logic and to write tests to prevent them in the future. - random.choice() takes a list argument From ajarncolin at gmail.com Sat Dec 17 10:56:45 2011 From: ajarncolin at gmail.com (col speed) Date: Sat, 17 Dec 2011 16:56:45 +0700 Subject: [Tutor] Baccarat code check. In-Reply-To: <4EEC6385.1060905@davea.name> References: <4EEC6385.1060905@davea.name> Message-ID: On 17 December 2011 16:40, Dave Angel wrote: > On 12/16/2011 03:29 AM, col speed wrote: >> >> If anyone has the time, please have a look at the attached text file >> and let me know any comments on how to improve it. >> Thanks a lot >> Col >> > I don't see any response for 24 hours, so I'd say that nobody has the time. > ?However, you could have improved the odds substantially by giving us a clue > what you were looking for. > > Is this a program that runs properly, correctly and quickly enough, and you > just want advice on making the code cleaner and clearer? > > Or does the program run apparently normally, but gets the wrong results, and > you need help fixing that? ?If so, tell us specifically what seems to be > wrong: ? what happens when you run it, and what did you expect different? > > Or does the program die with some exception? ?in that case, tell us how to > reproduce the symptom, and show us the full traceback when it dies. > > Or something else? > > .... > I can only guess the first case is your supposed situation. ?So I'll look it > over. ?I'm not running it, so all i can comment on is obvious bugs and > stylistic errors. ?I also have to assume you're running it on a Linux type > machine, with Python 2.7. > > I don't know baccarat, so I make mistakes on that account. > > First obvious problem is that each player has its own kitty. ?I don't know > of any card game where that is done. ?But maybe in baccarat the word means > something totally different. > > Naming difficulty, getPlayers() cannot reasonably be called more than once, > so it's better named something like init_players(). > > In class Card, your final else clause looks like a good place for assert(). > ?It'll never happen in production, but only till the program has passed its > test suite. > > In placeBets(), there doesn't seem to be any indication of which person > (name) is betting each time. ?That should probably be part of the prompt to > raw_input. > > In ? (), the raw_input() that's assigned to standordraw, it doesn't include > the player name in the prompt. This is even more important than the last, > since only a few of the players will get prompted like this each round. > > hope that helps some. > > > > -- > > DaveA > Thanks for your reply. Yes, you supposed correctly, I just wanted some advice to make it clearer and cleaner. Thanks for your help, I know people here don't have a lot of time and I appreciate that. That's all I wanted, really. I'll try & make myself clearer next time. Thanks again Col From ajarncolin at gmail.com Sat Dec 17 11:01:56 2011 From: ajarncolin at gmail.com (col speed) Date: Sat, 17 Dec 2011 17:01:56 +0700 Subject: [Tutor] Baccarat code check. In-Reply-To: References: Message-ID: On 17 December 2011 16:49, Peter Otten <__peter__ at web.de> wrote: > col speed wrote: > >> If anyone has the time, please have a look at the attached text file >> and let me know any comments on how to improve it. > > At first glance the code looks good. I think you can move to the next level > now ;) > > Are you using a version control system? If not, have a look at mercurial. > Here's an introduction: http://hginit.com/ > > Once you've checked in the code you can start writing tests that verify the > correctness of parts of it, see http://docs.python.org/library/unittest.html > Don't be afraid to change your code to make it easier to test. That's called > "refactoring" and usually improves the code quality. If something goes wrong > you always have the previous version in the version control. > > How do you know you're done writing tests? There's a great tool that helps > you measure what portion of your code is exercised by your tests: > > http://pypi.python.org/pypi/coverage > > Do you know the style guide for Python code > (http://www.python.org/dev/peps/pep-0008/)? You should at least consider to > follow it. > > Now to your actual code: I don't know Baccarat and haven't looked closely at > your script. I think you should base your Card class on data rather than > calculations. That will simplify it significantly: > > _cards = [ > ("1", 1), > ("2", 2), > ("3", 3), > ("4", 4), > ("5", 5), > ("6", 6), > ("7", 7), > ("8", 8), > ("9", 9), > ("10", 0), > ("J", 0), > ("Q", 0), > ("K", 0), > ("A", 1), > ] > > class Card(object): > ? ?def __init__(self, name, value): > ? ? ? ?self.name = name > ? ? ? ?self.value = value > > cards = [Card(n, v) for n, v in _cards] > > class Shoe(list): > ? ?"""A collection of 8 decks of cards""" > ? ?def __init__(self): > ? ? ? ?self[:] = cards*(4*8) > ? ? ? ?random.shuffle(self) > ? ?#... > > Once you have unittests in place you can try and replace your Card > implementation with mine and see if your script continues to work correctly. > > Last and least: > > - I ran your script and got an UnboundLocalError (I'm sorry I didn't keep > the traceback); there must be a code path in main() where last_card is > undefined. Try to separate the program logic from the user interface. This > makes it easier to identify and reproduce problems in the program logic and > to write tests to prevent them in the future. > > - random.choice() takes a list argument > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Fantastic! I will check all those out. Thanks again From beachkidken at gmail.com Sat Dec 17 16:19:37 2011 From: beachkidken at gmail.com (Ken G.) Date: Sat, 17 Dec 2011 10:19:37 -0500 Subject: [Tutor] Weird Error Message-ID: <4EECB309.6030603@gmail.com> I have use 'sleep.time(5)' in most of my program but the following error is throwing me for a loss. import time Traceback (most recent call last): File "/home/ken/Python2/Blood Glucose/BloodGlucose04ReadingTimed.py", line 63, in time.sleep(2) AttributeError: 'str' object has no attribute 'sleep' Using the following is okay: import time print "Now" time.sleep(2) print "Later" From __peter__ at web.de Sat Dec 17 16:40:48 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 17 Dec 2011 16:40:48 +0100 Subject: [Tutor] Weird Error References: <4EECB309.6030603@gmail.com> Message-ID: Ken G. wrote: > I have use 'sleep.time(5)' in most of my program but the following error > is throwing me for a loss. > > import time > Traceback (most recent call last): > File "/home/ken/Python2/Blood Glucose/BloodGlucose04ReadingTimed.py", > line 63, in > time.sleep(2) > AttributeError: 'str' object has no attribute 'sleep' > > Using the following is okay: > > import time > print "Now" > time.sleep(2) > print "Later" Look for an assignment like time = "whatever" in module BloodGlucose04ReadingTimed.py. From shrvtsnvs at gmail.com Sat Dec 17 16:45:50 2011 From: shrvtsnvs at gmail.com (Shrivats) Date: Sat, 17 Dec 2011 21:15:50 +0530 Subject: [Tutor] Weird Error In-Reply-To: <4EECB309.6030603@gmail.com> References: <4EECB309.6030603@gmail.com> Message-ID: <20111217154549.GA5716@zorander> Hello, On Sat, Dec 17, 2011 at 10:19:37AM -0500, Ken G. wrote: > I have use 'sleep.time(5)' in most of my program but the following error > is throwing me for a loss. > > import time > Traceback (most recent call last): > File "/home/ken/Python2/Blood Glucose/BloodGlucose04ReadingTimed.py", > line 63, in > time.sleep(2) > AttributeError: 'str' object has no attribute 'sleep' Here's your clue: Do you have another string variable that apparently goes by the name 'time' ? I have added another line to your snippet below. Running that will throw the same error you see above. > > Using the following is okay: > > import time > print "Now" time="hello" > time.sleep(2) > print "Later" > HTH, Shrivats From beachkidken at gmail.com Sat Dec 17 18:11:26 2011 From: beachkidken at gmail.com (Ken G.) Date: Sat, 17 Dec 2011 12:11:26 -0500 Subject: [Tutor] Weird Error In-Reply-To: References: <4EECB309.6030603@gmail.com> Message-ID: <4EECCD3E.8020006@gmail.com> On 12/17/2011 10:40 AM, Peter Otten wrote: > Ken G. wrote: > >> I have use 'sleep.time(5)' in most of my program but the following error >> is throwing me for a loss. >> >> import time >> Traceback (most recent call last): >> File "/home/ken/Python2/Blood Glucose/BloodGlucose04ReadingTimed.py", >> line 63, in >> time.sleep(2) >> AttributeError: 'str' object has no attribute 'sleep' >> >> Using the following is okay: >> >> import time >> print "Now" >> time.sleep(2) >> print "Later" > Look for an assignment like > > time = "whatever" > > in module BloodGlucose04ReadingTimed.py. Whew! I search for "time" in the program and yes, I did have time as an assignment in several places in the program prior to using time.sleep. Changed the assigned time to timing. Thanks guys. Ken From coolankur2006 at gmail.com Sat Dec 17 19:00:05 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Sat, 17 Dec 2011 23:30:05 +0530 Subject: [Tutor] Github Pygame Example Repository Message-ID: I have created an pygame example repo on github to promote the learning of this API. check this out https://github.com/ankur0890/Pygame-Examples-For-Learning . I created an blog post of the same on my linux blog : http:.//flossstuff.wordpress.com/2011/12/17/github-repository-for-pygame-examples/ . Suggestions and feedback would be great. Looking for contribution too :) Regards Ankur Aggarwal From stm.at.oc at googlemail.com Sat Dec 17 21:30:17 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Sat, 17 Dec 2011 21:30:17 +0100 Subject: [Tutor] unsupported operand Message-ID: Hi there, I would like to define concentration array based on time and then plot it. Here is the profile: from pylab import * import numpy import array import math tmax=1*3600 t = 1. outfile=open('ourtest_out.list','w') N = 100 Conc1 = arange([0, tmax]) outfile.close() lw = 2.0 #linewidth dpi = 96 figure(figsize=(12,6),dpi=dpi) pyplot.plot(Conc1, t,'r-',label='Conc' ) savefig('Conc.png') show() and this is the error that I got: TypeError: unsupported operand type(s) for -: 'list' and 'int' What would you suggest? Thank you, Sue From bodsda at googlemail.com Sat Dec 17 23:11:34 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Sat, 17 Dec 2011 22:11:34 +0000 Subject: [Tutor] unsupported operand In-Reply-To: References: Message-ID: <1327943704-1324159889-cardhu_decombobulator_blackberry.rim.net-565896635-@b14.c12.bise7.blackberry> I would suggest a few things, like variable naming style consistency or the unused file that you open and close. You also have an unused lw variable, and does dpi really need to be a variable? Its only used once, why not hard code it. But the main thing I suggest, is posting the 'complete' traceback, so we can see what caused the error. I'm gonna take a wild guess at it being the pyplot.plot call though, due to the data types that its moaning about. Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: stm atoc Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Sat, 17 Dec 2011 21:30:17 To: tutor Subject: [Tutor] unsupported operand Hi there, I would like to define concentration array based on time and then plot it. Here is the profile: from pylab import * import numpy import array import math tmax=1*3600 t = 1. outfile=open('ourtest_out.list','w') N = 100 Conc1 = arange([0, tmax]) outfile.close() lw = 2.0 #linewidth dpi = 96 figure(figsize=(12,6),dpi=dpi) pyplot.plot(Conc1, t,'r-',label='Conc' ) savefig('Conc.png') show() and this is the error that I got: TypeError: unsupported operand type(s) for -: 'list' and 'int' What would you suggest? Thank you, Sue _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From beachkidken at gmail.com Sat Dec 17 23:14:11 2011 From: beachkidken at gmail.com (Ken G.) Date: Sat, 17 Dec 2011 17:14:11 -0500 Subject: [Tutor] Github Pygame Example Repository In-Reply-To: References: Message-ID: <4EED1433.9070104@gmail.com> The second link should be read as follow: http://flossstuff.wordpress.com/2011/12/17/github-repository-for-pygame-examples/ You had an extra period after http: Ken On 12/17/2011 01:00 PM, ANKUR AGGARWAL wrote: > I have created an pygame example repo on github to promote the > learning of this API. check this out > https://github.com/ankur0890/Pygame-Examples-For-Learning . I created > an blog post of the same on my linux blog : > http:.//flossstuff.wordpress.com/2011/12/17/github-repository-for-pygame-examples/ > . Suggestions and feedback would be great. Looking for contribution > too :) > > Regards > Ankur Aggarwal > From steve at pearwood.info Sun Dec 18 02:07:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Dec 2011 12:07:27 +1100 Subject: [Tutor] unsupported operand In-Reply-To: References: Message-ID: <4EED3CCF.3000906@pearwood.info> stm atoc wrote: > and this is the error that I got: Would you like us to guess which line causes the error? Please show the ENTIRE traceback. Do not retype it from memory, paraphrase or simplify it, or otherwise change it in any way. Copy and paste it. > TypeError: unsupported operand type(s) for -: 'list' and 'int' > > What would you suggest? The code sample you showed did not include any subtractions. This hints that perhaps you are not showing us all of the code you are actually running. The full traceback will answer that one way or the other. Otherwise, I suggest you look at the line which the traceback prints. It probably has something like "result = a - b" (or some other subtraction). Look for the two variables: one of them is set to a list. -- Steven From lina.lastname at gmail.com Sun Dec 18 06:08:07 2011 From: lina.lastname at gmail.com (lina) Date: Sun, 18 Dec 2011 13:08:07 +0800 Subject: [Tutor] where does the ViewerFrameWorkGUI come from Message-ID: Hi, I met below issue: File "/usr/lib/python2.7/dist-packages/ViewerFramework/VF.py", line 369, in __init__ self.GUI = ViewerFrameworkGUI(self, title=title, NameError: global name 'ViewerFrameworkGUI' is not defined can someone tell me how to examine, I mean, how to examine, what would you do when you face the problem? Thanks with best regards, From steve at pearwood.info Sun Dec 18 09:32:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Dec 2011 19:32:34 +1100 Subject: [Tutor] where does the ViewerFrameWorkGUI come from In-Reply-To: References: Message-ID: <4EEDA522.1010300@pearwood.info> lina wrote: > Hi, > > I met below issue: > > File "/usr/lib/python2.7/dist-packages/ViewerFramework/VF.py", line > 369, in __init__ > self.GUI = ViewerFrameworkGUI(self, title=title, > NameError: global name 'ViewerFrameworkGUI' is not defined Is VF.py your code? If so, you have a bug in the code. If not, then *possibly* there is a bug in the ViewerFramework package. Or more likely you are aren't using it correctly. My guess is that you haven't initialised the framework correctly. Read the documentation for it. > can someone tell me how to examine, > > I mean, how to examine, what would you do when you face the problem? Read the documentation. Check your code. Google for the error message and see if other people are having it. What are you doing that leads to the error? Do something different. If there is a forum specifically for the ViewerFramework package, ask there. If not, write to the author. -- Steven From charleshbecker at gmail.com Sun Dec 18 12:28:42 2011 From: charleshbecker at gmail.com (Charles Becker) Date: Sun, 18 Dec 2011 04:28:42 -0700 Subject: [Tutor] Memory and functions Message-ID: <730C3AF9-E82D-4113-8625-B9E3D6603FAF@gmail.com> I have a rather obscure question, and not sure where in the docs to find an answer like this. For functions that return values (ie the list method pop): If you don't assign the returned value to anything does it still end up residing in memory? Just seems like this could be a potential problem to watch out for when memory usage is an issue (probably not most of the time). Also, where can I begin to find these 'lower level' answers in the docs? Thanks! Charles From steve at pearwood.info Sun Dec 18 13:02:10 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Dec 2011 23:02:10 +1100 Subject: [Tutor] Memory and functions In-Reply-To: <730C3AF9-E82D-4113-8625-B9E3D6603FAF@gmail.com> References: <730C3AF9-E82D-4113-8625-B9E3D6603FAF@gmail.com> Message-ID: <4EEDD642.6010704@pearwood.info> Charles Becker wrote: > I have a rather obscure question, and not sure where in the docs to find an answer like this. > > For functions that return values (ie the list method pop): If you don't assign the returned value to anything does it still end up residing in memory? Just seems like this could be a potential problem to watch out for when memory usage is an issue (probably not most of the time). Python is a modern language with a garbage collector. That means that behind the scenes Python deletes objects which are no longer in use. So the short answer is, yes, if you don't assign the returned value, it will be deleted by the garbage collector and you don't normally have to worry about it. > Also, where can I begin to find these 'lower level' answers in the docs? Mostly in the source code. Otherwise, scattered all over the documentation: it depends on what you consider "lower level". If you're familiar with C, or just curious, you might read this part: http://docs.python.org/extending/extending.html#reference-counts -- Steven From __peter__ at web.de Sun Dec 18 13:07:35 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 18 Dec 2011 13:07:35 +0100 Subject: [Tutor] Memory and functions References: <730C3AF9-E82D-4113-8625-B9E3D6603FAF@gmail.com> Message-ID: Charles Becker wrote: > For functions that return values (ie the list method pop): If you don't > assign the returned value to anything does it still end up residing in > memory? Just seems like this could be a potential problem to watch out > for when memory usage is an issue (probably not most of the time). Every object in CPython has a counter to keep track how many times it is referenced. When this counter drops to zero the object is destroyed and the memory is available for reuse. This is simple and works most of the time except when there are reference cycles. Consider: class A: pass a = A() b = A() a.other = b b.other = a del a del b There is now no way for your program to reach a or b, but the reference counter of a is still one because it is referenced by b as b.other, and the reference counter of b is still one because it's referenced by a. Therefore CPython has another mechanism called garbage collection as a backup that periodically searches for reference cycles. While the specific mechanism described above is only implemented in CPython all variants (pypy, jython, ironpython) guarantee that you don't have to bother about object lifetime. From wprins at gmail.com Sun Dec 18 21:28:51 2011 From: wprins at gmail.com (Walter Prins) Date: Sun, 18 Dec 2011 20:28:51 +0000 Subject: [Tutor] where does the ViewerFrameWorkGUI come from In-Reply-To: References: Message-ID: Lina, On 18 December 2011 05:08, lina wrote: > Hi, > > I met below issue: > > File "/usr/lib/python2.7/dist-packages/ViewerFramework/VF.py", line > 369, in __init__ > ? ?self.GUI = ViewerFrameworkGUI(self, title=title, > NameError: global name 'ViewerFrameworkGUI' is not defined > > > can someone tell me how to examine, > > I mean, how to examine, what would you do when you face the problem? You should be telling us what you're doing, what platform you're using, what packages you've installed and so on, and not be leaving us to guess these things. It makes our job harder than it would otherwise be. That said, I've spent only a few minutes to troubleshoot this and will outline what I did so you can see "what I did when faced with this problem": 1.) Some googling reveals to me that ViewerFramework/VF.py apparently forms part of a molecular visualization package called mgltools-viewerframework. 2.) OK so Installing this package yields the same files in the same location on my Ubuntu 11.10 box. 3.) Trying to see what was going on, I then when on to inspect the referenced source file at line 369, where it becomes apparent that the code is trying instantiate a class ViewerFrameworkGUI. 4.) The question then occurs: Where does this class come from? How is it that it's not defined? Consequently I started searching for this class, firstly in the same file, so see where it may be defined or where it might be imported from. 5.) Doing so I found the following code at line 221 in VF.py: try: from ViewerFramework.VFGUI import ViewerFrameworkGUI except: pass "Curious", I thought, how is it that this module can fail to import this class? And why is it squashing the exception? Generally I would consider this type of behaviour very undersireable. Far better would be to stub or mock out the class with a fake that gives some useful behaviour if it's instantiated (e.g. even if just to give some sensible error message to the end user...) but perhaps this is a semi-standard way of stubbing out optional extensions to packages in Python. 6.) So next I decided to manually replicate the aboev import in the Python interpreter to see what would happen: walterp at s1:/usr/lib/python2.7/dist-packages/ViewerFramework$ python Python 2.7.2+ (default, Oct 4 2011, 20:06:09) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ViewerFramework.VFGUI import ViewerFrameworkGUI Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/dist-packages/ViewerFramework/VFGUI.py", line 21, in import Tkinter, thread, string, Pmw, types ImportError: No module named Pmw >>> "Well then, what's this 'Pmw' that's missing?" I thought to myself. A quick google later and I found it: http://pmw.sourceforge.net/ 7.) OK, so that import will fail with an exception due to Pmw being missing (if it's not installed), but it'll go unnoticed due to the exception handler squashing it. This however means that the ViewerFrameworkGUI class is not always defined, which will cause other stuff depending on it to fail mysteriously (as you've found.) At this point, not knowing anything about the packages involved, I'd tentatively suggest that perhaps the Pmw package should be a dependency of the mgltools-viewerframework, and it not being might be an omission/bug in the package. Then again maybe they deliberately don't want the mgltools-viewerframework package to be neccesarily dependant on the Pmw package but keep it optional. Whatever the case is, the bottom line is that you need it in order to solve this issue... 8.) Knowing that oftentimes python modules are packaged on Debian based systems (like Ubuntu) as python-xxx I then tried: sudo apt-get install python-pmw ... and voila, the Pmw module should now be there. 9.) Thus I retried my experiment to manually import ViewerFrameworkGUI as before: walterp at s1:/usr/lib/python2.7/dist-packages/ViewerFramework$ python Python 2.7.2+ (default, Oct 4 2011, 20:06:09) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ViewerFramework.VFGUI import ViewerFrameworkGUI Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/dist-packages/ViewerFramework/VFGUI.py", line 22, in from PIL import Image, ImageTk ImportError: cannot import name ImageTk "Hmmm, so now it's not finding the ImageTk class from the PIL library for some reason" I thought. "Why might that be...?" I checked and I did in fact have the PIL library already installed, so it wasn't that PIL wasn't there at all. (This should've been expected since if PIL wasn't there at all, then presulably importing "Image" would've also failed...) A little bit of further googling and I find some evidence that ImageTk was (for whatever reason) seperated into its own package with the advent of Python 2.6 (See http://www.python-forum.org/pythonforum/viewtopic.php?f=4&p=65248 and https://bugzilla.redhat.com/show_bug.cgi?id=247171 ) and that I should install the python-imaging-tk package to get the Python module containing ImageTk. 10.) So I did: sudo apt-get install python-imaging-tk This then solved the ImageTk import issue, but left me with more issues. (I seem to be missing other "mgltools" related packages.) I'm however not terribly interested in troubleshooting this further on my box as I've got no use for these things and since what I've posted should solve your immediate issue and gives you an insight how I tackled your issue and you may not even have these other issues I'm going to leave it at that for now. Walter From rshack at xtra.co.nz Sun Dec 18 23:06:38 2011 From: rshack at xtra.co.nz (Russell Shackleton) Date: Mon, 19 Dec 2011 11:06:38 +1300 (NZDT) Subject: [Tutor] 'str' object has no attribute 'description' Message-ID: <1324245998.98105.YahooMailClassic@web96001.mail.aue.yahoo.com> I am learning Python classes by writing an adventure game. I have extracted just the relevant code. The player can look, go, drop, take, inventory but not examine. Python produces the error message in the Player class, examine function, in the first print statement. How do I fix this code, please? class Player(object): """The player in the game.""" def __init__(self, name, currentRoom=None): self.name = name self.currentRoom = currentRoom self.items = [] # items taken by Player def look(self): """Prints the room description, exits and items in the current room.""" print self.currentRoom def go(self, direction): """Go to another room through an exit.""" def drop(self, item): """Drop an item you are carrying in the current room.""" def take(self, item): """Take (pick up) an item from the current room.""" if item == self.currentRoom.item: self.items.append(item) print self.currentRoom.item + " added to player's inventory..\n" # remove item from currentRoom self.currentRoom.item = '' else: print "There is no " + item + " here to take!\n" def inventory(self): """Prints list of items the player is carrying.""" def examine(self, item): """Prints description of item.""" if item in self.items: # Error: 'str' object has no attribute 'description' print "Item Description: " + item.description + ".\n" else: print "You are not holding the " + item + " to examine!\n" class Item(object): """A useful item in the game.""" def __init__(self, name, description, location): self.name = name self.description = description self.location = location def __str__(self): """Description of item.""" return self.description class Game(object): """The adventure game.""" def __init__(self, name, player): self.name = name self.player = player print "Welcome to " + self..name + "\n" print player.currentRoom def play(self, character): """Command loop for game.""" while True: # loop forever commands = raw_input("-> ").lower() if not commands: print "Huh?" else: try: cmdlist = commands.split() # separate commands action = cmdlist[0] if action == "quit": print "See you later!" break elif action == "look": elif action == "go": elif action == "take": elif action == "drop": elif action == "examine": if len(cmdlist) != 2: print "An examine command must be followed by an item name." continue else: character.examine(cmdlist[1]) elif action == "inventory": except AttributeError, msg: print "Error - undefined method: " + str(msg) def main(): # Room descriptions room5 = Room(name="hallway", description="You are in a dark hallway.", item="diary") # Item descriptions diary = Item(name="diary", description="grey-covered Croxley diary", location=room5) From waynejwerner at gmail.com Sun Dec 18 23:23:36 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 18 Dec 2011 16:23:36 -0600 Subject: [Tutor] 'str' object has no attribute 'description' In-Reply-To: <1324245998.98105.YahooMailClassic@web96001.mail.aue.yahoo.com> References: <1324245998.98105.YahooMailClassic@web96001.mail.aue.yahoo.com> Message-ID: On Sun, Dec 18, 2011 at 4:06 PM, Russell Shackleton wrote: > I am learning Python classes by writing an adventure game. I have > extracted just the relevant code. The player can look, go, drop, take, > inventory but not examine. > > Python produces the error message in the Player class, examine function, > in the first print statement. > > It's best to give the full traceback, because it provides an awful lot of information. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From stm.at.oc at googlemail.com Sun Dec 18 23:35:34 2011 From: stm.at.oc at googlemail.com (stm atoc) Date: Sun, 18 Dec 2011 23:35:34 +0100 Subject: [Tutor] unsupported operand In-Reply-To: <4EED3CCF.3000906@pearwood.info> References: <4EED3CCF.3000906@pearwood.info> Message-ID: Well, I tried to check and I do not have that problem any more..but i have the clear script as follows and a couple of question regarding to this: # coding: utf-8 from pylab import * import numpy import matplotlib.pyplot as pyplot import matplotlib.mlab as mlab #tmax=360 with open("ourtest_out.list", "r") as f: t = numpy.array([float(v) for v in f.readline().split()[1:]]) for t, filename in enumerate("ourtest_out.list"): a = numpy.loadtxt("ourtest_out.list", skiprows=3) Conc=[] #Conc = a[:, 200] Conc.append(a[:,200]) #Conc = a[0:, tmax+1:] plot(Conc,t) show() My main problem is, i do try to see the plot of Conc according to time. I have a graph without any data! Basically, I have a program written in FORTRAN including conc, time, etc. calculation. The out put data shows that I do have concentration. However, i am not able to have a plot based on time. I should mention that I did have run the model (fortran) for concentration according to the number of layer (N=200) and defined the concentration like this Conc(0:N). Perhaps the reason that I am not able to see the concentration with time is because of this definition. BUT, still if I do plot based on pyplot.pcolor, I have a nice and seems correct graph. So, actually, I am not sure what is the problem for showing the regular/linear plot. I hope I made it clear now.. Would it be possible to give me some hint please? Thank you in advance, Sue On Sun, Dec 18, 2011 at 2:07 AM, Steven D'Aprano wrote: > stm atoc wrote: > >> and this is the error that I got: > > > Would you like us to guess which line causes the error? > > Please show the ENTIRE traceback. Do not retype it from memory, paraphrase > or simplify it, or otherwise change it in any way. Copy and paste it. > > >> TypeError: unsupported operand type(s) for -: 'list' and 'int' >> >> What would you suggest? > > > The code sample you showed did not include any subtractions. This hints that > perhaps you are not showing us all of the code you are actually running. The > full traceback will answer that one way or the other. > > Otherwise, I suggest you look at the line which the traceback prints. It > probably has something like "result = a - b" (or some other subtraction). > Look for the two variables: one of them is set to a list. > > > -- > Steven > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From hugo.yoshi at gmail.com Sun Dec 18 23:41:39 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 18 Dec 2011 23:41:39 +0100 Subject: [Tutor] 'str' object has no attribute 'description' In-Reply-To: References: <1324245998.98105.YahooMailClassic@web96001.mail.aue.yahoo.com> Message-ID: On Sun, Dec 18, 2011 at 11:23 PM, Wayne Werner wrote: > On Sun, Dec 18, 2011 at 4:06 PM, Russell Shackleton > wrote: >> >> I am learning Python classes by writing an adventure game. I have >> extracted just the relevant code. The player can look, go, drop, take, >> inventory but not examine. >> >> Python produces the error message in the Player class, examine function, >> in the first print statement. >> > > It's best to give the full traceback, because it provides an awful lot of > information. > > -Wayne > Wayne's right. Always give us a full traceback. Where the error finally shows itself is rarely the same as where it's first started, and a traceback can tell us that. That said, you did a pretty good job of removing irrelevant code (thank you!! it helps us a lot! :), and I was able to find your particular error. It starts in this snippet: elif action == "examine": if len(cmdlist) != 2: print "An examine command must be followed by an item name." continue else: character.examine(cmdlist[1]) # <--- right here the problem is that cmdlist is just a list of strings. Hence cmdlist[1] is a string as well. And strings don't have the description attribute, hence python is complaining. What you likely meant is not to examine not the string, but the item object with a name that equals that string. HTH, Hugo From stayvoid at gmail.com Sun Dec 18 23:45:18 2011 From: stayvoid at gmail.com (Stayvoid) Date: Mon, 19 Dec 2011 01:45:18 +0300 Subject: [Tutor] PYTHONPATH (Mac OS X) Message-ID: Hey there! How to set it right? Cheers! From rshack at xtra.co.nz Sun Dec 18 23:49:06 2011 From: rshack at xtra.co.nz (Russell Shackleton) Date: Mon, 19 Dec 2011 11:49:06 +1300 (NZDT) Subject: [Tutor] 'str' object has no attribute 'description' Message-ID: <1324248546.45282.YahooMailClassic@web96003.mail.aue.yahoo.com> I am learning Python classes by writing an adventure game. I have extracted just the relevant code. The player can look, go, drop, take, inventory but not examine. Python produces the error message in the Player class, examine function, in the first print statement. I have added the traceback following a suggestion from Wayne Werner. Traceback (most recent call last): File "adv03.py", line 205, in main() File "adv03.py", line 202, in main game.play(adventurer) File "adv03.py", line 147, in play character.examine(cmdlist[1]) File "adv03.py", line 86, in examine print "Item Description: " + item.description + ".\n" AttributeError: 'str' object has no attribute 'description' [Note: actual line numbers appended in comments in this listing] How do I fix this code, please? class Player(object): """The player in the game.""" def __init__(self, name, currentRoom=None): self.name = name self.currentRoom = currentRoom self.items = [] # items taken by Player def look(self): """Prints the room description, exits and items in the current room.""" print self.currentRoom def go(self, direction): """Go to another room through an exit.""" def drop(self, item): """Drop an item you are carrying in the current room.""" def take(self, item): """Take (pick up) an item from the current room.""" if item == self.currentRoom.item: self.items.append(item) print self.currentRoom.item + " added to player's inventory.\n" # remove item from currentRoom self.currentRoom.item = '' else: print "There is no " + item + " here to take!\n" def inventory(self): """Prints list of items the player is carrying.""" def examine(self, item): """Prints description of item.""" if item in self.items: # Error: 'str' object has no attribute 'description' print "Item Description: " + item.description + ".\n" # line 86 else: print "You are not holding the " + item + " to examine!\n" class Item(object): """A useful item in the game.""" def __init__(self, name, description, location): self.name = name self.description = description self.location = location def __str__(self): """Description of item.""" return self.description class Game(object): """The adventure game.""" def __init__(self, name, player): self.name = name self.player = player print "Welcome to " + self.name + "\n" print player.currentRoom def play(self, character): """Command loop for game.""" while True: # loop forever commands = raw_input("-> ").lower() if not commands: print "Huh?" else: try: cmdlist = commands.split() # separate commands action = cmdlist[0] if action == "quit": print "See you later!" break elif action == "look": elif action == "go": elif action == "take": elif action == "drop": elif action == "examine": if len(cmdlist) != 2: print "An examine command must be followed by an item name." continue else: character.examine(cmdlist[1]) # line 147 elif action == "inventory": except AttributeError, msg: print "Error - undefined method: " + str(msg) def main(): # Room descriptions room5 = Room(name="hallway", description="You are in a dark hallway.", item="diary") # Item descriptions diary = Item(name="diary", description="grey-covered Croxley diary", location=room5) game.play(adventurer) # line 202 From waynejwerner at gmail.com Mon Dec 19 00:15:10 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 18 Dec 2011 17:15:10 -0600 Subject: [Tutor] sqlite3: turning on foreign key support thru python In-Reply-To: References: Message-ID: On Fri, Dec 16, 2011 at 1:43 PM, Modulok wrote: > >> How do I tell if it succeeded (short of trying an operation that should > be > >> blocked by foreign keys)? How do I use that cursor object returned by > the > >> pragma query to tell if its a '1' (on) or a '0' (off) and verify the > state? > > > The cursor object contains the result set. It's a python generator object. > (Or > at least a generator interface.) You have to iterate over it in order to > see > the resulting rows which are stored as a tuple. Not all operations return a > result row. (For example, conn.execute('pragma foreign_keys=ON' will > return a > cursor object, but it won't generate any result rows, as there were > none returned by the database.) > > To see the result of your second command, do something like this:: > > rows = conn.execute('pragma foreign_keys') > for r in rows: > print r > If you're mucking about in the interactive prompt, and you just want to see the results quickly you can just turn it into a tuple or a list (list would be less typing): print(list(rows)) or just list(rows) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Dec 19 00:21:47 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 18 Dec 2011 17:21:47 -0600 Subject: [Tutor] reset password program In-Reply-To: References: <4EEBE786.6090509@pearwood.info> Message-ID: On Fri, Dec 16, 2011 at 7:17 PM, Robert Sjoblom wrote: > > Some improvements to think about, in order of least secure (easiest) to > most > > secure (hardest). > > > > (1) "my secret password.txt" is a crappy name. Is there a better name? > > I'm going to go with "EULA.txt"; the reasons should be obvious. +1, because I laughed. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Dec 19 00:41:29 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 18 Dec 2011 17:41:29 -0600 Subject: [Tutor] 'str' object has no attribute 'description' In-Reply-To: <1324248546.45282.YahooMailClassic@web96003.mail.aue.yahoo.com> References: <1324248546.45282.YahooMailClassic@web96003.mail.aue.yahoo.com> Message-ID: On Sun, Dec 18, 2011 at 4:49 PM, Russell Shackleton wrote: > I am learning Python classes by writing an adventure game. I have > extracted just the relevant code. The player can look, go, drop, take, > inventory but not examine. > > Python produces the error message in the Player class, examine function, > in the first print statement. > > I have added the traceback following a suggestion from Wayne Werner. > That's much more useful. As a slight aside, it probably would have been better to just reply-all to the original thread with the traceback. > > Traceback (most recent call last): > File "adv03.py", line 205, in > main() > File "adv03.py", line 202, in main > game.play(adventurer) > File "adv03.py", line 147, in play > character.examine(cmdlist[1]) > File "adv03.py", line 86, in examine > print "Item Description: " + item.description + ".\n" > AttributeError: 'str' object has no attribute 'description' > [Note: actual line numbers appended in comments in this listing] > > This is *much* more helpful - I don't even need to see your code to tell you what went wrong. I don't know if you've worked with other programming languages with nearly useless stack traces, but in Python you'll find that they're (usually) very high quality. In this case it tells you a few things. First, it tells you where it happened with this line: > File "adv03.py", line 86, in examine It happened in the file adv03.py, on line 86, in a function (or method) called "examine". The next two lines tell you what blew up, and why it did: print "Item Description: " + item.description + ".\n" > AttributeError: 'str' object has no attribute 'description' 'str' object has no attribute 'description'. Well if you look on the line before that the only description attribute you try to look up is item.description. So if 'str' doesn't have that attribute then item must be a string. With that in mind, let's take a look at that function: def examine(self, item): > """Prints description of item.""" > if item in self.items: > # Error: 'str' object has no attribute 'description' > print "Item Description: " + item.description + ".\n" # line 86 > else: > print "You are not holding the " + item + " to examine!\n" This looks pretty straightforward. You pass something in as item, and check to see if it's contained in your list of items. If it is, then you print out the description, otherwise you print out whatever you passed in. And so if we rewind back to where you call the function: character.examine(cmdlist[1]) # line 147 What is cmdlist? A list of strings. What is contained in cmdlist[1]? If you still have issues fixing this, please let us know. HTH, Wayne How do I fix this code, please? > > class Player(object): > """The player in the game.""" > def __init__(self, name, currentRoom=None): > self.name = name > self.currentRoom = currentRoom > self.items = [] # items taken by Player > > def look(self): > """Prints the room description, exits and items in the current > room.""" > print self.currentRoom > > def go(self, direction): > """Go to another room through an exit.""" > > def drop(self, item): > """Drop an item you are carrying in the current room.""" > > def take(self, item): > """Take (pick up) an item from the current room.""" > if item == self.currentRoom.item: > self.items.append(item) > print self.currentRoom.item + " added to player's inventory.\n" > # remove item from currentRoom > self.currentRoom.item = '' > else: > print "There is no " + item + " here to take!\n" > > def inventory(self): > """Prints list of items the player is carrying.""" > > def examine(self, item): > """Prints description of item.""" > if item in self.items: > # Error: 'str' object has no attribute 'description' > print "Item Description: " + item.description + ".\n" # line 86 > else: > print "You are not holding the " + item + " to examine!\n" > > class Item(object): > """A useful item in the game.""" > def __init__(self, name, description, location): > self.name = name > self.description = description > self.location = location > > def __str__(self): > """Description of item.""" > return self.description > > class Game(object): > """The adventure game.""" > def __init__(self, name, player): > self.name = name > self.player = player > print "Welcome to " + self.name + "\n" > print player.currentRoom > > def play(self, character): > """Command loop for game.""" > while True: # loop forever > commands = raw_input("-> ").lower() > if not commands: > print "Huh?" > else: > try: > cmdlist = commands.split() # separate commands > action = cmdlist[0] > if action == "quit": > print "See you later!" > break > elif action == "look": > elif action == "go": > elif action == "take": > elif action == "drop": > elif action == "examine": > if len(cmdlist) != 2: > print "An examine command must be followed by > an item name." > continue > else: > character.examine(cmdlist[1]) # line 147 > elif action == "inventory": > except AttributeError, msg: > print "Error - undefined method: " + str(msg) > > def main(): > # Room descriptions > room5 = Room(name="hallway", description="You are in a dark hallway.", > item="diary") > > # Item descriptions > diary = Item(name="diary", description="grey-covered Croxley diary", > location=room5) > > game.play(adventurer) # line 202 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Dec 19 01:28:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Dec 2011 00:28:54 +0000 Subject: [Tutor] unsupported operand In-Reply-To: References: <4EED3CCF.3000906@pearwood.info> Message-ID: On 18/12/11 22:35, stm atoc wrote: > Well, I tried to check and I do not have that problem any more..but i > have the clear script as follows and a couple of question regarding to > this: > > # coding: utf-8 > from pylab import * > import numpy > import matplotlib.pyplot as pyplot > import matplotlib.mlab as mlab > #tmax=360 > > with open("ourtest_out.list", "r") as f: > t = numpy.array([float(v) for v in f.readline().split()[1:]]) > > for t, filename in enumerate("ourtest_out.list"): > a = numpy.loadtxt("ourtest_out.list", skiprows=3) You do realize that you are throwing away the t that you created above? And I'm pretty sure this loop is not doing what you think it is... Lets try an experiment at the >?>> prompt: >>> for t,f in enumerate('testing'): ... print t,f ... 0 t 1 e 2 s 3 t 4 i 5 n 6 g Is that what you would have expected? > Conc=[] > Conc.append(a[:,200]) What is a? > plot(Conc,t) > show() HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Dec 19 01:41:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Dec 2011 00:41:35 +0000 Subject: [Tutor] 'str' object has no attribute 'description' In-Reply-To: <1324245998.98105.YahooMailClassic@web96001.mail.aue.yahoo.com> References: <1324245998.98105.YahooMailClassic@web96001.mail.aue.yahoo.com> Message-ID: On 18/12/11 22:06, Russell Shackleton wrote: > I have extracted just the relevant code. Its possible you extracted too much but.... > class Player(object): > """The player in the game.""" > def __init__(self, name, currentRoom=None): > def take(self, item): > """Take (pick up) an item from the current room.""" > if item == self.currentRoom.item: > self.items.append(item) > print self.currentRoom.item + " added to player's inventory..\n" > # remove item from currentRoom > self.currentRoom.item = '' Here at least you are making item a string rather than an Item() > def examine(self, item): > """Prints description of item.""" > if item in self.items: > # Error: 'str' object has no attribute 'description' > print "Item Description: " + item.description + ".\n" And here you access the item.description which doesn';t exist for strings. But you could get rounfd that by converting item to a str(). Then if it is an Item instance your __str__ method gets called - thats why you defined it right? - and if its already a string the same string gets returned... > print "You are not holding the " + item + " to examine!\n" > class Item(object): > """A useful item in the game.""" > def __init__(self, name, description, location): > self.name = name > self.description = description > self.location = location > > def __str__(self): > """Description of item.""" > return self.description > > class Game(object): > def play(self, character): > > def main(): > # Room descriptions > room5 = Room(name="hallway", description="You are in a dark hallway.", item="diary") > Notice that the item is just a strinng, not the diary object. Which doesn't actually exist yet anyhow! > # Item descriptions > diary = Item(name="diary", description="grey-covered Croxley diary", location=room5) This appears to be the only place you ever instantiate an Item? But this is not what you assigned to room5... So you are not assigning Items to the rooms. Unless its in the code you deleted? HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Mon Dec 19 04:04:53 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 18 Dec 2011 22:04:53 -0500 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: Message-ID: <4EEEA9D5.70605@gmail.com> On 12/18/2011 5:45 PM, Stayvoid wrote: > Hey there! > > How to set it right? You may not get an answer as your question is pretty vague. Please clarify, or expand, or tell us what problem you are having or trying to solve. -- Bob Gailer 919-636-4239 Chapel Hill NC From lina.lastname at gmail.com Mon Dec 19 04:47:10 2011 From: lina.lastname at gmail.com (lina) Date: Mon, 19 Dec 2011 11:47:10 +0800 Subject: [Tutor] where does the ViewerFrameWorkGUI come from In-Reply-To: References: Message-ID: On Mon, Dec 19, 2011 at 4:28 AM, Walter Prins wrote: > Lina, Hi Walter, I am sorry, before I posted I did not realize people would get much attention to do all following as you did. Thanks, Well, yesterday I posted a bug report and later during my waiting, based on it's also python related, so I was interested in digging further, googled showed me "uninstall python 2.6 and re-install autodocktools will solve this problem" (but later checked, it's not a sound/logical way of solving this problem, might with my luck/careless, during this process, something was fixed) before uninstall python2.6, the VF.py, well, when I tried to grep ViewerFrameworkGUI, it shows no results, but used ViewerFramework, after I removal of python2.6, during re-installation of autodocktools, the relevant depedence package (), in the situation without 2.6, I checked the VF.py, now it has the ViewerFrameworkGUI, not ViewerFramework. and then I installed 2.6, as you can see in my box, both /usr/lib/python2.7/dist-packages/ViewerFramework/VF.py /usr/lib/python2.6/dist-packages/ViewerFramework/VF.py all symbolic links to /usr/share/pyshared/ViewerFramework/VF.py I still don't understand what's going on. and it's pretty weird, before I cat VF.py | grep ViewerFrameworkGUI, it showed no result, but now it has. and most weird is that I noticed the -rw-r--r-- 1 root root 62177 Aug 18 06:38 VF.py it's been month ago, seems nothing changed. even yesterday I also remove and re-install the mgltools-viewerframework. 2011-12-18 13:15:06 remove mgltools-viewerframework 1.5.6~rc2+cvs.20110926-1 2011-12-18 13:56:00 install mgltools-viewerframework 1.5.6~rc2+cvs.20110926-1 Thanks with best regards, > > On 18 December 2011 05:08, lina wrote: >> Hi, >> >> I met below issue: >> >> File "/usr/lib/python2.7/dist-packages/ViewerFramework/VF.py", line >> 369, in __init__ >> ? ?self.GUI = ViewerFrameworkGUI(self, title=title, >> NameError: global name 'ViewerFrameworkGUI' is not defined >> >> >> can someone tell me how to examine, >> >> I mean, how to examine, what would you do when you face the problem? > > You should be telling us what you're doing, what platform you're > using, what packages you've installed and so on, and not be leaving us > to guess these things. ?It makes our job harder than it would > otherwise be. ?That said, I've spent only a few minutes to > troubleshoot this and will outline what I did so you can see "what I > did when faced with this problem": > > 1.) Some googling reveals to me that ViewerFramework/VF.py apparently > forms part of a molecular visualization package called > mgltools-viewerframework. > 2.) OK so Installing this package yields the same files in the same > location on my Ubuntu 11.10 box. > 3.) Trying to see what was going on, I then when on to inspect the > referenced source file at line 369, where it becomes apparent that the > code is trying instantiate a class ViewerFrameworkGUI. > 4.) The question then occurs: Where does this class come from? ?How is > it that it's not defined? ?Consequently I started searching for this > class, firstly in the same file, so see where it may be defined or > where it might be imported from. > 5.) Doing so I found the following code at line 221 in VF.py: > try: > ? ?from ViewerFramework.VFGUI import ViewerFrameworkGUI > except: > ? ?pass > > "Curious", I thought, how is it that this module can fail to import > this class? ?And why is it squashing the exception? ?Generally I would > consider this type of behaviour very undersireable. ?Far better would > be to stub or mock out the class with a fake that gives some useful > behaviour if it's instantiated (e.g. even if just to give some > sensible error message to the end user...) but perhaps this is a > semi-standard way of stubbing out optional extensions to packages in > Python. > > 6.) So next I decided to manually replicate the aboev import in the > Python interpreter to see what would happen: > walterp at s1:/usr/lib/python2.7/dist-packages/ViewerFramework$ python > Python 2.7.2+ (default, Oct ?4 2011, 20:06:09) > [GCC 4.6.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from ViewerFramework.VFGUI import ViewerFrameworkGUI > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python2.7/dist-packages/ViewerFramework/VFGUI.py", > line 21, in > ? ?import Tkinter, thread, string, Pmw, types > ImportError: No module named Pmw >>>> > > "Well then, what's this 'Pmw' that's missing?" I thought to myself. ?A > quick google later and I found it: http://pmw.sourceforge.net/ > > 7.) OK, so that import will fail with an exception due to Pmw being > missing (if it's not installed), but it'll go unnoticed due to the > exception handler squashing it. ?This however means that the > ViewerFrameworkGUI class is not always defined, which will cause other > stuff depending on it to fail mysteriously (as you've found.) ?At this > point, not knowing anything about the packages involved, I'd > tentatively suggest that perhaps the Pmw package should be a > dependency of the mgltools-viewerframework, and it not being might be > an omission/bug in the package. ?Then again maybe they deliberately > don't want the mgltools-viewerframework package to be neccesarily > dependant on the Pmw package but keep it optional. ?Whatever the case > is, the bottom line is that you need it in order to solve this > issue... > > 8.) Knowing that oftentimes python modules are packaged on Debian > based systems (like Ubuntu) as python-xxx I then tried: > sudo apt-get install python-pmw > ... and voila, the Pmw module should now be there. > > 9.) Thus I retried my experiment to manually import ViewerFrameworkGUI > as before: > walterp at s1:/usr/lib/python2.7/dist-packages/ViewerFramework$ python > Python 2.7.2+ (default, Oct ?4 2011, 20:06:09) > [GCC 4.6.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from ViewerFramework.VFGUI import ViewerFrameworkGUI > Traceback (most recent call last): > ?File "", line 1, in > ?File "/usr/lib/python2.7/dist-packages/ViewerFramework/VFGUI.py", > line 22, in > ? ?from PIL import Image, ImageTk > ImportError: cannot import name ImageTk > > "Hmmm, so now it's not finding the ImageTk class from the PIL library > for some reason" I thought. ?"Why might that be...?" ?I checked and I > did in fact have the PIL library already installed, so it wasn't that > PIL wasn't there at all. ?(This should've been expected since if PIL > wasn't there at all, then presulably importing "Image" would've also > failed...) > > A little bit of further googling and I find some evidence that ImageTk > was (for whatever reason) seperated into its own package with the > advent of Python 2.6 (See > http://www.python-forum.org/pythonforum/viewtopic.php?f=4&p=65248 and > https://bugzilla.redhat.com/show_bug.cgi?id=247171 ) and that I should > install the python-imaging-tk package to get the Python module > containing ImageTk. > > 10.) So I did: > sudo apt-get install python-imaging-tk > > This then solved the ImageTk import issue, but left me with more > issues. ?(I seem to be missing other "mgltools" related packages.) I'm > however not terribly interested in troubleshooting this further on my > box as I've got no use for these things and since what I've posted > should solve your immediate issue and gives you an insight how I > tackled your issue and you may not even have these other issues I'm > going to leave it at that for now. > > Walter > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From jugurtha.hadjar at gmail.com Mon Dec 19 10:19:38 2011 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Mon, 19 Dec 2011 10:19:38 +0100 Subject: [Tutor] Installing Python and modules In-Reply-To: References: Message-ID: <4EEF01AA.2060606@gmail.com> On 15/12/2011 01:28, Sean Baumgarten wrote: > Hello, > > I'm wondering if someone could walk me step-by-step through installing > Python and some third-party modules. I've never used Python or other > programming languages before, but I'm just trying to install it so I > can run a simple script. I'm running Mac OSX 10.6.8. > > Hello Sean, Installing Python shouldn't be a problem .. I found it more complicated to subscribe to this mailing list than to install it :) .. I think it comes with most of what you need in a single package. I needed recently pyWin, and I downloaded it from Sourceforge. I'll walk in your shoes for a bit (Although I'm on Windows XP 5.1.2600 & Python 3.2) I searched for the term Numpy on Google. The first site it returned was numpy.scipy.org I clicked on Download, I landed on http://new.scipy.org/download.html. I opened two links in new tabs : "SourceForge site for Numpy" & "SourceForge site for Scipy" http://sourceforge.net/projects/numpy/files/ And http://sourceforge.net/projects/scipy/files/ "Looking for the latest version? *Download numpy-1.6.1-win32-superpack-python2.6.exe (6.0 MB) *Looking for the latest version? *Download scipy-0.10.0-win32-superpack-python2.6.exe (46.0 MB) * * *You click on the links (I think the site is OS aware, so you'll probably be given a link for a "dmg" or something if you're on a mac) I see the "python2.6" at the end, I guess it won't work but I'll test for the sake of being certain nevertheless. I click on the numpy-1.6.1 because it's smaller and to test quickly.. (I'm typing as I'm doing, so do some "nop"s while you wait :) ) I launch the installation of numpy-1.6.1 and it says "Python version 2.6 required, which was not found in the registry" in a dialog box titled "Cannot install". I Google "nympy python 3.2" .. The second link seems interesting http://www.wilmott.com/messageview.cfm?catid=10&threadid=83588 The guy posting the question was advised to stick with Python 2.6 or 2.7 and given a link for the FAQ http://new.scipy.org/faq.html#does-numpy-currently-work-with-python-3-x-what-about-scipy I don't know which version of Python you're using. -- ~Jugurtha Hadjar, -------------- next part -------------- An HTML attachment was scrubbed... URL: From bganesh05 at gmail.com Mon Dec 19 16:54:55 2011 From: bganesh05 at gmail.com (Ganesh Borse) Date: Mon, 19 Dec 2011 23:54:55 +0800 Subject: [Tutor] Request for guidance about a python syntax Message-ID: Dear Tutors, I am new to python. I am trying to understand (& use) the python implementation of goertzel implementation provided on http://www.black-aura.com/blog/2011/12/10/python-implementation-of-the-goertzel-algorithm-dtmf-decoding/ . This python program uses unpack_from() function to unpack string into array of ints, with the following statement: frames = struct.unpack_from(*"%dH" % nframes * **nchannels*, frames) I could know the use of unpack_from, but I could not understand the "fmt" part, i.e *"%dH" % nframes * nchannels*. Can you pls help me know, what is the purpose of two "%" signs in this statement? Thanks for your help in advance. Best Regards, banes -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Mon Dec 19 17:15:13 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 19 Dec 2011 11:15:13 -0500 Subject: [Tutor] Request for guidance about a python syntax In-Reply-To: References: Message-ID: On Mon, Dec 19, 2011 at 10:54 AM, Ganesh Borse wrote: > I could know the use of unpack_from, but I could not understand the "fmt" > part, i.e *"%dH" % nframes * nchannels*. > Can you pls help me know, what is the purpose of two "%" signs in this > statement? > > That's python's string formatting. See http://docs.python.org/library/stdtypes.html#string-formatting-operations for details. Basically, it's building the format for the call to unpack_from on the fly. The "%dH" portion is calling for a single decimal value to become part of the string (that's the "%d" portion). That value comes from multiplying nframes by nchannels. So, for example, if nframes = 10 and nchannels = 24, then the string becomes "240H". That, in turn, tells the program to unpack a sequence of 240 unsigned short values from the buffer. -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Dec 19 17:35:00 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 19 Dec 2011 08:35:00 -0800 Subject: [Tutor] A few Python Mysteries Message-ID: <4EEF67B4.6090109@sbcglobal.net> Win 7, 64-bit I had Py 2.5 installed on my PC earlier this year, and it began failing around June. I finally uninstalled it, and tried 2.6. Still had problems that centered around getting to IDLE. Uninstalled 2.6, and went to 2.7. Same problem. I completely uninstalled 2.7. I do have several folders of py programs. No Python. After that episode, I began to notice the following messages when I signed on to my PC after a boot. I do not bring my PC down very often. Specified module could not be found: Loadlib python.dll failed, and another of the same for Python25.dll failed (maybe not found). I did a search for both, but neither were found. I ignored this inconvenience for a few weeks, and had developed a need to copy a particular python program on Win 7 to another computer. Call it abc.py. I copied it to a thumb drive, and plugged the drive into the other PC, which has Python on it. abc.py was missing from the drive. I tried this about three times, and even went to yet another PC. No abc.py. Finally, I pulled xyz.py from an XP PC on to the drive. When I put it on yet another PC, xyz.py was there, and I copied it on to the PC. Very strange. Note again, I did not have Python installed on the Win 7 PC. I have no idea if any of this is relevant to the attempt to install Py on my Win 7 PC, but it and the sign-on msgs may indicate something is twisted in the registry. Comments? It would be nice to get rid of the two msgs upon sign-on. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From eire1130 at gmail.com Mon Dec 19 17:50:17 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 19 Dec 2011 11:50:17 -0500 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EEF67B4.6090109@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> Message-ID: On Mon, Dec 19, 2011 at 11:35 AM, Wayne Watson wrote: > Win 7, 64-bit > > I had Py 2.5 installed on my PC earlier this year, and it began failing > around June. I finally uninstalled it, and tried 2.6. Still had problems > that centered around getting to IDLE. Uninstalled 2.6, and went to 2.7. > Same problem. I completely uninstalled 2.7. I do have several folders of py > programs. No Python. > > After that episode, I began to notice the following messages when I signed > on to my PC after a boot. I do not bring my PC down very often. > > Specified module could not be found: Loadlib python.dll failed, and > another of the same for Python25.dll failed (maybe not found). I did a > search for both, but neither were found. > > I ignored this inconvenience for a few weeks, and had developed a need to > copy a particular python program on Win 7 to another computer. Call it > abc.py. I copied it to a thumb drive, and plugged the drive into the other > PC, which has Python on it. abc.py was missing from the drive. I tried > this about three times, and even went to yet another PC. No abc.py. > > Finally, I pulled xyz.py from an XP PC on to the drive. When I put it on > yet another PC, xyz.py was there, and I copied it on to the PC. Very > strange. Note again, I did not have Python installed on the Win 7 PC. I > have no idea if any of this is relevant to the attempt to install Py on my > Win 7 PC, but it and the sign-on msgs may indicate something is twisted in > the registry. > > Comments? > > It would be nice to get rid of the two msgs upon sign-on. > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > CE 1955 October 20 07:53:32.6 UT > -- "The Date" The mystery unfolds. > > Web Page: > > > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Did you change the PATH to the right directory? It may still be pointing to the old directory, or you may have never set it to begin with. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Dec 19 18:10:40 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 19 Dec 2011 18:10:40 +0100 Subject: [Tutor] Request for guidance about a python syntax References: Message-ID: Jerry Hill wrote: > On Mon, Dec 19, 2011 at 10:54 AM, Ganesh Borse > wrote: > >> I could know the use of unpack_from, but I could not understand the "fmt" >> part, i.e *"%dH" % nframes * nchannels*. >> Can you pls help me know, what is the purpose of two "%" signs in this >> statement? >> >> > That's python's string formatting. See > http://docs.python.org/library/stdtypes.html#string-formatting-operations > for > details. Basically, it's building the format for the call to unpack_from > on the fly. The "%dH" portion is calling for a single decimal value to > become part of the string (that's the "%d" portion). That value comes > from > multiplying nframes by nchannels. So, for example, if nframes = 10 and > nchannels = 24, then the string becomes "240H". That, in turn, tells the > program to unpack a sequence of 240 unsigned short values from the buffer. Close, but % and * have the same operator precedence. Therefore the expression "%dH" % nframes * nchannels is evaluated as (%dH" % nframes) * nchannels So >>> nframes = 2 >>> nchannels = 3 >>> "%dH" % nframes '2H' >>> "%dH" % nframes * nchannels '2H2H2H' The original script still works because multiplying a string by an integer repeats the string, and the format "2H2H2H" is equivalent to "6H", but "%dH" % (nframes * nchannels) is probably a bit more efficient, especially for large values of nchannels. From malaclypse2 at gmail.com Mon Dec 19 19:31:45 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 19 Dec 2011 13:31:45 -0500 Subject: [Tutor] Request for guidance about a python syntax In-Reply-To: References: Message-ID: On Mon, Dec 19, 2011 at 12:10 PM, Peter Otten <__peter__ at web.de> wrote: > Close, but % and * have the same operator precedence. Therefore the > expression > > "%dH" % nframes * nchannels > > is evaluated as > > (%dH" % nframes) * nchannels > > Thanks Peter, that's exactly correct. Maybe this will teach me not to post things without actually trying them in the interactive interpreter. -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Dec 19 20:21:09 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 19 Dec 2011 11:21:09 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> Message-ID: <4EEF8EA5.5000204@sbcglobal.net> An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Mon Dec 19 20:28:43 2011 From: eire1130 at gmail.com (James Reynolds) Date: Mon, 19 Dec 2011 14:28:43 -0500 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EEF8EA5.5000204@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EEF8EA5.5000204@sbcglobal.net> Message-ID: On Mon, Dec 19, 2011 at 2:21 PM, Wayne Watson wrote: > > > On 12/19/2011 8:50 AM, James Reynolds wrote: > > > > On Mon, Dec 19, 2011 at 11:35 AM, Wayne Watson < > sierra_mtnview at sbcglobal.net> wrote: > >> Win 7, 64-bit >> >> I had Py 2.5 installed on my PC earlier this year, and it began failing >> around June. I finally ... >> >> CE 1955 October 20 07:53:32.6 UT >> -- "The Date" The mystery unfolds. >> >> Web Page: >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > > Did you change the PATH to the right directory? It may still be pointing > to the old directory, or you may have never set it to begin with. > > Someone suggested this several months when I was having an install problem. > =========== > That being said, it sounds an awful lot like the python.exe isn't in your > path. To get it there you can open windows explorer (WIN+E) right click on > computer > properties then click advanced system settings. In the window > that pops up, click the "environment variables" button. In the "system > variables" portion, find the path variable and click the "Edit..." button. > Assuming that your new installation was placed in C:\Python25\ you will > want to add ";C:\Python25\" (the semicolon is important!) to the end of > your path. > =========== > Is that what you are suggesting? I brought up WE and clicked on > properties, and got a six tab dialog. Pushed Advanced. Tabs are: Sharing, > Security, Prev versions, general, tools, h/w, quota. I don't see anything > about about a PATH, sys or env vars. > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > CE 1955 October 20 07:53:32.6 UT > -- "The Date" The mystery unfolds. > > Web Page: > > > > In windows 7, 1. Go to start 2. Right click on "Computer" 3. Select Properties. This will bring up the "System" menu. 4. Select "Advanced system Settings" on the left hand side. 5. In this new window, select Environment variables... at the bottom 6. In the bottom window area, scroll down until you find "PATH" 7. Select "Edit" (do NOT delete anything contained in this or will screw some stuff up) 8. scroll to the very end and put a ; as a deliminator if there isn't one on the end already. Then put the direct path to you Python install you care about. (it should be something like this:(;C:\Python27) - this is mine in fact. 9. Hit OK. Then accept your way out. You will have to reboot. 10. To test, open a cmd prompt and and type simply "python". if you get Python 2.7.2 (some more stuff) then python is now on your path. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jsantos.lazer at gmail.com Mon Dec 19 21:00:40 2011 From: jsantos.lazer at gmail.com (Joaquim Santos) Date: Mon, 19 Dec 2011 20:00:40 +0000 Subject: [Tutor] Python challenge and decryption Message-ID: Hi list! This is my first post here but I've been following the list for some time now! I know that recently there was a message about decryption and all. I think that was what made me go back into the Python challenge and try to solve some of them... For the second one, I first laid on paper my ideas, about user interaction (or input) and what would do what. I haven't implemented the user input yet but as I tested I ended up having some problems. Anticipated but still annoying... My Python version is 2.7.1 and my OS is Linux Mint 11. My code is this one: def decrypt(cypheredText, shiftedCypherNumber): ''' This function will take two arguments. The first is the cyphered text, the second is the number of characters we need to shift the text so we can decrypt it. This is a Caesar cypher. ''' crypticText = list(cypheredText) for letter in crypticText: asciiValue = ord(letter) asciiValue += shiftedCypherNumber newLetter = chr(asciiValue) print newLetter This solves the riddle, however some characters are not correctly decyphered (a is coming back as {...) and prints the solution like this: r e c o m m e n d e d 0 " n o w " { p p l y " o n " t h e " u r l - How can I make this "Human readable"? ... Print the letters in just one (or more) lines and maybe replace the " for spaces (This one I suppose it could/should be done with whitespaces() or just making a loop to check and change those for ' '.) Thanks for your time! -- Joaquim Santos http://js-vfx.com *linkedin* -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Mon Dec 19 21:25:51 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 19 Dec 2011 20:25:51 +0000 Subject: [Tutor] A few Python Mysteries In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EEF8EA5.5000204@sbcglobal.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF47407AC1E@SCACMX008.exchad.jpmchase.net> James wrote: In windows 7, 1. Go to start 2. Right click on "Computer" 3. Select Properties. This will bring up the "System" menu. 4. Select "Advanced system Settings" on the left hand side. 5. In this new window, select Environment variables... at the bottom 6. In the bottom window area, scroll down until you find "PATH" 7. Select "Edit" (do NOT delete anything contained in this or will screw some stuff up) 8. scroll to the very end and put a ; as a deliminator if there isn't one on the end already. Then put the direct path to you Python install you care about. (it should be something like this:(;C:\Python27) - this is mine in fact. 9. Hit OK. Then accept your way out. You will have to reboot. 10. To test, open a cmd prompt and and type simply "python". if you get Python 2.7.2 (some more stuff) then python is now on your path. ============================================================================================= Modify "User Variables" and not "System variables". You will need to restart any open command prompt but not the full machine. PATH=%PATH%;c:\python27 That should pick up the system variables and then append python's location to it. http://geekswithblogs.net/renso/archive/2009/10/21/how-to-set-the-windows-path-in-windows-7.aspx If that does not work; then feel free to follow James's advice and then restart. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Mon Dec 19 21:46:12 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 19 Dec 2011 20:46:12 +0000 Subject: [Tutor] Python challenge and decryption In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47407AC4E@SCACMX008.exchad.jpmchase.net> Hi list! ?My Python version is 2.7.1 and my OS is Linux Mint 11. My code is this one: def decrypt(cypheredText, shiftedCypherNumber): ''' This function will take two arguments. The first is the cyphered text, the second is the number of characters we need to shift the text so we can decrypt it. This is a Caesar cypher. ''' crypticText = list(cypheredText) for letter in crypticText: asciiValue = ord(letter) asciiValue += shiftedCypherNumber newLetter = chr(asciiValue) print newLetter This solves the riddle, however some characters are not correctly decyphered? (a is coming back as {...) and prints the solution like this: r e c o m m ?- How can I make this "Human readable"? ... Print the letters in just one (or more) lines and maybe replace the " for spaces (This one I suppose it could/should be done with whitespaces() or just making a loop to check and change those for ' '.) Thanks for your time! -- Joaquim Santos http://js-vfx.com linkedin ============================================= Remove the print in the function. Add each character to a list (char_list) after you are have gotten newLetter: return ''.join( char_list ) def decrypt(cypheredText, shiftedCypherNumber): ''' This function will take two arguments. The first is the cyphered text, the second is the number of characters we need to shift the text so we can decrypt it. This is a Caesar cypher. ''' crypticList = [] crypticText = list(cypheredText) for letter in crypticText: asciiValue = ord(letter) # Add some range checking / wrapping here asciiValue += shiftedCypherNumber newLetter = chr(asciiValue) crypticList.append( newLetter ) return ''.join( crypticList ) Creating a list of the string is unnecessary. You can iterate through the string directly. for letter in cypheredText: In order to avoid getting '{', you need to do some range checking. Since this is based on ASCII your ranges are: A-Z = 65-90 a-z = 97-122 When it crosses the end of the range (90 or 122), it should then come back to the beginning. That way z wraps to a, and Z to A (for shifting number of 1). Alternatively, you can just make the entire string upper/lower case and then not deal with multiple cases. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Mon Dec 19 23:42:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Dec 2011 09:42:21 +1100 Subject: [Tutor] Python challenge and decryption In-Reply-To: References: Message-ID: <4EEFBDCD.6090604@pearwood.info> Joaquim Santos wrote: > - How can I make this "Human readable"? ... Print the letters in just one > (or more) lines and maybe replace the " for spaces (This one I suppose it > could/should be done with whitespaces() or just making a loop to check and > change those for ' '.) Firstly, you should not directly print anything in the function. You should always separate *functionality* from *presentation*. The function should do the job of doing the Caesar shift, and should return a string. This allows the caller to store the result in a variable for further work. Presentation should be handled by the caller, often (but not always) by using print. So you should accumulate each character into a list, then when done combine all the characters together into a string using ''.join(the_list), and finally return the string. Secondly, Caesar decryption should wrap around -- that is, it should only apply to letters A...Z and only produce letters A...Z, and likewise for lowercase. Anything not a letter shouldn't be shifted. So it isn't enough to just add the shift to the letter. E.g. 'z' shifted by 1 gives '{', but needs to be 'a'. If you have trouble implementing these two concepts, don't hesitate to ask for additional hints and suggestions. -- Steven From steve at pearwood.info Tue Dec 20 00:19:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Dec 2011 10:19:36 +1100 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EEF67B4.6090109@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> Message-ID: <4EEFC688.5090309@pearwood.info> Wayne Watson wrote: > Win 7, 64-bit > > I had Py 2.5 installed on my PC earlier this year, and it began failing > around June. I finally uninstalled it, and tried 2.6. Still had > problems that centered around getting to IDLE. Uninstalled 2.6, and went > to 2.7. Same problem. I completely uninstalled 2.7. I do have several > folders of py programs. No Python. Programs should not just "begin failing" unless somebody (you?) or something (a virus, another program?) mess with them. Especially not something as simple and stable as Python. Who installed Python 2.5 in the first place? If it was provided with your computer, then it was provided for a reason. Python is not a standard part Windows, but a number of PC manufacturers provide Python 2.5 to run their tools, and by removing it, you have broken whatever it is that the manufacturer tools are supposed to be doing. Installing Python 2.6 or 2.7 will probably not work as a replacement. If you installed Python 2.5 yourself, then it doesn't matter. However, my guess is that Python 2.5 was installed by the manufacturer, and my evidence for this is the error messages that you now see at boot up: > After that episode, I began to notice the following messages when I > signed on to my PC after a boot. I do not bring my PC down very often. > > Specified module could not be found: Loadlib python.dll failed, and > another of the same for Python25.dll failed (maybe not found). I did a > search for both, but neither were found. Of course they're not found. You uninstalled them. My first advice: re-install Python 2.5. If you have a recovery disk supplied by the manufacturer, try using that. Make sure you install a 64-bit version of Python, not 32-bit. Then do the same with Python 2.7. Make sure it is the 64-bit version. Then check that you still have BOTH Python 2.5 and 2.7 installed: look in the start menu, and you should see two entries for Python. > I ignored this inconvenience for a few weeks, and had developed a need > to copy a particular python program on Win 7 to another computer. Call > it abc.py. I copied it to a thumb drive, and plugged the drive into the > other PC, which has Python on it. abc.py was missing from the drive. I > tried this about three times, and even went to yet another PC. No abc.py. This has *nothing* to do with Python. To Windows, abc.py is just another file, like abc.txt or abc.jpg or abc.doc. If copying files to a thumb drive is failing (other than by human error, or faulty thumb drive), then you have deeper problems with your Windows installation than just missing Python. But I suspect either human error or a faulty thumb drive. Since I don't use Windows 7, and did not see how you tried to copy the file to the thumb drive, I can't be sure, but if something as fundamental as copying files was failing, then I would expect your Windows machine to be crashing constantly. So more likely the thumb drive is failing, or human error. Can you copy *other* files from the Windows 7 machine onto the thumb drive, and then from there to the second computer? -- Steven From ajarncolin at gmail.com Tue Dec 20 00:47:42 2011 From: ajarncolin at gmail.com (col speed) Date: Tue, 20 Dec 2011 06:47:42 +0700 Subject: [Tutor] Python challenge and decryption In-Reply-To: References: Message-ID: On 20 December 2011 03:00, Joaquim Santos wrote: > Hi list! > > This is my first post here but I've been following the list for some time > now! I know that recently there was a message about decryption and all. I > think that was what made me go back into the Python challenge and try to > solve some of them... > > For the second one, I first laid on paper my ideas, about user interaction > (or input) and what would do what. > > I haven't implemented the user input yet but as I tested I ended up having > some problems. Anticipated but still annoying... > > ?My Python version is 2.7.1 and my OS is Linux Mint 11. >snip< > Joaquim Santos > > http://js-vfx.com > > linkedin > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Have a look at the string module, particularly string.maketrans and string.translate. I think they are in the builtin str in version 3x, but in 2.7 you have to import string. Hope that helps Col From sierra_mtnview at sbcglobal.net Tue Dec 20 02:25:04 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 19 Dec 2011 17:25:04 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EEF8EA5.5000204@sbcglobal.net> Message-ID: <4EEFE3F0.3040407@sbcglobal.net> > 1. Go to start > 2. Right click on "Computer" > 3. Select Properties. This will bring up the "System" menu. > 4. Select "Advanced system Settings" on the left hand side. > 5. In this new window, select Environment variables... at the bottom > 6. In the bottom window area, scroll down until you find "PATH" > 7. Select "Edit" (do NOT delete anything contained in this or will > screw some stuff up) > 8. scroll to the very end and put a ; as a deliminator if there isn't > one on the end already. Then put the direct path to you Python install > you care about. (it should be something like this:(;C:\Python27) I see at the end: Program Files\jEdit;C:\Python25\ There is no Python on my PC. Python 2.5 is what I started with, so I guess I should make this: Program Files\jEdit > - this is mine in fact. > 9. Hit OK. Then accept your way out. You will have to reboot. > 10. To test, open a cmd prompt and and type simply "python". if you > get Python 2.7.2 (some more stuff) then python is now on your path. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From stayvoid at gmail.com Tue Dec 20 02:33:58 2011 From: stayvoid at gmail.com (Stayvoid) Date: Tue, 20 Dec 2011 04:33:58 +0300 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: <4EEEA9D5.70605@gmail.com> References: <4EEEA9D5.70605@gmail.com> Message-ID: > Please clarify, or expand, or tell us what problem you are having or > trying to solve. Hi! I want to have a possibility to import modules from the folder, which is not included in the load path. Example: module.py --------- def testfunc(name): file = open(name) return len(file.readlines()) if __name__ == "__main__": print testfunc(module.py) Code listing (shell): python /Users/Username/pythonmodules/module.py NameError: name 'module.py' is not defined Kind regards. From sierra_mtnview at sbcglobal.net Tue Dec 20 02:39:42 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 19 Dec 2011 17:39:42 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EEFC688.5090309@pearwood.info> References: <4EEF67B4.6090109@sbcglobal.net> <4EEFC688.5090309@pearwood.info> Message-ID: <4EEFE75E.4030804@sbcglobal.net> On 12/19/2011 3:19 PM, Steven D'Aprano wrote: > Wayne Watson wrote: >> Win 7, 64-bit >> >> I had Py 2.5 installed on my PC earlier this year, and it began >> failing around June. I finally uninstalled it, and tried 2.6. Still >> had problems that centered around getting to IDLE. Uninstalled 2.6, >> and went to 2.7. Same problem. I completely uninstalled 2.7. I do >> have several folders of py programs. No Python. > > > Programs should not just "begin failing" unless somebody (you?) or > something (a virus, another program?) mess with them. Especially not > something as simple and stable as Python. > > Who installed Python 2.5 in the first place? If it was provided with > your computer, then it was I did. It worked for months. > provided for a reason. Python is not a standard part Windows, but a > number of PC manufacturers provide Python 2.5 to run their tools, and > by removing it, you have broken whatever it is that the manufacturer > tools are supposed to be doing. Installing Python 2.6 or 2.7 will > probably not work as a replacement. > > If you installed Python 2.5 yourself, then it doesn't matter. > > However, my guess is that Python 2.5 was installed by the > manufacturer, and my evidence for this is the error messages that you > now see at boot up: > > >> After that episode, I began to notice the following messages when I >> signed on to my PC after a boot. I do not bring my PC down very often. >> >> Specified module could not be found: Loadlib python.dll failed, and >> another of the same for Python25.dll failed (maybe not found). I did >> a search for both, but neither were found. > > Of course they're not found. You uninstalled them. I would expect so, but why did it complain specifically about them and not others? See PATH comment below. > > My first advice: re-install Python 2.5. If you have a recovery disk > supplied by the manufacturer, try using that. Make sure you install a > 64-bit version of Python, not 32-bit. I really no longer have a need for 2.5, so I thought I might as well go for something newer, which is basically what I'm doing, since 2.5 wasn't working. > > Then do the same with Python 2.7. Make sure it is the 64-bit version. > Then check that you still have BOTH Python 2.5 and 2.7 installed: look > in the start menu, and you should see two entries for Python. > Whoops. Python 2.7.2 is on the menu and was installed 12/18. I thought I uninstalled it last night. It is the 64-bit version. It's beginning to look like the PATH is the problem, since I found Python25 at the end of the PATH variable, as noted to James above. > >> I ignored this inconvenience for a few weeks, and had developed a >> need to copy a particular python program on Win 7 to another >> computer. Call it abc.py. I copied it to a thumb drive, and plugged >> the drive into the other PC, which has Python on it. abc.py was >> missing from the drive. I tried this about three times, and even >> went to yet another PC. No abc.py. > > This has *nothing* to do with Python. To Windows, abc.py is just > another file, like abc.txt or abc.jpg or abc.doc. If copying files to > a thumb drive is failing (other than by human error, or faulty thumb > drive), then you have deeper problems with your Windows installation > than just missing Python. > > But I suspect either human error or a faulty thumb drive. Since I > don't use Windows 7, and did not see how you tried to copy the file to > the thumb drive, I can't be sure, but if something as fundamental as > copying files was failing, then I would expect your Windows machine to > be crashing constantly. So more likely the thumb drive is failing, or > human error. > > Can you copy *other* files from the Windows 7 machine onto the thumb > drive, and then from there to the second computer? No problem at all copying any other files to the thumb drive. After I get out of this quandary with PATH, and get 2.7.2 working, I'll try to recreate the problem. > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Tue Dec 20 02:47:21 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 19 Dec 2011 17:47:21 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47407AC1E@SCACMX008.exchad.jpmchase.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EEF8EA5.5000204@sbcglobal.net> <5B80DD153D7D744689F57F4FB69AF47407AC1E@SCACMX008.exchad.jpmchase.net> Message-ID: <4EEFE929.3020204@sbcglobal.net> The PATH variable for me (user) has c:\Users\Wayne\g95\bin On 12/19/2011 12:25 PM, Prasad, Ramit wrote: > James wrote: > In windows 7, > > 1. Go to start > 2. Right click on "Computer" > 3. Select Properties. This will bring up the "System" menu. > 4. Select "Advanced system Settings" on the left hand side. > 5. In this new window, select Environment variables... at the bottom > 6. In the bottom window area, scroll down until you find "PATH" > 7. Select "Edit" (do NOT delete anything contained in this or will screw some stuff up) > 8. scroll to the very end and put a ; as a deliminator if there isn't one on the end already. Then put the direct path to you Python install you care about. (it should be something like this:(;C:\Python27) - this is mine in fact. > 9. Hit OK. Then accept your way out. You will have to reboot. > 10. To test, open a cmd prompt and and type simply "python". if you get Python 2.7.2 (some more stuff) then python is now on your path. > ============================================================================================= > Modify "User Variables" and not "System variables". > You will need to restart any open command prompt > but not the full machine. > > PATH=%PATH%;c:\python27 > > That should pick up the system variables > and then append python's location to it. > > http://geekswithblogs.net/renso/archive/2009/10/21/how-to-set-the-windows-path-in-windows-7.aspx > > If that does not work; then feel free to follow > James's advice and then restart. > > > Ramit > > > Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology > 712 Main Street | Houston, TX 77002 > work phone: 713 - 216 - 5423 > > -- > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From bganesh05 at gmail.com Tue Dec 20 03:10:25 2011 From: bganesh05 at gmail.com (Ganesh Borse) Date: Tue, 20 Dec 2011 10:10:25 +0800 Subject: [Tutor] Request for guidance about a python syntax In-Reply-To: References: Message-ID: Hi, That's amazing. Thanks for sharing this information. Regards On Tue, Dec 20, 2011 at 2:31 AM, Jerry Hill wrote: > On Mon, Dec 19, 2011 at 12:10 PM, Peter Otten <__peter__ at web.de> wrote: > >> Close, but % and * have the same operator precedence. Therefore the >> expression >> >> "%dH" % nframes * nchannels >> >> is evaluated as >> >> (%dH" % nframes) * nchannels >> >> > Thanks Peter, that's exactly correct. Maybe this will teach me not to > post things without actually trying them in the interactive interpreter. > > -- > Jerry > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Tue Dec 20 03:44:08 2011 From: d at davea.name (Dave Angel) Date: Mon, 19 Dec 2011 21:44:08 -0500 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: <4EEFF678.4080204@davea.name> On 12/19/2011 08:33 PM, Stayvoid wrote: >> Please clarify, or expand, or tell us what problem you are having or >> trying to solve. > Hi! > > I want to have a possibility to import modules from the folder, which > is not included in the load path. > > Example: > > module.py > --------- > def testfunc(name): > file = open(name) > return len(file.readlines()) > > if __name__ == "__main__": > print testfunc(module.py) > > Code listing (shell): > python /Users/Username/pythonmodules/module.py > > NameError: name 'module.py' is not defined > > Kind regards. > First rule: include the complete error message, including the traceback. Also, make sure you copy/paste the message, not paraphrase or retype it. Anyway, chances are the error occurs because you didn't have any quotes around the filename. Python is forced to look up the name "module" in the global dictionary, and it can't find it. Of course, the error message wouldn't be exactly that. -- DaveA From d at davea.name Tue Dec 20 03:47:02 2011 From: d at davea.name (Dave Angel) Date: Mon, 19 Dec 2011 21:47:02 -0500 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EEFE929.3020204@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EEF8EA5.5000204@sbcglobal.net> <5B80DD153D7D744689F57F4FB69AF47407AC1E@SCACMX008.exchad.jpmchase.net> <4EEFE929.3020204@sbcglobal.net> Message-ID: <4EEFF726.9080909@davea.name> On 12/19/2011 08:47 PM, Wayne Watson wrote: > The PATH variable for me (user) has c:\Users\Wayne\g95\bin > By top-posting, you've ruined the whole continuity of what you quoted. Anyway, with a PATH like that, you won't be able to type Python at a command prompt. It works much better if it's on the path. -- DaveA From sierra_mtnview at sbcglobal.net Tue Dec 20 04:33:27 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 19 Dec 2011 19:33:27 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EEF67B4.6090109@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> Message-ID: <4EF00207.7000905@sbcglobal.net> It became apparent during the other part of this thread that I had not uninstalled Python 2.7, as I thought I had. As pointed out in the PATH discussion (James R.), the last item in the system variable PATH was Python25. I would think then changing it to Python27 might Python rolling again. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From alan.gauld at btinternet.com Tue Dec 20 10:06:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 Dec 2011 09:06:28 +0000 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: On 20/12/11 01:33, Stayvoid wrote: > I want to have a possibility to import modules from the folder, which > is not included in the load path. The code and error below has nothing to do with importing modules or the PYTHONPATH value. > module.py > --------- > def testfunc(name): > file = open(name) > return len(file.readlines()) > > if __name__ == "__main__": > print testfunc(module.py) This is simply opening the file module.py as any other file. It does not invoke Pythons import mechanism. > Code listing (shell): > python /Users/Username/pythonmodules/module.py > > NameError: name 'module.py' is not defined Please post the full error text not a summary. But in this case it isc complaining about the favct that you have not put quotes around the filename so it thinks module.py is a variable, but when it looks for it, it is not defined. BTW To set PYTHONPATH in a MacOSX environment you have to edit your .profile or .bash_profile (I can never remember which!) and add a line like export PYTHONPATH=/path/to/your/modules:/another/module/path/here HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From james.homme at highmark.com Tue Dec 20 18:31:49 2011 From: james.homme at highmark.com (Homme, James) Date: Tue, 20 Dec 2011 17:31:49 +0000 Subject: [Tutor] Beginner Exercise: Why Didn't I Break It? Message-ID: Hi, Please don't give me the answer. Please tell me where to read to find out. So far, the data types this little book has talked about are strings and numbers. The book is here. http://learnpythonthehardway.org/book/ I cut out the parts of the program I definitely understand to focus on this part. This exercise is a practice exercise that talks about functions. The instructions were to try to break the file and make it not run, so I decided to try to call the below function with one argument instead of three. I'm trying to explain to myself why it didn't break. I have comments in here for what I think is going on. # This function takes one argument. # It returns three items. def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 # It returns three things in parentheses, which, I guess is one group of things. I thought it would complain. stuff = secret_formula(start_point) print stuff # This is three items, according to me. It makes three separate variables, that we print out below. beans, jars, crates = secret_formula(start_point) print "We have %d beans, %d jars, and %d crates." % (beans, jars, crates) Thanks. Jim Jim Homme, Usability Services, Phone: 412-544-1810. ________________________________ This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Dec 20 19:00:14 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 20 Dec 2011 13:00:14 -0500 Subject: [Tutor] Beginner Exercise: Why Didn't I Break It? In-Reply-To: References: Message-ID: On Tue, Dec 20, 2011 at 12:31 PM, Homme, James wrote: > So far, the data types this little book has talked about are strings and numbers. ... > return jelly_beans, jars, crates ... > # It returns three things in parentheses, which, I guess is one group of things. I thought it would complain. You book may not have talked about it yet, but there is a third data type involved here, a tuple. ?The secret_formula() function doesn't actually return three separate things. ?It returns a single object that contains a sequence of three other objects. ?In this case, it specifically returns a tuple (rather than a list or other sequence type). Take a look here http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences for more about tuples in particular, and the rest of that page for an overview of sequence types in general. >beans, jars, crates = secret_formula(start_point) This line performs what python calls "sequence unpacking" (sometimes also called "tuple unpacking"). ?That's described in the same link I referenced above. Hopefully that gives you a few places to read more without explaining the whole thing. -- Jerry From james.homme at highmark.com Tue Dec 20 19:10:43 2011 From: james.homme at highmark.com (Homme, James) Date: Tue, 20 Dec 2011 18:10:43 +0000 Subject: [Tutor] Beginner Exercise: Why Didn't I Break It? In-Reply-To: References: Message-ID: Hi Jerry, Thank you. This reminds me of single dimension arrays in VBScript. Note that I said Reminds. I'm trying to pretend I don't know about other languages, so I can give myself less learning stress. thanks. Jim -----Original Message----- From: tutor-bounces+james.homme=highmark.com at python.org [mailto:tutor-bounces+james.homme=highmark.com at python.org] On Behalf Of Jerry Hill Sent: Tuesday, December 20, 2011 1:00 PM To: tutor at python.org Subject: Re: [Tutor] Beginner Exercise: Why Didn't I Break It? On Tue, Dec 20, 2011 at 12:31 PM, Homme, James wrote: > So far, the data types this little book has talked about are strings and numbers. ... > return jelly_beans, jars, crates ... > # It returns three things in parentheses, which, I guess is one group of things. I thought it would complain. You book may not have talked about it yet, but there is a third data type involved here, a tuple. The secret_formula() function doesn't actually return three separate things. It returns a single object that contains a sequence of three other objects. In this case, it specifically returns a tuple (rather than a list or other sequence type). Take a look here http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences for more about tuples in particular, and the rest of that page for an overview of sequence types in general. >beans, jars, crates = secret_formula(start_point) This line performs what python calls "sequence unpacking" (sometimes also called "tuple unpacking"). That's described in the same link I referenced above. Hopefully that gives you a few places to read more without explaining the whole thing. -- Jerry _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ________________________________ This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. From andrew at logaan.com Tue Dec 20 18:55:15 2011 From: andrew at logaan.com (Andrew Heagle) Date: Tue, 20 Dec 2011 12:55:15 -0500 Subject: [Tutor] Threads and Signals Message-ID: <201112201255.15844.andrew@logaan.com> Hi, I am testing out some stuff with threads and signals. This is just a prototype of how I want to incorporate it into my main script. I figured out how to "catch" signals for SIGUSR1 to output what all the thread children are "working" on. The problem I have is if in terminalA I run my script, and in terminalB I do `kill -SIGUSR1 $pid` the output from the script shows up on terminalA. How can I get the output to show up in terminalB? The reason I ask is because the script will be running in a loop forever doing something, so I would like to be able to "query it". I attached my test script in case that helps, so feel free to critique my code at the same time, if you like as I just starting learning Python recently. Thanks, Andrew -------------- next part -------------- A non-text attachment was scrubbed... Name: killtest.py Type: text/x-python Size: 2314 bytes Desc: not available URL: From alan.gauld at btinternet.com Tue Dec 20 20:50:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 20 Dec 2011 19:50:41 +0000 Subject: [Tutor] Beginner Exercise: Why Didn't I Break It? In-Reply-To: References: Message-ID: On 20/12/11 18:10, Homme, James wrote: > Hi Jerry, > Thank you. This reminds me of single dimension arrays in VBScript. You are absolutely right, tuples are like read-only arrays in VB. We have writeable arrays in python too but we call them something else :-) BTW The list prefers bottom posting to top posting so in future if you can add your comments after the relevant mail content that will be greatly appreciated. :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bganesh05 at gmail.com Wed Dec 21 02:57:09 2011 From: bganesh05 at gmail.com (Ganesh Borse) Date: Wed, 21 Dec 2011 09:57:09 +0800 Subject: [Tutor] request for guidance on goertzel algorithm for DTMF detection Message-ID: Dear Tutors, I was studyin the two python implementations of geortzel algo for DTMF detection: http://www.black-aura.com/blog/2011/12/10/python-implementation-of-the-goertzel-algorithm-dtmf-decoding/ . http://johnetherton.com/projects/pys60-dtmf-detector/ However, I found that both of these have limited functionality in terms of frequency ranges and when it comes to .wav files with more noise. Can you please help to guide me if you are aware of any other better implementations of goertzel algo in python? Or which can be the best mailing list for the queries regarding DTMF decoding/ goertzel alogs? Thanks for your help. Best Regards, Banes -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Dec 21 03:32:42 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 20 Dec 2011 18:32:42 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF00207.7000905@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> Message-ID: <4EF1454A.4020409@sbcglobal.net> I changed Python25 to Python27, and rebooted. I got the same two dll msgs again. On 12/19/2011 7:33 PM, Wayne Watson wrote: > It became apparent during the other part of this thread that I had not > uninstalled Python 2.7, as I thought I had. As pointed out in the > PATH discussion (James R.), the last item in the system variable PATH > was Python25. I would think then changing it to Python27 might Python > rolling again. > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From eire1130 at gmail.com Wed Dec 21 03:41:00 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 20 Dec 2011 21:41:00 -0500 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF1454A.4020409@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> Message-ID: On Tue, Dec 20, 2011 at 9:32 PM, Wayne Watson wrote: > I changed Python25 to Python27, and rebooted. I got the same two dll msgs > again. > > > On 12/19/2011 7:33 PM, Wayne Watson wrote: > >> It became apparent during the other part of this thread that I had not >> uninstalled Python 2.7, as I thought I had. As pointed out in the PATH >> discussion (James R.), the last item in the system variable PATH was >> Python25. I would think then changing it to Python27 might Python rolling >> again. >> >> > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > CE 1955 October 20 07:53:32.6 UT > -- "The Date" The mystery unfolds. > > Web Page: > > > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Did you also verify that Python is installed at C:\Python27 and not some other place? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Dec 21 10:04:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Dec 2011 09:04:25 +0000 Subject: [Tutor] request for guidance on goertzel algorithm for DTMF detection In-Reply-To: References: Message-ID: On 21/12/11 01:57, Ganesh Borse wrote: > Dear Tutors, > > I was studyin the two python implementations of geortzel algo for DTMF > detection: ... > Can you please help to guide me if you are aware of any other better > implementations of goertzel algo in python? Or which can be the best > mailing list for the queries regarding DTMF decoding/ goertzel alogs? This should go to the main Python mailing list/newsgroup at comp.lang.python It certainly is a long shot for a list aimed at beginner python programmers! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Wed Dec 21 11:08:26 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 21 Dec 2011 10:08:26 +0000 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF1454A.4020409@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> Message-ID: Hi Wayne, On 21 December 2011 02:32, Wayne Watson wrote: > I changed Python25 to Python27, and rebooted. ?I got the same two dll msgs > again. The PATH issue has nothing to do with your error messages. Python25.dll is normally installed in the C:\Windows\System32 folder, not C:\Python25, so whether or not c:\Python25 is in your PATH is irrelevant to whether it will be found (in C:\Windows\System32). The facts as far as I can tell are: a) Some application in your startup is trying to link to/load Python25.dll but failing as per the message you posted. b) You've uninstalled Python 2.5, so a) is not really surprising. c) The application (whatever it is) will *NOT* automatically start using the newer Python27.dll because you've installed Python 2.7. These are considered seperate/distinct versions of Python. Your options to get rid of the message is: a) Reinstall Python 2.5 b) Remove the application that depends on Python 2.5 (that is expecting it to be present.) To add: I'd be careful of 32 bit/64 bit issues -- If the application trying to run is in fact 32 bit then you should probably be installing the 32-bit version of Python, otherwise it probably still won't find Python25.dll. (32-bit applications won't be able to link to 64-bit dll's, and in any case on 64-bit versions of Windows things get a bit obscure -- C:\Windows\System32 actually contain 64-bit native dll's while 32-bit compatility dll's reside in c:\Windows\SysWOW64 but is presented as c:\Windows\System32 to 32-bit processes by the OS... ) If you don't know whether the application is 32-bit or 64-bit you'll just have to find out by trial and error. Install the one and if this doesn't resolve the problem then remove it again and install the other. Walter From steve at pearwood.info Wed Dec 21 11:43:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 21 Dec 2011 21:43:27 +1100 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF1454A.4020409@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> Message-ID: <4EF1B84F.3010203@pearwood.info> Wayne Watson wrote: > I changed Python25 to Python27, and rebooted. I got the same two dll > msgs again. I suggest you find out what applications are trying to run using Python 2.5. This is a Windows problem -- you need to get the list of programs that run at start up and inspect them for something that uses Python. Since I don't use Windows, I can't be more specific. -- Steven From jsantos.lazer at gmail.com Wed Dec 21 12:39:58 2011 From: jsantos.lazer at gmail.com (Joaquim Santos) Date: Wed, 21 Dec 2011 11:39:58 +0000 Subject: [Tutor] Python challenge and decryption Message-ID: Hi List! Thanks for all the input you guys gave me! I'm trying to implement your ideas on the function and I've been getting some parts right (the correct translation, still vertical and without spaces) or the wrong translation but with spaces... My problem is my range check. I'm also getting a funny problem with return, but I'll ask about it later. What I would like to know now, because it would help me a lot to draw my solution(I like to make sketches/line numbers while I'm thinking) was where to get the ascii table for Python! I searched and got a lot of modules and stuff to install and print it out but no printed online version? You can find for other languages, so where is the one for Python? I know I could install the said modules/scripts but I just think this should also be somewhere... -- Joaquim Santos http://js-vfx.com *linkedin* -------------- next part -------------- An HTML attachment was scrubbed... URL: From jamie at kontrol.kode5.net Wed Dec 21 12:49:05 2011 From: jamie at kontrol.kode5.net (Jamie Paul Griffin) Date: Wed, 21 Dec 2011 11:49:05 +0000 Subject: [Tutor] list mail formatting Message-ID: <20111221114905.GA27863@kontrol.kode5.net> Can I just ask why the majority of the mail on this list is in multipart/alternative and/or html format. It's driving me nuts trying to read this on my console. Is there not a requirement to use plain text as with most other technical mailing lists? I don't mean to moan and I know it's not a major issue but still. jamie. From d at davea.name Wed Dec 21 13:43:52 2011 From: d at davea.name (Dave Angel) Date: Wed, 21 Dec 2011 07:43:52 -0500 Subject: [Tutor] Python challenge and decryption In-Reply-To: References: Message-ID: <4EF1D488.5060008@davea.name> On 12/21/2011 06:39 AM, Joaquim Santos wrote: > Hi List! > > Thanks for all the input you guys gave me! > > I'm trying to implement your ideas on the function and I've been getting > some parts right (the correct translation, still vertical and without > spaces) or the wrong translation but with spaces... My problem is my range > check. I'm also getting a funny problem with return, but I'll ask about it > later. > > What I would like to know now, because it would help me a lot to draw my > solution(I like to make sketches/line numbers while I'm thinking) was where > to get the ascii table for Python! I searched and got a lot of modules and > stuff to install and print it out but no printed online version? You can > find for other languages, so where is the one for Python? > > I know I could install the said modules/scripts but I just think this > should also be somewhere... > ASCII predated Python by some 40 years. So any reference that is accurate would do. But you can make your own table quite trivially with a simple loop: for ordinal in range(ord(" "), 128): print ordinal, "-", chr(ordinal) ASCII codes below " " are control codes, such as newline and tab. ASCII is a 7-bit code, so the highest value is 127. -- DaveA From d at davea.name Wed Dec 21 13:57:33 2011 From: d at davea.name (Dave Angel) Date: Wed, 21 Dec 2011 07:57:33 -0500 Subject: [Tutor] list mail formatting In-Reply-To: <20111221114905.GA27863@kontrol.kode5.net> References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: <4EF1D7BD.4070302@davea.name> On 12/21/2011 06:49 AM, Jamie Paul Griffin wrote: > Can I just ask why the majority of the mail on this list is in multipart/alternative and/or html format. It's driving me nuts trying to read this on my console. Is there not a requirement to use plain text as with most other technical mailing lists? > > I don't mean to moan and I know it's not a major issue but still. > > jamie. > _ It's a common problem, in that most html formatting messes up the indenting of an inline program segment. But other than telling each newcomer that has the latter problem, there's no enforcement, as far as I know. if you're using Thunderbird, you can just tell it to View->MessageBodyAs->Plain text. I do that for all my email, and it prevents much spam, makes Phishing more obvious, and probably avoids some viruses. -- DaveA From jamie at kontrol.kode5.net Wed Dec 21 14:29:40 2011 From: jamie at kontrol.kode5.net (Jamie Paul Griffin) Date: Wed, 21 Dec 2011 13:29:40 +0000 Subject: [Tutor] list mail formatting In-Reply-To: <4EF1D7BD.4070302@davea.name> References: <20111221114905.GA27863@kontrol.kode5.net> <4EF1D7BD.4070302@davea.name> Message-ID: <20111221132940.GC27863@kontrol.kode5.net> On Wed, Dec 21, 2011 at 07:57:33AM -0500, Dave Angel wrote: > On 12/21/2011 06:49 AM, Jamie Paul Griffin wrote: > >Can I just ask why the majority of the mail on this list is in multipart/alternative and/or html format. It's driving me nuts trying to read this on my console. Is there not a requirement to use plain text as with most other technical mailing lists? > > > >I don't mean to moan and I know it's not a major issue but still. > > > > jamie. > >_ > It's a common problem, in that most html formatting messes up the > indenting of an inline program segment. But other than telling each > newcomer that has the latter problem, there's no enforcement, as far > as I know. > > if you're using Thunderbird, you can just tell it to > View->MessageBodyAs->Plain text. I do that for all my email, and it > prevents much spam, makes Phishing more obvious, and probably avoids > some viruses. > > -- > > DaveA I only use text MUA's. When using mutt is not such a problem but I spend a lot of time on a console using mail(1) and then it is a problem. i'm trying to put together a perl script to filter it all but it's just a little frustrating. From sierra_mtnview at sbcglobal.net Wed Dec 21 16:15:31 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 21 Dec 2011 07:15:31 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF1B84F.3010203@pearwood.info> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> Message-ID: <4EF1F813.5070101@sbcglobal.net> Python is long gone from my system. I only have Python 27. Somewhere a long the line, the uninstall of Python5 probably did not remove the Python5 from the PATH. I have no explanation as to why Python7 was not in the PATH. I have no idea why some remnant of why Python6 is hanging around. I uninstalled it long ago too. On 12/21/2011 2:43 AM, Steven D'Aprano wrote: > Wayne Watson wrote: >> I changed Python25 to Python27, and rebooted. I got the same two dll >> msgs again. > > I suggest you find out what applications are trying to run using > Python 2.5. This is a Windows problem -- you need to get the list of > programs that run at start up and inspect them for something that uses > Python. > > Since I don't use Windows, I can't be more specific. > > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From bodsda at googlemail.com Wed Dec 21 18:57:40 2011 From: bodsda at googlemail.com (bodsda at googlemail.com) Date: Wed, 21 Dec 2011 17:57:40 +0000 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF1F813.5070101@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> <4EF1F813.5070101@sbcglobal.net> Message-ID: <631779736-1324490260-cardhu_decombobulator_blackberry.rim.net-669533441-@b14.c12.bise7.blackberry> I think your missing the point. Ignore the fact that your PATH doesn't contain the correct paths to python. The problem is that on startup, a program (unknown) is looking for the dll file for python2.5 - it is looking for this in the system32 directory. To be rid of the startup errors, you need to replace the dll that was removed by the uninstallation of python2.5 - to do this, reinstall python2.5 Bodsda Sent from my BlackBerry? wireless device -----Original Message----- From: Wayne Watson Sender: tutor-bounces+bodsda=googlemail.com at python.org Date: Wed, 21 Dec 2011 07:15:31 To: Steven D'Aprano; tutor at python.org Subject: Re: [Tutor] A few Python Mysteries Python is long gone from my system. I only have Python 27. Somewhere a long the line, the uninstall of Python5 probably did not remove the Python5 from the PATH. I have no explanation as to why Python7 was not in the PATH. I have no idea why some remnant of why Python6 is hanging around. I uninstalled it long ago too. On 12/21/2011 2:43 AM, Steven D'Aprano wrote: > Wayne Watson wrote: >> I changed Python25 to Python27, and rebooted. I got the same two dll >> msgs again. > > I suggest you find out what applications are trying to run using > Python 2.5. This is a Windows problem -- you need to get the list of > programs that run at start up and inspect them for something that uses > Python. > > Since I don't use Windows, I can't be more specific. > > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From d at davea.name Wed Dec 21 19:16:28 2011 From: d at davea.name (Dave Angel) Date: Wed, 21 Dec 2011 13:16:28 -0500 Subject: [Tutor] list mail formatting In-Reply-To: <20111221132940.GC27863@kontrol.kode5.net> References: <20111221114905.GA27863@kontrol.kode5.net> <4EF1D7BD.4070302@davea.name> <20111221132940.GC27863@kontrol.kode5.net> Message-ID: <4EF2227C.1050200@davea.name> On 12/21/2011 08:29 AM, Jamie Paul Griffin wrote: > On Wed, Dec 21, 2011 at 07:57:33AM -0500, Dave Angel wrote: >> On 12/21/2011 06:49 AM, Jamie Paul Griffin wrote: >>> Can I just ask why the majority of the mail on this list is in multipart/alternative and/or html format. It's driving me nuts trying to read this on my console. Is there not a requirement to use plain text as with most other technical mailing lists? >>> >>> I don't mean to moan and I know it's not a major issue but still. >>> >>> jamie. >>> _ >> It's a common problem, in that most html formatting messes up the >> indenting of an inline program segment. But other than telling each >> newcomer that has the latter problem, there's no enforcement, as far >> as I know. >> >> if you're using Thunderbird, you can just tell it to >> View->MessageBodyAs->Plain text. I do that for all my email, and it >> prevents much spam, makes Phishing more obvious, and probably avoids >> some viruses. >> >> -- >> >> DaveA > I only use text MUA's. When using mutt is not such a problem but I spend a lot of time on a console using mail(1) and then it is a problem. i'm trying to put together a perl script to filter it all but it's just a little frustrating. > I have not seen any messages that would not display for me as plain text. In this mode, thunderbird ignores the other version(s) of the message. For some regular mail, I sometimes end up with a blank message, or one that says "to see the entire email, click on this link." Those I generally just delete, unless I know the company, and am actually interested. What I don't do is to try to extract just the text from the html stuff. -- DaveA From wprins at gmail.com Wed Dec 21 19:18:14 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 21 Dec 2011 18:18:14 +0000 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF1F813.5070101@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> <4EF1F813.5070101@sbcglobal.net> Message-ID: Hi Wayne, On 21 December 2011 15:15, Wayne Watson wrote: > Python is long gone from my system. I presume you mean Python **2.5** is long gone from your system (not Python in general), but in any case, this much has been well understood since several emails ago. >I only have Python 27. OK, that's also been clear since several emails ago and is not an issue (except that I have the impression that's not working properly either?) > Somewhere along the line, the uninstall of Python5 probably did not remove the Python5 > from the PATH. I have no explanation as to why Python7 was not in the PATH. To clarify: Python on Windows does **not** put itself on the System PATH when installed. Consequently the reason Python 2.7 is not on the PATH is in fact because no-one put it there (yet), since as I say, Python itself would not have done it. This also explains why C:\Python25 was not removed from the PATH when you uninstalled Python 2.5 -- Since Python's installation never put it there, it obviously wasn't going to remove it when it was uninstalled. Instead, the implication is that something or somebody else put it there -- most likely the application that *did* put it there is the **same** application that is now complaining about the fact that it can't find the Python 2.5 DLL when you boot up... > ?I have no idea why some remnant of why Python6 is hanging around. I > uninstalled it long ago too. I presume by Python6 you mean Python 2.6. Why do you think a remnant of this is hanging around? Anyway, re the bootup messages, I've already suggested what your options are, but in short: a) Find and remove the application that's trying to use Python 2.5 b) Install Python 2.5 again, and hope that's enough to get the app that wants to use it running again. Re your other Python problems, I'd suggest doing the following: 1) Go into your Control Panel->"Programs and Features", and remove all copies of Python (if any.) 2) Go into your C:\ Drive, and delete any existing Python folders that may still exist: C:\Python25 C:\Python26 C:\Python27 3) Redownload your Python installer (MSI file) of the version of your choice (2.7?) from the Python dowload site and re-install that with default options. 4) IDLE should then be present in your Start->All Programs menu under "Python 2.7", and should be easily locatable also with the Start menu quick search feature. Note, at this point (after the initial installation), Python via the command prompt won't be runnable from anywhere, since C:\Python27 will not have been put on the system PATH yet. A previous post in this thread explains how to add it (and you should be familiar enough with the system PATH by now to do this yourself anyway ;) ) Please try these suggestions and post back with specificity if you have further problems. HTH, Walter From sierra_mtnview at sbcglobal.net Wed Dec 21 20:33:30 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 21 Dec 2011 11:33:30 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> Message-ID: <4EF2348A.4000406@sbcglobal.net> Howdy, On 12/21/2011 2:08 AM, Walter Prins wrote: > Hi Wayne, > > On 21 December 2011 02:32, Wayne Watson wrote: >> I changed Python25 to Python27, and rebooted. I got the same two dll msgs >> again. > The PATH issue has nothing to do with your error messages. True, but it should have a lot to do with Python27. Some good news is that unlike previous attempts, I can actually see IDLE as a choice on a right-click of a py file. However, a spinner icon appears for about 5 seconds and then disappears. > Python25.dll is normally installed in the C:\Windows\System32 folder, > not C:\Python25, so whether or not c:\Python25 is in your PATH is > irrelevant to whether it will be found (in C:\Windows\System32). I have no Python of any kind in System32. I uninstalled 25 months ago. As far as I can tell, there is not a scrap of it left. > > The facts as far as I can tell are: > a) Some application in your startup is trying to link to/load > Python25.dll but failing as per the message you posted. Hmm, I made have made a mistake about a 25 dll. When I rebooted last night, I though I recalled 26. I'll reboot again in awhile and verify that. Yikes! No need. It's 26dll. I wrote it down after my first boot. My second was last night. > b) You've uninstalled Python 2.5, so a) is not really surprising. > c) The application (whatever it is) will *NOT* automatically start > using the newer Python27.dll because you've installed Python 2.7. > These are considered seperate/distinct versions of Python. > > Your options to get rid of the message is: > a) Reinstall Python 2.5 > b) Remove the application that depends on Python 2.5 (that is > expecting it to be present.) > > To add: I'd be careful of 32 bit/64 bit issues -- If the application > trying to run is in fact 32 bit then you should probably be installing > the 32-bit version of Python, otherwise it probably still won't find > Python25.dll. Forgetting about 25 (32-bit), per above, I installed a 64-bit version of 2.7.2. python-2.7.2.adm64.msi. > (32-bit applications won't be able to link to 64-bit > dll's, and in any case on 64-bit versions of Windows things get a bit > obscure -- C:\Windows\System32 actually contain 64-bit native dll's > while 32-bit compatility dll's reside in c:\Windows\SysWOW64 but is > presented as c:\Windows\System32 to 32-bit processes by the OS... ) > If you don't know whether the application is 32-bit or 64-bit you'll > just have to find out by trial and error. Install the one and if this > doesn't resolve the problem then remove it again and install the > other. > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Wed Dec 21 20:38:06 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 21 Dec 2011 11:38:06 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: <631779736-1324490260-cardhu_decombobulator_blackberry.rim.net-669533441-@b14.c12.bise7.blackberry> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> <4EF1F813.5070101@sbcglobal.net> <631779736-1324490260-cardhu_decombobulator_blackberry.rim.net-669533441-@b14.c12.bise7.blackberry> Message-ID: <4EF2359E.4000904@sbcglobal.net> On 12/21/2011 9:57 AM, bodsda at googlemail.com wrote: > I think your missing the point. Ignore the fact that your PATH doesn't contain the correct paths to python. As I just wrote to Prins. I think I made a copy error on the dll. I'm looking at the sheet I wrote the msg on and it shows 26.dll There is no 2.5 on my system. I removed it months ago. True about the PATH, but having Python25 in it was wrong. It's now 27. Why 25 got put in there I do not know. > > The problem is that on startup, a program (unknown) is looking for the dll file for python2.5 - it is looking for this in the system32 directory. To be rid of the startup errors, you need to replace the dll that was removed by the uninstallation of python2.5 - to do this, reinstall python2.5 See my post to Prins above. > > Bodsda > Sent from my BlackBerry? wireless device > > -----Original Message----- > From: Wayne Watson > Sender: tutor-bounces+bodsda=googlemail.com at python.org > Date: Wed, 21 Dec 2011 07:15:31 > To: Steven D'Aprano; tutor at python.org > Subject: Re: [Tutor] A few Python Mysteries > > Python is long gone from my system. I only have Python 27. Somewhere a > long the line, the uninstall of Python5 probably did not remove the > Python5 from the PATH. I have no explanation as to why Python7 was not > in the PATH. I have no idea why some remnant of why Python6 is hanging > around. I uninstalled it long ago too. > > On 12/21/2011 2:43 AM, Steven D'Aprano wrote: >> Wayne Watson wrote: >>> I changed Python25 to Python27, and rebooted. I got the same two dll >>> msgs again. >> I suggest you find out what applications are trying to run using >> Python 2.5. This is a Windows problem -- you need to get the list of >> programs that run at start up and inspect them for something that uses >> Python. >> >> Since I don't use Windows, I can't be more specific. >> >> >> -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Wed Dec 21 20:56:20 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 21 Dec 2011 11:56:20 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> <4EF1F813.5070101@sbcglobal.net> Message-ID: <4EF239E4.2010908@sbcglobal.net> Hi, On 12/21/2011 10:18 AM, Walter Prins wrote: > Hi Wayne, > > On 21 December 2011 15:15, Wayne Watson wrote: >> Python is long gone from my system. > I presume you mean Python **2.5** is long gone from your system (not > Python in general), but in any case, this much has been well > understood since several emails ago. All but 2.7.2. > >> I only have Python 27. > OK, that's also been clear since several emails ago and is not an > issue (except that I have the impression that's not working properly > either?) > >> Somewhere along the line, the uninstall of Python5 probably did not remove the Python5 >> from the PATH. I have no explanation as to why Python7 was not in the PATH. > To clarify: Python on Windows does **not** put itself on the System > PATH when installed. Consequently the reason Python 2.7 is not on the > PATH is in fact because no-one put it there (yet), since as I say, So, PythonNN, where NN is the version, should never appear in PATH? > Python itself would not have done it. This also explains why > C:\Python25 was not removed from the PATH when you uninstalled Python > 2.5 -- Since Python's installation never put it there, it obviously > wasn't going to remove it when it was uninstalled. Instead, the > implication is that something or somebody else put it there -- most It's conceivable when I raised some of the questions a month of so ago, someone suggested putting PythonNN on the path. I recall the PATH idea surfaced back then. > likely the application that *did* put it there is the **same** > application that is now complaining about the fact that it can't find > the Python 2.5 DLL when you boot up... See my mis-copy 26.dll in my other post to you. > >> I have no idea why some remnant of why Python6 is hanging around. I >> uninstalled it long ago too. > I presume by Python6 you mean Python 2.6. Why do you think a remnant > of this is hanging around? True. 2.6, and not 6. See previous comments about 26.dll. I think I'm going to pass on the 2.5 comments below in light of the 26.dll typo. > Anyway, re the bootup messages, I've already suggested what your > options are, but in short: > a) Find and remove the application that's trying to use Python 2.5 > b) Install Python 2.5 again, and hope that's enough to get the app > that wants to use it running again. > > Re your other Python problems, I'd suggest doing the following: > 1) Go into your Control Panel->"Programs and Features", and remove all > copies of Python (if any.) I'm leaving 2.7.2 there for now. > 2) Go into your C:\ Drive, and delete any existing Python folders that > may still exist: > C:\Python25 > C:\Python26 C:\Python25 and 26 are long gone. I'm holding onto 27. 3) Redownload your Python installer (MSI file) of the version of your choice (2.7?) from the Python dowload site and re-install that with default options. Let's hold off on this in light of the 26.dll discover. It may have some bearing on the current state of 27. 4) IDLE should then be present in your Start->All Programs menu under "Python 2.7", and should be easily locatable also with the Start menu quick search feature. IDLE shows as normal when I right-click on py files. It just doesn't bring up IDLE. Note, at this point (after the initial installation), Python via the command prompt won't be runnable from anywhere, since C:\Python27 will not have been put on the system PATH yet. A previous post in this thread explains how to add it (and you should be familiar enough with the system PATH by now to do this yourself anyway ;) ) When the PythonNN point I made is answered, then I address the PATH again. Please try these suggestions and post back with specificity if you have further problems. HTH, Walter _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From steve at pearwood.info Wed Dec 21 22:44:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 22 Dec 2011 08:44:27 +1100 Subject: [Tutor] list mail formatting In-Reply-To: <4EF1D7BD.4070302@davea.name> References: <20111221114905.GA27863@kontrol.kode5.net> <4EF1D7BD.4070302@davea.name> Message-ID: <4EF2533B.4050400@pearwood.info> Dave Angel wrote: > On 12/21/2011 06:49 AM, Jamie Paul Griffin wrote: >> Can I just ask why the majority of the mail on this list is in >> multipart/alternative and/or html format. It's driving me nuts trying >> to read this on my console. ^^^^^^^ to which Dave replied: > if you're using Thunderbird, I don't think Thunderbird runs as a mail client in the console :) I normally use mutt at the console, and set it to automatically decode HTML emails using elinks. This seems to work for me, except for a regrettable tendency for mutt to prefer the HTML part to the plain text part when available. -- Steven From alan.gauld at btinternet.com Thu Dec 22 00:51:46 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Dec 2011 23:51:46 +0000 Subject: [Tutor] list mail formatting In-Reply-To: <20111221114905.GA27863@kontrol.kode5.net> References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: On 21/12/11 11:49, Jamie Paul Griffin wrote: > Can I just ask why the majority of the mail on this list is in > multipart/alternative and/or html format. Because thats what the majority of email systems are set up to send as default, and have been for the last 10 years or more. > Is there not a requirement to use plain text as with > most other technical mailing lists? No, because many of the users of this list are non technical beginners who understand relatively little about computers. We request, and advise where possible, on setting up email in plain text, but we do not insist since that would deter the very people we are trying to help. > I don't mean to moan and I know it's not a major issue but still. It's a frustration to most folks who were brought up on plain-text email. But most modern emailers find the idea of using only plain text anachronistic at best and just downright bizarre in many (most?) cases! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Dec 22 01:10:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Dec 2011 00:10:36 +0000 Subject: [Tutor] A few Python Mysteries In-Reply-To: <4EF239E4.2010908@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> <4EF1F813.5070101@sbcglobal.net> <4EF239E4.2010908@sbcglobal.net> Message-ID: On 21/12/11 19:56, Wayne Watson wrote: >> To clarify: Python on Windows does **not** put itself on the System >> PATH when installed. > So, PythonNN, where NN is the version, should never appear in PATH? Not from a standard Python installation. But other programs whjich use Pythonn may install a version and modify the PATH for you, or you may, for your own benefit, add it manually. I always add a new Python version to my PATH as a matter of course. > It's conceivable when I raised some of the questions a month of so ago, > someone suggested putting PythonNN on the path. Very possible indeed. >> likely the application that *did* put it there is the **same** >> application that is now complaining about the fact that it can't find >> the Python 2.5 DLL when you boot up... > See my mis-copy 26.dll in my other post to you. OK, But the principle remains. If you have an app in your startup sequence that expects to find Python it will complain. You can check your startup sequence using a Microsoft tool. MSCONFIG or somesuch. Google Windows startup tool or similar... You can disable individual programs and restart to find out what is causing it. >>> I have no idea why some remnant of why Python6 is hanging around. I >>> uninstalled it long ago too. The problem is that it is not hanging around and some app expects it to be there. The error message is about a missing file... One thing that may be significant... Are you installing your Windows Python versions from python.org or from ActiveState? They are very similar but not identical. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Dec 22 01:27:12 2011 From: d at davea.name (Dave Angel) Date: Wed, 21 Dec 2011 19:27:12 -0500 Subject: [Tutor] A few Python Mysteries In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> <4EF1F813.5070101@sbcglobal.net> <4EF239E4.2010908@sbcglobal.net> Message-ID: <4EF27960.9080609@davea.name> On 12/21/2011 07:10 PM, Alan Gauld wrote: > > > One thing that may be significant... > Are you installing your Windows Python versions from > python.org or from ActiveState? They are very similar > but not identical. > And one difference is that ActiveState sets up both the PATH and the registry to make it easy to doubleclick on either python itself or on a script, when viewed in Explorer or equivalent. -- DaveA From sierra_mtnview at sbcglobal.net Thu Dec 22 04:21:48 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 21 Dec 2011 19:21:48 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EEF67B4.6090109@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> Message-ID: <4EF2A24C.7070701@sbcglobal.net> If you read on past a few paragraphs, there is some reason for hope that 2.7.2 is close to running. But first, the dll story. As it turns out in the other part of this thread, the "Python25.dll" was a typo on my part. It's really Python26.dll. Upon re-booting to make sure of that I read the message fully, and discovered that it read: C:\Program Files9x86)\Uniblue\DriverScanner\Python26.dll not installed. What is Uniblue you ask? I installed a new version of the video program Winamp back in early Nov, and it had some selections. One of which was to include Uniblue Driver Checker. I thought I'd give it a try. After the install completed, I thought I'd give it a try. It goes through all your drivers to find which ones are out of date. Surprise. You can buy the latest ones through them. I uninstalled Uniblue, but as it turns out, it was an incomplete uninstall. I just spent the last 30-45 minutes trying to get it uninstalled. Finally, I sent an e-mail on how to do it. I have no idea how it got entangled with Python 2.6. So for the time being it's out of the picture. As a question asked by others, is Python27 under ...\System32. It is under C:\Python27. Further, it is the 64-bit version associated with Python. In reading some of the other posts, I was unsure of whether Python27 is put on the PATH or not by the install. The question remains unanswered. I just left it there, as I re-installed 2.7.2 minutes ago. Here's where matters stand. The fact that when I right click on a py file, it begins with Open and then Edit with IDLE is very encouraging. The downside is that IDLE does not come up. However, the Start menu's Python27 entry shows Edit with IDLE, Manuals, ..., and Python Console. The console works. The fact that IDLE actually appears in both places is again encouraging. Under ...\Python27\Lib\idlelib, I can find idle.py, idle.pyw and IdleHistory.py. Clicking on idle.pyw does nothing. A few months ago when I broached this install and IDLE problem, someone mentioned idle.bat. It is in the same idlelib. Is there something that needs to be done here, to get IDLE active? Is this where having Python27 in the path causes a problem with IDLE? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From rhettnaxel at gmail.com Thu Dec 22 04:34:54 2011 From: rhettnaxel at gmail.com (Alexander) Date: Wed, 21 Dec 2011 22:34:54 -0500 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: On Wed, Dec 21, 2011 at 6:51 PM, Alan Gauld wrote: > On 21/12/11 11:49, Jamie Paul Griffin wrote: >> >> Can I just ask why the majority of the mail on this list is in > >> multipart/alternative and/or html format. > > Because thats what the majority of email systems are set up to > send as default, and have been for the last 10 years or more. > >> Is there not a requirement to use plain text as with > >> most other technical mailing lists? > > No, because many of the users of this list are non technical > beginners who understand relatively little about computers. > We ?request, and advise where possible, on setting up email > in plain text, but we do not insist since that would deter > the very people we are trying to help. > >> I don't mean to moan and I know it's not a major issue but still. > > > It's a frustration to most folks who were brought up on > plain-text email. But most modern emailers find the idea > of using only plain text anachronistic at best and just > downright bizarre in many (most?) cases! > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I'm glad I came across this thread. I've been following a few posts here and there, and now that Alan has posted I feel comfortable exchanging emails for this mailing list from here on in rich formatting. -- Alexander 7D9C597B From wprins at gmail.com Thu Dec 22 05:20:39 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 22 Dec 2011 04:20:39 +0000 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF2A24C.7070701@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> Message-ID: Hi Wayne, On 22 December 2011 03:21, Wayne Watson wrote: > I uninstalled Uniblue, but as it turns out, it > was an incomplete uninstall. ?I just spent the last 30-45 minutes trying to > get it uninstalled. Finally, I sent an e-mail on how to do it. I have no > idea how it got entangled with Python 2.6. So for the time being it's out of > the picture. Well, presumably it uses/depends on Python 2.6... > As a question asked by others, is Python27 under ...\System32. It is under > C:\Python27. ?Further, it is the 64-bit version associated with Python. I didn't ask. I stated, and to clarify: When you install the standard distribution of Python, the majority of the files get put under C:\PythonNN (unless otherwise specified by the user). However, the Python engine in the form of a DLL is *also* put under the System32 directory. > In reading some of the other posts, I was unsure of whether Python27 is put > on the PATH or not by the install. ?The question remains unanswered. ?I just > left it there, as I re-installed 2.7.2 minutes ago. ?Here's where matters > stand. I've already answered this also, with an unambigious exception to my answer pointed out by another poster, which is that it depends on whether you installed the standard Python distribution or whether you installed the ActiveState Python distribution. So, did you install the standard Python distribution or did you install the ActiveState version of Python? The answer to this question will determine whether the PATH will have been affected by the Python installation. Even so, it's an irrelevance w.r.t. your IDLE problems... > The fact that when I right click on a py file, it begins with Open and then > Edit with IDLE is very encouraging. Having this entry in your context menu simply means certain entries are in your system's registery but says very little else about whether it will work or not. > The downside is that IDLE does not come up. Which suggests that the associations/registry entries are in fact broken, perhaps because they're pointing to a non-existent installation of Python... > However, the Start menu's Python27 entry shows Edit with IDLE, Manuals, > ..., and Python Console. ?The console works. The fact that IDLE actually > appears in both places is again encouraging. Does IDLE start from the Start menu when you click it? >> Under ...\Python27\Lib\idlelib, I can find idle.py, idle.pyw and > IdleHistory.py. ?Clicking on idle.pyw does nothing. Does double clicking idle.pyw do anything? Normally double clicking idle.pyw will start IDLE. Does double clicking idle.bat do anything? Normally clicking idle.bat will also start IDLE. If you open a command prompt and then enter cd \Python27\Lib\idlelib idle.bat Does it output any error messages? If so, what? > > A few months ago when I broached this install and IDLE problem, someone > mentioned idle.bat. It is in the same ?idlelib. Is there something that > needs to be done here, to get IDLE active? ?Is this where having Python27 in > the path causes a problem with IDLE? Whether or not you have C:\Python27 in the PATH is irrelevant to whether IDLE will run. In any case, I'd still suggest reinstalling Python 2.7 -- you seem to be having file association/registry issues and who knows what else, these things will not resolve themselves by fiddling around with the PATH issue, which is in any case a red herring, an irrelevance w.r.t. your IDLE issues. Walter From rhettnaxel at gmail.com Thu Dec 22 05:44:49 2011 From: rhettnaxel at gmail.com (Alexander) Date: Wed, 21 Dec 2011 23:44:49 -0500 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: On Wed, Dec 21, 2011 at 11:02 PM, prakash singh wrote: > hi everybody i jsut want to login into ?the web page can anyone help > me please i will attach the page i just want to give username and > password using the pyhton code please help me on this.please look for > the attachment. ____________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor This is interesting. What networks are you connected to? And the python code you mentioned, upload it as an attachment and it will be easier to help you. From jamie at kontrol.kode5.net Thu Dec 22 09:59:05 2011 From: jamie at kontrol.kode5.net (Jamie Paul Griffin) Date: Thu, 22 Dec 2011 08:59:05 +0000 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: <20111222085905.GB32036@kontrol.kode5.net> On Wed, Dec 21, 2011 at 11:51:46PM +0000, Alan Gauld wrote: > On 21/12/11 11:49, Jamie Paul Griffin wrote: > >Is there not a requirement to use plain text as with > > most other technical mailing lists? > > No, because many of the users of this list are non technical > beginners who understand relatively little about computers. > We request, and advise where possible, on setting up email > in plain text, but we do not insist since that would deter > the very people we are trying to help. I can understand that and it's a fair point. So, perhaps my suggestion of putting some filtering/reformatting software on the list server could help with this? jamie. From alan.gauld at btinternet.com Thu Dec 22 10:10:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Dec 2011 09:10:58 +0000 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: On 22/12/11 03:34, Alexander wrote: >> We request, and advise where possible, on setting up email >> in plain text, but we do not insist >> It's a frustration to most folks who were brought up on >> plain-text email. > > I'm glad I came across this thread. I've been following a few posts > here and there, and now that Alan has posted I feel comfortable > exchanging emails for this mailing list from here on in rich > formatting. Notice I didn't say we encourage it. If you can send mails in plain tesxt you will avoid many problems, particularly in code formatting issues. You will also avoid frustrating those who might help you. But, if you can't figure out how to send in plain text we would rather you posted RTF than not post at all! But if you ever want to grow as a programmer and use any of the more advanced technical mailing lists you will find them less accomodating. So avoiding plain text may work here but will ultimately be limiting to your learning. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Dec 22 10:14:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Dec 2011 09:14:57 +0000 Subject: [Tutor] list mail formatting In-Reply-To: <20111222085905.GB32036@kontrol.kode5.net> References: <20111221114905.GA27863@kontrol.kode5.net> <20111222085905.GB32036@kontrol.kode5.net> Message-ID: On 22/12/11 08:59, Jamie Paul Griffin wrote: > I can understand that and it's a fair point. > So, perhaps my suggestion of putting some filtering/reformatting > software on the list server could help with this? Maybe, but I'm a list moderator and I have absolutely no access to the list server installation, I just use the web admin interface. I don't even know who does have access to the server installation. It's probably someone at the python.org admin level. So how we would ever do that I have no idea! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rhettnaxel at gmail.com Thu Dec 22 10:53:13 2011 From: rhettnaxel at gmail.com (Alexander Etter) Date: Thu, 22 Dec 2011 04:53:13 -0500 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: On Dec 22, 2011, at 4:10, Alan Gauld wrote: > On 22/12/11 03:34, Alexander wrote: > >>> We request, and advise where possible, on setting up email >>> in plain text, but we do not insist > >>> It's a frustration to most folks who were brought up on >>> plain-text email. >> >> I'm glad I came across this thread. I've been following a few posts >> here and there, and now that Alan has posted I feel comfortable >> exchanging emails for this mailing list from here on in rich >> formatting. > > Notice I didn't say we encourage it. If you can send mails in plain tesxt you will avoid many problems, particularly in code formatting issues. You will also avoid frustrating those who might help you. > > But, if you can't figure out how to send in plain text we would rather you posted RTF than not post at all! > > But if you ever want to grow as a programmer and use any of the more advanced technical mailing lists you will find them less accomodating. > So avoiding plain text may work here but will ultimately be limiting to your learning. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________ Ah I know of what you mentioned. On an GNU Emacs mailing list I was advised to avoid anything but plaintext. It just seems so archaic. But I'm a novice and will learn why eventually. Alexander. From jamie at kontrol.kode5.net Thu Dec 22 12:04:18 2011 From: jamie at kontrol.kode5.net (Jamie Paul Griffin) Date: Thu, 22 Dec 2011 11:04:18 +0000 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> <20111222085905.GB32036@kontrol.kode5.net> Message-ID: <20111222110418.GC32036@kontrol.kode5.net> On Thu, Dec 22, 2011 at 09:14:57AM +0000, Alan Gauld wrote: > On 22/12/11 08:59, Jamie Paul Griffin wrote: > > >I can understand that and it's a fair point. > > So, perhaps my suggestion of putting some filtering/reformatting > > software on the list server could help with this? > > Maybe, but I'm a list moderator and I have absolutely no access > to the list server installation, I just use the web admin interface. > I don't even know who does have access to the server installation. > It's probably someone at the python.org admin level. > > So how we would ever do that I have no idea! No problem. I'll write something to reformat these emails on my server, saves any bother. Thank you for humouring me. From pprakashsingh72 at gmail.com Thu Dec 22 12:06:18 2011 From: pprakashsingh72 at gmail.com (prakash singh) Date: Thu, 22 Dec 2011 16:36:18 +0530 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: i am asking a code how to fill the column of username and password with letters and press enter after that anyone who can help me on that thanks for the replies ,please provide me so that i can automate the rest part of the router gui On Thu, Dec 22, 2011 at 3:23 PM, Alexander Etter wrote: > > On Dec 22, 2011, at 4:10, Alan Gauld wrote: > >> On 22/12/11 03:34, Alexander wrote: >> >>>> We ?request, and advise where possible, on setting up email >>>> in plain text, but we do not insist >> >>>> It's a frustration to most folks who were brought up on >>>> plain-text email. >>> >>> I'm glad I came across this thread. I've been following a few posts >>> here and there, and now that Alan has posted I feel comfortable >>> exchanging emails for this mailing list from here on in rich >>> formatting. >> >> Notice I didn't say we encourage it. If you can send mails in plain tesxt you will avoid many problems, particularly in code formatting issues. You will also avoid frustrating those who might help you. >> >> But, if you can't figure out how to send in plain text we would rather you posted RTF than not post at all! >> >> But if you ever want to grow as a programmer and use any of the more advanced technical mailing lists you will find them less accomodating. >> So avoiding plain text may work here but will ultimately be limiting to your learning. >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> ______________________________ > > Ah I know of what you mentioned. On an GNU Emacs mailing list I was advised to avoid anything but plaintext. > It just seems so archaic. But I'm a novice and will learn why eventually. > Alexander. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Dec 22 13:26:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Dec 2011 12:26:18 +0000 Subject: [Tutor] username/password question [was Re: list mail formatting] In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: On 22/12/11 11:06, prakash singh wrote: > i am asking a code how to fill the column of username and password > with letters and press enter after that anyone who can help me on that > thanks for the replies ,please provide me so that i can automate the > rest part of the router gui Please do not hijack a thread by just replying to an existing email. This conceals your message on threaded mail/news readers and makes it less likely you will get a reply. It is also confusing for readers trying to sesarch the archives in the future. Always start a new subject with a new message. And change the subject line to reflect the true subject. Now, as to your question can you give us a bit more context? What column of username/password? What kind of GUI? Is this web based or desktop based? Are you trying to screen-scrape an existing GUI or are you trying to create a new GUI? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu Dec 22 14:18:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 23 Dec 2011 00:18:28 +1100 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: <4EF32E24.7000903@pearwood.info> prakash singh wrote: > i am asking a code how to fill the column of username and password > with letters and press enter after that anyone who can help me on that > thanks for the replies ,please provide me so that i can automate the > rest part of the router gui Everything you need to know to solve this problem can be learned from this website: http://catb.org/~esr/faqs/smart-questions.html Good luck! -- Steven From sierra_mtnview at sbcglobal.net Thu Dec 22 16:38:30 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Dec 2011 07:38:30 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> Message-ID: <4EF34EF6.2030002@sbcglobal.net> Hi, Walter. On 12/21/2011 8:20 PM, Walter Prins wrote: > Hi Wayne, > > On 22 December 2011 03:21, Wayne Watson wrote: >> I uninstalled Uniblue, but as it turns out, it >> was an incomplete uninstall. I just spent the last 30-45 minutes trying to >> get it uninstalled. Finally, I sent an e-mail on how to do it. I have no >> idea how it got entangled with Python 2.6. So for the time being it's out of >> the picture. > Well, presumably it uses/depends on Python 2.6... I'm looking at the Uniblue DriverScanner, and see mostly exe files, and a few dll files. They may all relate to the uniblue program itself. There's a language folder there, and a x64 folder there. x64 has the installer. Otherwise, there is no reference to anything that looks like a 26 dll, nor is there a list of drivers the program might want to examine for age. Of course, all of this should have been uninstalled. Although, the Win7 indexed search is very fast to find something there are times when it flubs (possibly since I don't know all the tricks one can use in a search). looking for 26.dll has turned up nothing an either a folder or inside a file. Supposedly, Uniblue supply an answer in 24 hours. If not, I'll try Winamp. >> As a question asked by others, is Python27 under ...\System32. It is under >> C:\Python27. Further, it is the 64-bit version associated with Python. > I didn't ask. I stated, and to clarify: When you install the standard > distribution of Python, the majority of the files get put under > C:\PythonNN (unless otherwise specified by the user). However, the > Python engine in the form of a DLL is *also* put under the System32 > directory. I'm looking at System32 entries right now. I see folders such as spool, speech, setup,restore, and lots of dll files. Some of the "p" dll files are p2psvc.dll, packager.dll, p2p.dll, and python27.dll. No python26.dll, and nothing starting with py other than the 27 file. >> In reading some of the other posts, I was unsure of whether Python27 is put >> on the PATH or not by the install. The question remains unanswered. I just >> left it there, as I re-installed 2.7.2 minutes ago. Here's where matters >> stand. > I've already answered this also, with an unambigious exception to my > answer pointed out by another poster, which is that it depends on > whether you installed the standard Python distribution or whether you Standard. Interesting dependency. I considered Active once, but did not install it. > installed the ActiveState Python distribution. So, did you install > the standard Python distribution or did you install the ActiveState > version of Python? The answer to this question will determine whether > the PATH will have been affected by the Python installation. Even so, > it's an irrelevance w.r.t. your IDLE problems... What is the outcome based on what I wrote about not Active? > >> The fact that when I right click on a py file, it begins with Open and then >> Edit with IDLE is very encouraging. > Having this entry in your context menu simply means certain entries > are in your system's registery but says very little else about whether > it will work or not. > >> The downside is that IDLE does not come up. > Which suggests that the associations/registry entries are in fact > broken, perhaps because they're pointing to a non-existent > installation of Python... If so, how I can I tell? > >> However, the Start menu's Python27 entry shows Edit with IDLE, Manuals, >> ..., and Python Console. The console works. The fact that IDLE actually >> appears in both places is again encouraging. > Does IDLE start from the Start menu when you click it? Nothing happens that I can detect. I'm looking at Properties of it. It shows Start in: c:\Python27. Type of File: shortcut (link). Location: ...\star menu\programs\python2.7 Interesting under the Security tab it shows Wayne with only special permissions. No Read, Write, Read & Execute(!!). Admin allows all but special. Users allows Read&Execute and Read. Same with Everyone Under Details tab Name is IDLE(Python GUI) link. Folder Path: c:\ProgramData\Microsoft\Windows\Start... I can see nothing past "Start..." > >>> Under ...\Python27\Lib\idlelib, I can find idle.py, idle.pyw and >> IdleHistory.py. Clicking on idle.pyw does nothing. > Does double clicking idle.pyw do anything? Nothing but a momentary circular arrow icon. Thinking I guess. > Normally double clicking > idle.pyw will start IDLE. Does double clicking idle.bat do anything? > Normally clicking idle.bat will also start IDLE. If you open a > command prompt and then enter > cd \Python27\Lib\idlelib > idle.bat > > Does it output any error messages? If so, what? A black command window comes up very briefly. It looks empty, but it's really gone quickly. > >> A few months ago when I broached this install and IDLE problem, someone >> mentioned idle.bat. It is in the same idlelib. Is there something that >> needs to be done here, to get IDLE active? Is this where having Python27 in >> the path causes a problem with IDLE? > Whether or not you have C:\Python27 in the PATH is irrelevant to > whether IDLE will run. I'm removing it nevertheless unless your answer to my Active above has some relevance to keeping it. > > In any case, I'd still suggest reinstalling Python 2.7 -- you seem to > be having file association/registry issues and who knows what else, In the last 24 hours I've re-installed 2.7.2 twice. The last time was around 7-9 pm last night. I don't see how doing it again is going to help. If there's a registry issue, then I need to figure out how to resolve it. > these things will not resolve themselves by fiddling around with the > PATH issue, which is in any case a red herring, Apparently so. > an irrelevance w.r.t. > your IDLE issues. Who know what the cause is? Maybe Uniblue. I hope not. :-) > > Walter > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Thu Dec 22 16:43:12 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Dec 2011 07:43:12 -0800 Subject: [Tutor] A few Python Mysteries In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF00207.7000905@sbcglobal.net> <4EF1454A.4020409@sbcglobal.net> <4EF1B84F.3010203@pearwood.info> <4EF1F813.5070101@sbcglobal.net> <4EF239E4.2010908@sbcglobal.net> Message-ID: <4EF35010.3000601@sbcglobal.net> On 12/21/2011 4:10 PM, Alan Gauld wrote: > On 21/12/11 19:56, Wayne Watson wrote: > >>> To clarify: Python on Windows does **not** put itself on the System >>> PATH when installed. >> So, PythonNN, where NN is the version, should never appear in PATH? > > Not from a standard Python installation. > But other programs whjich use Pythonn may install a version and modify > the PATH for you, or you may, for your own benefit, add it manually. > I always add a new Python version to my PATH as a matter of course. > >> It's conceivable when I raised some of the questions a month of so ago, >> someone suggested putting PythonNN on the path. > > Very possible indeed. > >>> likely the application that *did* put it there is the **same** >>> application that is now complaining about the fact that it can't find >>> the Python 2.5 DLL when you boot up... >> See my mis-copy 26.dll in my other post to you. > > OK, But the principle remains. If you have an app in your startup > sequence that expects to find Python it will complain. Per my new sub thread {Reset], Uniblue seems to the trouble maker with 26.dll. > > You can check your startup sequence using a Microsoft tool. > MSCONFIG or somesuch. Google Windows startup tool or similar... > You can disable individual programs and restart to find out > what is causing it. I see msconfig.exe, but at the moment am hesitant to use it. > >>>> I have no idea why some remnant of why Python6 is hanging around. I >>>> uninstalled it long ago too. > > The problem is that it is not hanging around and some app expects > it to be there. The error message is about a missing file... > > One thing that may be significant... > Are you installing your Windows Python versions from > python.org or from ActiveState? They are very similar > but not identical. from Python Org. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Thu Dec 22 17:14:15 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Dec 2011 08:14:15 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF34EF6.2030002@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> Message-ID: <4EF35757.2030105@sbcglobal.net> I just searched the registry for the dll. Nothing. I then searched for python. It found a a Python "folder" with a PythonCore folder. Under it are three folders: 2.5, 2.7 and 3.2. I do recall installing 3.2, but I'm pretty sure I uninstalled it. Under each of the three folders is Module. Looking at the contents shows only default (name) REG_SZ (type) for each. Nothing else. OK,in scrolling around I see another Python "folder" and PythonCore under it, and subfolders 2.7 and 3.2. Under 2.7 are the subfolders Help, InstallPath, Modules, PythonPath. For 3.2, just an empty Modules. All of these are under SOFTWARE. The first set of three is under WOW6432Node, which is under SOFTWARE. Interesting, but it doesn't reveal much to me. For more fun, I searched for idle. It's buried under Interface, and the entry is REG_SZ with value idlesettings. From cranky.frankie at gmail.com Thu Dec 22 17:33:01 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Thu, 22 Dec 2011 11:33:01 -0500 Subject: [Tutor] possibly a version error Message-ID: On the bottom of this web page: http://developer.yahoo.com/python/python-xml.html is a program that reads an RSS feed for the weather and then parses the XML to show weather data by a zip code you input. I'm trying to run this under Python 3.2 and get this error: Traceback (most recent call last): File "D:\MyDocs\Python\Element Tree for XML\weather.py", line 27, in pprint(weather_for_zip(12303)) File "D:\MyDocs\Python\Element Tree for XML\weather.py", line 10, in weather_for_zip dom = minidom.parse(urllib.urlopen(url)) AttributeError: 'module' object has no attribute 'urlopen' I'm wondering if this is because this is Python 2.x code? Can someone who has 2.x try to run this and let me know if that's the problem? Is there a way to get this to work in Python 3.2? -- Frank L. "Cranky Frankie" Palmeri From sierra_mtnview at sbcglobal.net Thu Dec 22 17:37:37 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Dec 2011 08:37:37 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF35757.2030105@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> Message-ID: <4EF35CD1.1040109@sbcglobal.net> More. I did some Googling on IDLE not appearing. My case appears not to be unique. One site offered this as a solution in 2.6, C:\Python27>python.exe \Lib\idlelib\idle.py. It issued a complaint that "no such file or directory exists". It however does. A place to go that may clear this up might be . I found the suggestion above there. There are other comments about this issue there, but I haven't sorted through all of them. From hugo.yoshi at gmail.com Thu Dec 22 17:41:40 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 22 Dec 2011 17:41:40 +0100 Subject: [Tutor] possibly a version error In-Reply-To: References: Message-ID: On Thu, Dec 22, 2011 at 5:33 PM, Cranky Frankie wrote: > On the bottom of this web page: > > http://developer.yahoo.com/python/python-xml.html > > is a program that reads an RSS feed for the weather and then parses > the XML to show weather data by a zip code you input. I'm trying to > run this under Python 3.2 and get this error: > > Traceback (most recent call last): > ?File "D:\MyDocs\Python\Element Tree for XML\weather.py", line 27, in > ? ?pprint(weather_for_zip(12303)) > ?File "D:\MyDocs\Python\Element Tree for XML\weather.py", line 10, in > weather_for_zip > ? ?dom = minidom.parse(urllib.urlopen(url)) > AttributeError: 'module' object has no attribute 'urlopen' > > I'm wondering if this is because this is Python 2.x code? Can someone > who has 2.x try to run this and let me know if that's the problem? Is > there a way to get this to work in Python 3.2? > I usually find it helpful to check the documentation before doing anything else when I encounter errors like this in code found online. Right here: http://docs.python.org/library/urllib.html At the top of the page you should find the information you need (you're right on the money, basically). HTH, Hugo From cranky.frankie at gmail.com Thu Dec 22 18:09:40 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Thu, 22 Dec 2011 12:09:40 -0500 Subject: [Tutor] possibly a version error In-Reply-To: References: Message-ID: It says to use import urllib2 but I get this error: Traceback (most recent call last): File "D:\MyDocs\Python\Element Tree for XML\weather.py", line 2, in import urllib2 ImportError: No module named urllib2 On Thu, Dec 22, 2011 at 11:41 AM, Hugo Arts wrote: > On Thu, Dec 22, 2011 at 5:33 PM, Cranky Frankie > wrote: >> On the bottom of this web page: >> >> http://developer.yahoo.com/python/python-xml.html >> >> is a program that reads an RSS feed for the weather and then parses >> the XML to show weather data by a zip code you input. I'm trying to >> run this under Python 3.2 and get this error: >> >> Traceback (most recent call last): >> ?File "D:\MyDocs\Python\Element Tree for XML\weather.py", line 27, in >> ? ?pprint(weather_for_zip(12303)) >> ?File "D:\MyDocs\Python\Element Tree for XML\weather.py", line 10, in >> weather_for_zip >> ? ?dom = minidom.parse(urllib.urlopen(url)) >> AttributeError: 'module' object has no attribute 'urlopen' >> >> I'm wondering if this is because this is Python 2.x code? Can someone >> who has 2.x try to run this and let me know if that's the problem? Is >> there a way to get this to work in Python 3.2? >> > > I usually find it helpful to check the documentation before doing > anything else when I encounter errors like this in code found online. > Right here: > > http://docs.python.org/library/urllib.html > > At the top of the page you should find the information you need > (you're right on the money, basically). > > HTH, > Hugo -- Frank L. "Cranky Frankie" Palmeri From cranky.frankie at gmail.com Thu Dec 22 18:13:19 2011 From: cranky.frankie at gmail.com (Cranky Frankie) Date: Thu, 22 Dec 2011 12:13:19 -0500 Subject: [Tutor] possibly a version error Message-ID: I got it to work: Use this for the import - import urllib.request the use this: dom = minidom.parse(urllib.request.urlopen(url)) Here's the code that works in 3.2: from pprint import pprint import urllib.request from xml.dom import minidom WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s' WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' def weather_for_zip(zip_code): url = WEATHER_URL % zip_code dom = minidom.parse(urllib.request.urlopen(url)) forecasts = [] for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'): forecasts.append({ 'date': node.getAttribute('date'), 'low': node.getAttribute('low'), 'high': node.getAttribute('high'), 'condition': node.getAttribute('text') }) ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0] return { 'current_condition': ycondition.getAttribute('text'), 'current_temp': ycondition.getAttribute('temp'), 'forecasts': forecasts, 'title': dom.getElementsByTagName('title')[0].firstChild.data } pprint(weather_for_zip(12303)) -- Frank L. "Cranky Frankie" Palmeri From alan.gauld at btinternet.com Thu Dec 22 18:58:33 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Dec 2011 17:58:33 +0000 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF35CD1.1040109@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> Message-ID: On 22/12/11 16:37, Wayne Watson wrote: > C:\Python27>python.exe \Lib\idlelib\idle.py. It issued a complaint that > "no such file or directory exists". It however does. It almost certainly doesn't. The \ in front of Lib says look in the root directory of the C drive. You probably need: C:\Python27> python.exe Lib\idlelib\idle.py. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From james.homme at highmark.com Thu Dec 22 19:52:42 2011 From: james.homme at highmark.com (Homme, James) Date: Thu, 22 Dec 2011 18:52:42 +0000 Subject: [Tutor] Guidance About Installing First Python Module Message-ID: Hi, This is on Windows XP Professional. Before asking this question, I read the tutorial at PyPi, among other things. By the time I was done attempting to figure out seemingly conflicting documentation about how to get and install Python modules, I attempted to deduce that I should get virtualenv.py, which would go and get some magic stuff that then would enable me to start to install other Python modules. I downloaded it and ran it. It pointed out an error, and said that this usually happens when someone installs Python for just their user. That was true for me. I uninstalled and re-installed Python, this time for all users. I noticed that the entire error message didn't print out, so I opened up the program and found the whole error message. It says this. Note: some Windows users have reported this error when they installed Python for "Only this user". The problem may be resolvable if you install Python "For all users". (See https://bugs.launchpad.net/virtualenv/+bug/352844). I went to that page and read some stuff that says that the program needs to find python25.dll or python26.dll, so I popped open Windows Find and searched for Python*.dll. I found some older dll's like python25.dll and python26.dll in other folders, but not my Python 2.7.2 setup. I went back to the page where the bug is reported and clicked to see the full activity log. There was nothing about Python 27 in there. How should I proceed? Thanks. Jim Jim Homme, Usability Services, Phone: 412-544-1810. ________________________________ This e-mail and any attachments to it are confidential and are intended solely for use of the individual or entity to whom they are addressed. If you have received this e-mail in error, please notify the sender immediately and then delete it. If you are not the intended recipient, you must not keep, use, disclose, copy or distribute this e-mail without the author's prior permission. The views expressed in this e-mail message do not necessarily represent the views of Highmark Inc., its subsidiaries, or affiliates. From sierra_mtnview at sbcglobal.net Thu Dec 22 20:08:26 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Dec 2011 11:08:26 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> Message-ID: <4EF3802A.2050300@sbcglobal.net> Ah, yes.Thanks. That is, I think, was the what I copied from some web page. OK, I just tried it, and got several messages. C:\Python27>python.exe Lib\idlelib\idle.py Traceback (most recent call last): File "Lib\idlelib\idle.py", line 11, in idlelib.PyShell.main() File "C:\Python27\Lib\idlelib\PyShell.py", line 1403, in main shell = flist.open_shell() File "C:\Python27\Lib\idlelib\PyShell.py", line 279, in open_shell self.pyshell = PyShell(self) File "C:\Python27\Lib\idlelib\PyShell.py", line 832, in __init__ OutputWindow.__init__(self, flist, None, None) File "C:\Python27\Lib\idlelib\OutputWindow.py", line 16, in __init__ EditorWindow.__init__(self, *args) File "C:\Python27\Lib\idlelib\EditorWindow.py", line 273, in __init__ self.update_recent_files_list() File "C:\Python27\Lib\idlelib\EditorWindow.py", line 799, in update_recent_files_list rf_file = open(self.recent_files_path, 'w') IOError: [Errno 13] Permission denied: 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' ------------------------- Maybe as I pointed out a few msgs ago here the permissions shown on Properties looked a bit odd. On 12/22/2011 9:58 AM, Alan Gauld wrote: > On 22/12/11 16:37, Wayne Watson wrote: > >> C:\Python27>python.exe \Lib\idlelib\idle.py. It issued a complaint that >> "no such file or directory exists". It however does. > > It almost certainly doesn't. The \ in front of Lib says look in the > root directory of the C drive. > > You probably need: > > C:\Python27> python.exe Lib\idlelib\idle.py. > > HTH > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From alan.gauld at btinternet.com Thu Dec 22 23:34:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Dec 2011 22:34:01 +0000 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF3802A.2050300@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> Message-ID: On 22/12/11 19:08, Wayne Watson wrote: > IOError: [Errno 13] Permission denied: > 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' > ------------------------- > Maybe as I pointed out a few msgs ago here the permissions shown on > Properties looked a bit odd. But the problem here is with .idlerc in your home directory. Can you find that file and ensure that read/write permissions are set? It may be a hidden file so you might have to tweak the View settings. .idelrc is presumably where Idle stores your local config settings. Although I confess I never noticed it when I used Windows. But then I probably never had a need to notice it! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Thu Dec 22 23:58:18 2011 From: bgailer at gmail.com (bob gailer) Date: Thu, 22 Dec 2011 17:58:18 -0500 Subject: [Tutor] =?windows-1252?q?What_is_=99?= Message-ID: <4EF3B60A.5020907@gmail.com> >>> "?" '\xe2\x84\xa2' What is this hex string? -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Fri Dec 23 00:30:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 23 Dec 2011 10:30:25 +1100 Subject: [Tutor] =?windows-1252?q?What_is_=99?= In-Reply-To: <4EF3B60A.5020907@gmail.com> References: <4EF3B60A.5020907@gmail.com> Message-ID: <4EF3BD91.6050007@pearwood.info> bob gailer wrote: > >>> "?" > '\xe2\x84\xa2' > > What is this hex string? Presumably you are running Python 2, yes? I will assume that you are using Python 2 in the following explanation. You have just run smack bang into a collision between text and bytes, and in particular, the fact that your console is probably Unicode aware, but Python so-called strings are by default bytes and not text. When you enter "?", your console is more than happy to allow you to enter a Unicode trademark character[1] and put it in between " " delimiters. This creates a plain bytes string. But the ? character is not a byte, and shouldn't be treated as one -- Python should raise an error, but in an effort to be helpful, instead it tries to automatically encode that character to bytes using some default encoding. (Probably UTF-8.) The three hex bytes you actually get is the encoding of the TM character. Python 2 does have proper text strings, but you have to write it as a unicode string: py> s = u"?" py> len(s) 1 py> s u'\u2122' py> print s ? py> s.encode('utf-8') '\xe2\x84\xa2' Notice that encoding the trademark character to UTF-8 gives the same sequence of bytes as Python guesses on your behalf, which supports my guess that it is using UTF-8 by default. If you take the three character byte string and decode it using UTF-8, you will get the trademark character back. If all my talk of encodings doesn't mean anything to you, you should read this: http://www.joelonsoftware.com/articles/Unicode.html [1] Assuming your console is set to use the same encoding as my mail client is using. Otherwise I'm seeing something different to you. -- Steven From badouglas at gmail.com Fri Dec 23 03:11:43 2011 From: badouglas at gmail.com (bruce) Date: Thu, 22 Dec 2011 21:11:43 -0500 Subject: [Tutor] list issue.. i think Message-ID: hi. got a test where i have multiple lists with key/values. trying to figure out how to do a join/multiply, or whatever python calls it, where i have a series of resulting lists/dicts that look like the following.. the number of lists/rows is dynamic.. the size of the list/rows will also be dynamic as well. i've looked over the py docs, as well as different potential solns.. psuedo code, or pointers would be helpful. thanks... test data a['a1']=['a1','a2','a3'] a['a2']=['b1','b2','b3'] a['a3']=['c1','c2','c3'] end test result:: a1:a1,a2:b1,a3:c1 a1:a2,a2:b1,a3:c1 a1:a3,a2:b1,a3:c1 a1:a1,a2:b2,a3:c1 a1:a2,a2:b2,a3:c1 a1:a3,a2:b2,a3:c1 a1:a1,a2:b3,a3:c1 a1:a2,a2:b3,a3:c1 a1:a3,a2:b3,a3:c1 a1:a1,a2:b1,a3:c2 a1:a2,a2:b1,a3:c2 a1:a3,a2:b1,a3:c2 a1:a1,a2:b2,a3:c2 a1:a2,a2:b2,a3:c2 a1:a3,a2:b2,a3:c2 a1:a1,a2:b3,a3:c2 a1:a2,a2:b3,a3:c2 a1:a3,a2:b3,a3:c2 a1:a1,a2:b1,a3:c3 a1:a2,a2:b1,a3:c3 a1:a3,a2:b1,a3:c3 a1:a1,a2:b2,a3:c3 a1:a2,a2:b2,a3:c3 a1:a3,a2:b2,a3:c3 a1:a1,a2:b3,a3:c3 a1:a2,a2:b3,a3:c3 a1:a3,a2:b3,a3:c3 -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Fri Dec 23 04:34:58 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 23 Dec 2011 03:34:58 +0000 Subject: [Tutor] list issue.. i think In-Reply-To: References: Message-ID: On 23 December 2011 02:11, bruce wrote: > hi. > > got a test where i have multiple lists with key/values. trying to figure out > how to do a join/multiply, or whatever python calls it, where i have a > series of resulting lists/dicts that look like the following.. > > the number of lists/rows is dynamic.. > the size of the list/rows will also be dynamic as well. > > i've looked over the py docs, as well as different potential solns.. > > psuedo code, or pointers would be helpful. > > thanks... > > test data > a['a1']=['a1','a2','a3'] > a['a2']=['b1','b2','b3'] > a['a3']=['c1','c2','c3'] > > end test result:: > a1:a1,a2:b1,a3:c1 > a1:a2,a2:b1,a3:c1 > a1:a3,a2:b1,a3:c1 > > a1:a1,a2:b2,a3:c1 > a1:a2,a2:b2,a3:c1 > a1:a3,a2:b2,a3:c1 > > a1:a1,a2:b3,a3:c1 > a1:a2,a2:b3,a3:c1 > a1:a3,a2:b3,a3:c1 > > a1:a1,a2:b1,a3:c2 > a1:a2,a2:b1,a3:c2 > a1:a3,a2:b1,a3:c2 > > a1:a1,a2:b2,a3:c2 > a1:a2,a2:b2,a3:c2 > a1:a3,a2:b2,a3:c2 > > a1:a1,a2:b3,a3:c2 > a1:a2,a2:b3,a3:c2 > a1:a3,a2:b3,a3:c2 > > a1:a1,a2:b1,a3:c3 > a1:a2,a2:b1,a3:c3 > a1:a3,a2:b1,a3:c3 > > a1:a1,a2:b2,a3:c3 > a1:a2,a2:b2,a3:c3 > a1:a3,a2:b2,a3:c3 > > a1:a1,a2:b3,a3:c3 > a1:a2,a2:b3,a3:c3 > a1:a3,a2:b3,a3:c3 > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I think you want to take a look at the itertools module (http://docs.python.org/library/itertools.html), probably itertools.product, although I can't see exactly what you want as a final result. The process will be something like: turn a into list of lists of key:value pairs call itertools.product() using star notation (http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) to turn the list into sequential arguments -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T.? Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 From steve at pearwood.info Fri Dec 23 04:39:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 23 Dec 2011 14:39:16 +1100 Subject: [Tutor] list issue.. i think In-Reply-To: References: Message-ID: <4EF3F7E4.10504@pearwood.info> bruce wrote: > hi. > > got a test where i have multiple lists with key/values. trying to figure > out how to do a join/multiply, or whatever python calls it, where i have a Whatever Python calls what? You need to explain what *you* mean by "a join/multiply" before we can tell what you are referring to. Perhaps start with a simple example? > series of resulting lists/dicts that look like the following.. > > the number of lists/rows is dynamic.. > the size of the list/rows will also be dynamic as well. > > i've looked over the py docs, as well as different potential solns.. > > psuedo code, or pointers would be helpful. > > thanks... > > test data > a['a1']=['a1','a2','a3'] > a['a2']=['b1','b2','b3'] > a['a3']=['c1','c2','c3'] If you're indexing by key rather than by position, you need a dict, not a list. So: a = {} a['a1']=['a1','a2','a3'] a['a2']=['b1','b2','b3'] a['a3']=['c1','c2','c3'] > end test result:: > a1:a1,a2:b1,a3:c1 > a1:a2,a2:b1,a3:c1 > a1:a3,a2:b1,a3:c1 I don't even understand what that is supposed to mean. -- Steven From sierra_mtnview at sbcglobal.net Fri Dec 23 05:20:01 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Dec 2011 20:20:01 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> Message-ID: <4EF40171.9030508@sbcglobal.net> Hi, I found it, but not in a place I would expect. It's under my username, Wayne. It is a folder and has three files: breakpoints.lst recent-files.lst ZZrecent-files.lst The last one has the odd ZZ, but is empty. breakpoints.lst is empty too. recent-files.lst contains about 21 files like: C:\Users\Wayne\Sandia_Meteors\Trajectory_Estimation\radiant.py C:\Users\Wayne\Sandia_Meteors\Trajectory_Estimation\cross_prod.py ZZ... is the most recent file, 7/18/2011. If I right-click .idlerc, I can see properties for SYSTEM, some very oddly named user, Wayne, Admin, and WMPNetwork. On 12/22/2011 2:34 PM, Alan Gauld wrote: > On 22/12/11 19:08, Wayne Watson wrote: > >> IOError: [Errno 13] Permission denied: >> 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' >> ------------------------- >> Maybe as I pointed out a few msgs ago here the permissions shown on >> Properties looked a bit odd. > > But the problem here is with .idlerc in your home directory. > > Can you find that file and ensure that read/write permissions > are set? It may be a hidden file so you might have to tweak > the View settings. > > .idelrc is presumably where Idle stores your local config settings. > Although I confess I never noticed it when I used Windows. But then I > probably never had a need to notice it! > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From lina.lastname at gmail.com Fri Dec 23 11:01:21 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 23 Dec 2011 18:01:21 +0800 Subject: [Tutor] something relevant to array Message-ID: Hi, 1] How to input some column in idle like: a a a 2] I want to combine a series of files like a.txt 1 a 2 a 3 a b.txt 1 b 2 b 3 b into one as: a b a b a b The work-in-progress code as following, #!/usr/bin/python3 import os INFILEEXT = ".xvg" NUM_OF_FILE = 10 if __name__=="__main__": result = [0]*NUM_OF_FILE for i in range(NUM_OF_FILE): filename = "A_mindist_" + str(i+1) + INFILEEXT #text = open(filename,"r").readlines() with open(filename,"r") as f: for line in f: parts = f.readline().strip() if len(parts) == 26: dist = parts.split()[1] print(dist) result[i].append(dist) print(result) $ cat A_mindist_1.xvg 4.640000e+05 3.169008e-01 4.680000e+05 4.319328e-01 4.720000e+05 5.126960e-01 $ cat A_mindist_2.xvg 4.640000e+05 5.237660e-01 4.680000e+05 2.352828e-01 4.720000e+05 2.280239e-01 I wish result[0] = 3.169008e-01 4.319328e-01 5.126960e-01 result[1] = 5.237660e-01 2.352828e-01 2.280239e-01 Thanks with best regards, From steve at pearwood.info Fri Dec 23 11:24:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 23 Dec 2011 21:24:24 +1100 Subject: [Tutor] list mail formatting In-Reply-To: References: <20111221114905.GA27863@kontrol.kode5.net> Message-ID: <4EF456D8.9040607@pearwood.info> Alexander Etter wrote: > Ah I know of what you mentioned. On an GNU Emacs mailing list I was advised to avoid anything but plaintext. > It just seems so archaic. But I'm a novice and will learn why eventually. There's a number of reasons. In no particular order, and in all cases "you" is generic you, not you personally. * Mastery of your tools. Are you the master of your tools, or are they the master of you? If the writer can't turn off HTML mail in common mail clients, there is little hope that he can control a compiler, an editor, source control, etc. And if he *won't* turn it off, that shows laziness and carelessness to others that reflects badly. Especially in the open source coding community, including here, your reputation is worth more than gold. * Code is plain text. Editors sometimes use colour and formatting to highlight parts of the code, but fundamentally, programming is about reading and writing code. If you need fancy fonts and formatting and dancing paperclips to get your message across, chances are you will never be more than a mediocre programmer. * Mail client independence. The people you are writing to use a wide variety of mail clients, under many different circumstances. They might be logged into a Unix server with only a primitive command-line mail app; they might be using mutt, or Thunderbird, or Outlook, or possibly not even reading it via mail at all, but via a newsgroup on Usenet. All of these programs may display your message differently. You have no control over the presentation that the user will see -- best to make the fewest assumptions, namely, plain text, and not rely on features which may be missing. * Your readers may be colour blind, and your red and green lines may look identical. Or they may be completely blind, and using a screen reader. Or they might prefer to disable HTML emails, and avoid all the dangers and problems with it (security vulnerabilities, privacy breaches, and the rest). Or they might be sick and tired of straining to reading crappy emails with light blue text on a slightly darker blue background. Either way, your formatting is lost. Don't expect people to turn on HTML display just for you. * Layout of code (especially Python code) is special. Your mail client may mangle the layout. It is very common to see code posted where all indentation is lost, or even line breaks, so everything is squashed into a single line: def func(a, b): while b < 100: print b b += 1 print a-b Or every line is separated by a blank line, which makes it a PITA to paste into the interactive interpreter. Even if the reader can fix the mangling, they shouldn't have to. -- Steven From roadierich at googlemail.com Fri Dec 23 11:25:23 2011 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 23 Dec 2011 10:25:23 +0000 Subject: [Tutor] something relevant to array In-Reply-To: References: Message-ID: On 23 December 2011 10:01, lina wrote: > Hi, > > 1] How to input some column in idle > > like: > > a > a > a > > 2] I want to combine a series of files like > > a.txt > > 1 a > 2 a > 3 a > > b.txt > > 1 b > 2 b > 3 b > > into one as: > a b > a b > a b > > The work-in-progress code as following, > > > #!/usr/bin/python3 > > import os > > INFILEEXT = ".xvg" > > NUM_OF_FILE = 10 > > if __name__=="__main__": > ? ?result = [0]*NUM_OF_FILE > ? ?for i in range(NUM_OF_FILE): > > ? ? ? ?filename = "A_mindist_" + str(i+1) + INFILEEXT > ? ? ? ?#text = open(filename,"r").readlines() > ? ? ? ?with open(filename,"r") as f: > ? ? ? ? ? ?for line in f: > ? ? ? ? ? ? ? ?parts = f.readline().strip() > ? ? ? ? ? ? ? ?if len(parts) == 26: > ? ? ? ? ? ? ? ? ? ?dist = parts.split()[1] > ? ? ? ? ? ? ? ? ? ?print(dist) > ? ? ? ? ? ? ? ? ? ?result[i].append(dist) > ? ?print(result) > > $ cat A_mindist_1.xvg > 4.640000e+05 ?3.169008e-01 > 4.680000e+05 ?4.319328e-01 > 4.720000e+05 ?5.126960e-01 > > > $ cat A_mindist_2.xvg > 4.640000e+05 ?5.237660e-01 > 4.680000e+05 ?2.352828e-01 > 4.720000e+05 ?2.280239e-01 > > > I wish > result[0] ?= > 3.169008e-01 > 4.319328e-01 > 5.126960e-01 > > result[1] = > 5.237660e-01 > 2.352828e-01 > 2.280239e-01 > > > Thanks with best regards, > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You can't append to an int, you need to initialise your result list with lists. Instead of result = [0]*NUM_OF_FILE you need result= [ [] for i in range(NUM_OF_FILES) ] In the future, please include the error message you receive when trying to run the program. -- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T.? Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 From alan.gauld at btinternet.com Fri Dec 23 11:42:44 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Dec 2011 10:42:44 +0000 Subject: [Tutor] something relevant to array In-Reply-To: References: Message-ID: On 23/12/11 10:01, lina wrote: > with open(filename,"r") as f: > for line in f: > parts = f.readline().strip() Are you sure you want to do this? You are already reading a line from the file in the for loop. This will read the next line. So parts will comprise every second line in the file. Is that what you want? > if len(parts) == 26: > dist = parts.split()[1] > print(dist) > result[i].append(dist) > print(result) > > $ cat A_mindist_1.xvg > 4.640000e+05 3.169008e-01 > 4.680000e+05 4.319328e-01 > 4.720000e+05 5.126960e-01 > > > $ cat A_mindist_2.xvg > 4.640000e+05 5.237660e-01 > 4.680000e+05 2.352828e-01 > 4.720000e+05 2.280239e-01 > > > I wish > result[0] = > 3.169008e-01 > 4.319328e-01 > 5.126960e-01 > > result[1] = > 5.237660e-01 > 2.352828e-01 > 2.280239e-01 This suggests you want each line so i'd expect your code to look more like with open(filename,"r") as f: for line in f: result[i].append(line.strip().split()[1]) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lina.lastname at gmail.com Fri Dec 23 11:48:13 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 23 Dec 2011 18:48:13 +0800 Subject: [Tutor] something relevant to array In-Reply-To: References: Message-ID: On Fri, Dec 23, 2011 at 6:42 PM, Alan Gauld wrote: > On 23/12/11 10:01, lina wrote: > >> ? ? ? ? with open(filename,"r") as f: >> ? ? ? ? ? ? for line in f: >> ? ? ? ? ? ? ? ? parts = f.readline().strip() > > > Are you sure you want to do this? > You are already reading a line from the file in the for loop. > This will read the next line. So parts will comprise every second line in > the file. Is that what you want? No. that's why I am so confusing now. why the results so un-expected. did not print the even line out (if the first line is odd line). > > > >> ? ? ? ? ? ? ? ? if len(parts) == 26: >> ? ? ? ? ? ? ? ? ? ? dist = parts.split()[1] >> ? ? ? ? ? ? ? ? ? ? print(dist) >> ? ? ? ? ? ? ? ? ? ? result[i].append(dist) >> ? ? print(result) >> >> $ cat A_mindist_1.xvg >> 4.640000e+05 ?3.169008e-01 >> 4.680000e+05 ?4.319328e-01 >> 4.720000e+05 ?5.126960e-01 >> >> >> $ cat A_mindist_2.xvg >> 4.640000e+05 ?5.237660e-01 >> 4.680000e+05 ?2.352828e-01 >> 4.720000e+05 ?2.280239e-01 >> >> >> I wish >> result[0] ?= >> 3.169008e-01 >> 4.319328e-01 >> 5.126960e-01 >> >> result[1] = >> 5.237660e-01 >> 2.352828e-01 >> 2.280239e-01 > > > This suggests you want each line so i'd expect your code to look more like > > > ? ? ? ? with open(filename,"r") as f: > ? ? ? ? ? ? for line in f: > ? ? ? ? ? ? ? ? result[i].append(line.strip().split()[1]) > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From lina.lastname at gmail.com Fri Dec 23 12:02:48 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 23 Dec 2011 19:02:48 +0800 Subject: [Tutor] something relevant to array In-Reply-To: References: Message-ID: #!/usr/bin/python3 import os INFILEEXT = ".xvg" NUM_OF_FILES = 2 if __name__=="__main__": result = [ [] for i in range(NUM_OF_FILES)] for i in range(NUM_OF_FILES): filename = "A_mindist_" + str(i+1) + INFILEEXT #text = open(filename,"r").readlines() with open(filename,"r") as f: for line in f: if len(line.strip()) == 26: result[i].append(line.strip().split()[1]) for i in range(len(result)): for j in range(len(result[i])): print(result[i][j]) still have a little problem about print out, I wish to get like a a b b c c which will show in the same line, not as a b c a b c Thanks, cat A_dist_1.xvg @ legend loctype view @ legend 0.78, 0.8 @ legend length 2 @ s0 legend "r_24-r_29" 0.000000e+00 2.109407e-01 4.000000e+03 2.263405e-01 8.000000e+03 3.234825e-01 From alan.gauld at btinternet.com Fri Dec 23 13:01:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Dec 2011 12:01:19 +0000 Subject: [Tutor] something relevant to array In-Reply-To: References: Message-ID: On 23/12/11 11:02, lina wrote: > for i in range(len(result)): > for j in range(len(result[i])): > print(result[i][j]) You don't need all the indexing. Use Pythons for loop to get the items: for group in result: for item in group: print item, # comma prevents auto newline It's easier to read and less processing for the computer. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From pasokan at talentsprint.com Fri Dec 23 13:26:22 2011 From: pasokan at talentsprint.com (Asokan Pichai) Date: Fri, 23 Dec 2011 17:56:22 +0530 Subject: [Tutor] something relevant to array In-Reply-To: References: Message-ID: On Fri, Dec 23, 2011 at 3:31 PM, lina wrote: > > Hi, > [SNIPPED] > 2] I want to combine a series of files like > > a.txt > > 1 a > 2 a > 3 a > > b.txt > > 1 b > 2 b > 3 b > > into one as: > a b > a b > a b > Is this ok? ---------------------------------------------------------------------------------------- a = [line.split()[1] for line in open('a.txt') if len(line.strip()) == 26] b = [line.split()[1] for line in open('b.txt') if len(line.strip()) == 26] both = zip(a, b) ---------------------------------------------------------------------------------------- Asokan Pichai From andreas.perstinger at gmx.net Fri Dec 23 13:19:45 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Fri, 23 Dec 2011 13:19:45 +0100 Subject: [Tutor] something relevant to array In-Reply-To: References: Message-ID: <4EF471E1.1080604@gmx.net> On 2011-12-23 12:02, lina wrote: > for i in range(len(result)): > for j in range(len(result[i])): > print(result[i][j]) > > still have a little problem about print out, > > I wish to get like > a a > b b > c c > which will show in the same line, > > not as > a > b > c > a > b > c So you wish to print all the first elements from your sublists on the first line, all the second elements on the second line, and so on, right? Python 3.2 (r32:88445, Mar 25 2011, 19:28:28) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> result = [["a1", "b1", "c1"],["a2", "b2", "c2"],["a3", "b3", "c3"]] >>> for i in zip(*result): ... print(" ".join(i)) ... a1 a2 a3 b1 b2 b3 c1 c2 c3 Explanation: "zip()" takes an arbitrary number of iterables and "returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables." (see the docs on http://docs.python.org/py3k/library/functions.html#zip): >>> print(list(zip([1, 2, 3], [4, 5, 6]))) [(1, 4), (2, 5), (3, 6)] In your case, you would have to call "zip()" with zip(result[0], result[1], result[2], ... result[x]) depending on how many files you process. But using the *-operator you can unpack "result" (which is a list of sublists), so that "zip" will see all the sublists as separate arguments. See also http://docs.python.org/py3k/tutorial/controlflow.html#unpacking-argument-lists For printing you just join all the elements of one tuple to a string. HTH, Andreas From sierra_mtnview at sbcglobal.net Fri Dec 23 13:56:21 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 23 Dec 2011 04:56:21 -0800 Subject: [Tutor] Unable to remove three libs from XP Message-ID: <4EF47A75.7090905@sbcglobal.net> I have three py libs and the python program itself, 2.52, installed on an 6 year old HP Laptop. I decided to remove them, and removed Python with the Control Panel Add/Remove icon. Worked fine. When I tried to remove any of the remaining libs, press the add/remove button does nothing but blink. How do I get around this problem? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From jugurtha.hadjar at gmail.com Fri Dec 23 14:04:17 2011 From: jugurtha.hadjar at gmail.com (Jugurtha Hadjar) Date: Fri, 23 Dec 2011 14:04:17 +0100 Subject: [Tutor] possibly a version error In-Reply-To: References: Message-ID: <4EF47C51.4060205@gmail.com> On 22/12/2011 18:13, Cranky Frankie wrote: > I got it to work: > > Use this for the import - import urllib.request > > the use this: dom = minidom.parse(urllib.request.urlopen(url)) > > Here's the code that works in 3.2: > > from pprint import pprint > import urllib.request > from xml.dom import minidom > > WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s' > WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' > > def weather_for_zip(zip_code): > url = WEATHER_URL % zip_code > dom = minidom.parse(urllib.request.urlopen(url)) > forecasts = [] > for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'): > forecasts.append({ > 'date': node.getAttribute('date'), > 'low': node.getAttribute('low'), > 'high': node.getAttribute('high'), > 'condition': node.getAttribute('text') > }) > ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0] > return { > 'current_condition': ycondition.getAttribute('text'), > 'current_temp': ycondition.getAttribute('temp'), > 'forecasts': forecasts, > 'title': dom.getElementsByTagName('title')[0].firstChild.data > } > > pprint(weather_for_zip(12303)) > Hello, I tried it and it works fine (Python 3.2, Windows XP (5.1.2600) ) Here's what I got: {'current_condition': 'Light Rain', 'current_temp': '37', 'forecasts': [{'condition': 'AM Rain/Snow', 'date': '23 Dec 2011', 'high': '39', 'low': '16'}, {'condition': 'Partly Cloudy', 'date': '24 Dec 2011', 'high': '31', 'low': '20'}], 'title': 'Yahoo! Weather - Schenectady, NY'} I'll probably tinker with it to make it show the weather here in Algiers (Algeria, North Africa). Thanks, -- ~Jugurtha Hadjar, From lina.lastname at gmail.com Fri Dec 23 14:08:26 2011 From: lina.lastname at gmail.com (lina) Date: Fri, 23 Dec 2011 21:08:26 +0800 Subject: [Tutor] something relevant to array In-Reply-To: <4EF471E1.1080604@gmx.net> References: <4EF471E1.1080604@gmx.net> Message-ID: On Fri, Dec 23, 2011 at 8:19 PM, Andreas Perstinger wrote: > On 2011-12-23 12:02, lina wrote: >> >> ? ? for i in range(len(result)): >> ? ? ? ? for j in range(len(result[i])): >> ? ? ? ? ? ? print(result[i][j]) >> >> still have a little problem about print out, >> >> I wish to get like >> a a >> b b >> c c >> which will show in the same line, >> >> not as >> a >> b >> c >> a >> b >> c > > > So you wish to print all the first elements from your sublists on the first > line, all the second elements on the second line, and so on, right? yes. > > Python 3.2 (r32:88445, Mar 25 2011, 19:28:28) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> result = [["a1", "b1", "c1"],["a2", "b2", "c2"],["a3", "b3", "c3"]] >>>> for i in zip(*result): > ... ? print(" ".join(i)) > ... > a1 a2 a3 > b1 b2 b3 > c1 c2 c3 > > Explanation: > "zip()" takes an arbitrary number of iterables and "returns an iterator of > tuples, where the i-th tuple contains the i-th element from each of the > argument sequences or iterables." (see the docs on > http://docs.python.org/py3k/library/functions.html#zip): > >>>> print(list(zip([1, 2, 3], [4, 5, 6]))) > [(1, 4), (2, 5), (3, 6)] > > In your case, you would have to call "zip()" with > > zip(result[0], result[1], result[2], ... result[x]) > > depending on how many files you process. > > But using the *-operator you can unpack "result" (which is a list of > sublists), so that "zip" will see all the sublists as separate arguments. > See also > http://docs.python.org/py3k/tutorial/controlflow.html#unpacking-argument-lists > > For printing you just join all the elements of one tuple to a string. > > HTH, Andreas Thanks for all. really good suggestions. Best regards and have a weekend. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From jsantos.lazer at gmail.com Fri Dec 23 17:58:50 2011 From: jsantos.lazer at gmail.com (Joaquim Santos) Date: Fri, 23 Dec 2011 16:58:50 +0000 Subject: [Tutor] Python challenge and decryption Message-ID: Hi again list! I've been trying to implement the feedback I got. So far, I removed the print statements from the function, limited the range (just for the z at the moment) and tried to get all printing in one or two lines... but without success... I don't know if I'm doing the join as it should... The new list I ended up trying to populate it with 2 different ways, but without success when joined... This is the new (and a improved) code: import string def decrypt(cypheredText, shiftedCypherNumber): ''' This function will take two arguments. The first is the cyphered text, the second is the number of characters we need to shift the text so we can decrypt it. This is a Caesar cypher. ''' for letter in cypheredText: asciiValue = ord(letter) if asciiValue in range(97, 123): asciiValue += shiftedCypherNumber if asciiValue > 122: asciiValue -= 26 newLetter = chr(asciiValue) text = list() text.append(newLetter) joinedText = ' '.join(text) return joinedText text = 'g fmnc wms bgblr rpylqjyrc gr zw fylb' a = decrypt(text, 2) print a For the new list (text), I initially tried to do it like this -> text = list(newLetter) and only now resorted to the append... which way is more correct? Or which is not correct at all? And why is the return giving me just one letter? (the last one...) Thanks for all the tips so far. The maketrans like suggested probably would be faster but I didn't knew about it and now that I'm trying to grind this on my own I kind of prefer it... I'm learning more then if I used a function or something... The ASCII table was invaluable in making me rethink my approach! Merry Christmas to all in the list! In case someone doesn't believe in it, have a very nice weekend and all the best! Joaquim -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Dec 23 18:32:50 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 23 Dec 2011 17:32:50 +0000 Subject: [Tutor] Python challenge and decryption In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474082754@SCACMX008.exchad.jpmchase.net> Posting as HTML caused your indentation to be all wrong. Try to post as plain text to remove those errors. Thankfully your program is not very complicated. import string def decrypt(cypheredText, shiftedCypherNumber): ''' This function will take two arguments. The first is the cyphered text, the second is the number of characters we need to shift the text so we can decrypt it. This is a Caesar cypher. ''' for letter in cypheredText: asciiValue = ord(letter) if asciiValue in range(97, 123): asciiValue += shiftedCypherNumber if asciiValue > 122: asciiValue -= 26 newLetter = chr(asciiValue) text = list() text.append(newLetter) joinedText = ' '.join(text) return joinedText text = 'g fmnc wms bgblr rpylqjyrc gr zw fylb' a = decrypt(text, 2) print a You have very little range checking which means that it is very likely to not work (or behave oddly) for unexpected values. The biggest flaw I see is that your list is created at the wrong level. It should be outside the for loop. The problem with list creation being in the for loop is that you create a new list each iteration of the for loop and what happens to the old list? You lose it. If you created the list outside the for loop and my indentation above is incorrect then you created and appended to it after finishing your for loop. This would be incorrect because what would happen to all the values calculated inside the for loop? They would be lost. Either way, it is incorrect. You should declare text before the for loop and then append to it inside the for loop. The above is why you only get one letter and also why text=list(newLetter) is incorrect for your problem. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Fri Dec 23 19:49:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Dec 2011 18:49:07 +0000 Subject: [Tutor] Python challenge and decryption In-Reply-To: References: Message-ID: On 23/12/11 16:58, Joaquim Santos wrote: > Thanks for all the tips so far. The maketrans like suggested probably > would be faster but I didn't knew about it That's exactly the point. Very few people know about maketrans before they take the Python Challenge. But that's the whole point of the challenge, as you go through it you will discover new and powerful tools in the Python library that save you from having to invent your own. (Look out for the hints and pointers in the challenge!) If you try to complete the Python challenge without using new modules you will have a very long project in front of you!! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Fri Dec 23 20:54:11 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 23 Dec 2011 11:54:11 -0800 Subject: [Tutor] Unable to remove three libs from XP In-Reply-To: <4EF47A75.7090905@sbcglobal.net> References: <4EF47A75.7090905@sbcglobal.net> Message-ID: <4EF4DC63.2010506@sbcglobal.net> This is a laugher. The Add/Remove screen was hiding a dialog that wanted to know if I really wanted to remove the program. Argh. On 12/23/2011 4:56 AM, Wayne Watson wrote: > I have three py libs and the python program itself, 2.52, installed on > an 6 year old HP Laptop. I decided to remove them, and removed Python > with the Control Panel Add/Remove icon. Worked fine. When I tried to > remove any of the remaining libs, press the add/remove button does > nothing but blink. How do I get around this problem? > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From ramit.prasad at jpmorgan.com Fri Dec 23 21:47:05 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 23 Dec 2011 20:47:05 +0000 Subject: [Tutor] Unable to remove three libs from XP In-Reply-To: <4EF4DC63.2010506@sbcglobal.net> References: <4EF47A75.7090905@sbcglobal.net> <4EF4DC63.2010506@sbcglobal.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF4740828DE@SCACMX008.exchad.jpmchase.net> >This is a laugher. The Add/Remove screen was hiding a dialog that >wanted to know if I really wanted to remove the program. Argh. This is why I try and avoid pop-ups when I create a GUI app. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From mylesbroomes at hotmail.co.uk Fri Dec 23 22:21:18 2011 From: mylesbroomes at hotmail.co.uk (myles broomes) Date: Fri, 23 Dec 2011 21:21:18 +0000 Subject: [Tutor] Television simulation Message-ID: Im trying to create a 'Television simulation' program. Heres the code ive written for it: #television simulation #a program that simulates a television #the user can turn the television on or off, change the volume or change the channel #create the television class class Television(object): """A virtual television simulation""" def __init__(self): print("The television is off.") def power_button(self, power = "off"): if power == "off": power = "on" print("The power is now on.") else: power = "off" print("The power is now off.") def volume_button(self, volume = 0): up_or_down = input("Do you want to increase or decrease the volume? (up/down): ") if up_or_down == "up": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume > 10: volume = 10 print("The volume is now",volume) elif up_or_down == "down": amount = int(input("By how much? (Enter a number): ")) volume += amount if volume < 0: volume = 0 print("The volume is now",volume) else: print("That is not a valid choice.") def channel_button(self, channel = 1): new_channel = int(input("What channel do you want to watch? (Enter a number between 1 and 10.): ")) if new_channel < 1 or new_channel > 10: print("That is not a valid channel!") else: channel = new_channel print("The channel is now",channel) #create the main part of the program, the television simulation def main(): tv = Television() choice = None while choice != "0": print \ (""" Television simulation 0 - Quit 1 - Turn the television on or off 2 - Change the volume 3 - Change the channel """) choice = input("Choice: ") print() #exit if choice == "0": print("Good-bye.") #turn the television on or off elif choice == "1": tv.power_button() #increase or decrease the volume elif choice == "2": tv.volume_button() #change the channel elif choice == "3": tv.channel_button() else: print("\nInvalid choice!") main() ("\n\nPress the enter key to exit.") It works fine but the problem im having is that when volume, channel or power are changed inside of their methods, their values dont change in the program if that makes sense. So i was just wondering if there was a way around this. Thanks in advance, Myles Broomes From d at davea.name Fri Dec 23 22:43:24 2011 From: d at davea.name (Dave Angel) Date: Fri, 23 Dec 2011 16:43:24 -0500 Subject: [Tutor] Television simulation In-Reply-To: References: Message-ID: <4EF4F5FC.4060805@davea.name> On 12/23/2011 04:21 PM, myles broomes wrote: > Im trying to create a 'Television simulation' program. Heres the code ive written for it: > > #television simulation > #a program that simulates a television > #the user can turn the television on or off, change the volume or change the channel > > #create the television class > class Television(object): > """A virtual television simulation""" > def __init__(self): > print("The television is off.") > > def power_button(self, power = "off"): > if power == "off": > power = "on" The above line does nothing useful, as the value is thrown out when the method returns. Same is true in several other places below. > print("The power is now on.") > else: > power = "off" > print("The power is now off.") > > def volume_button(self, volume = 0): > up_or_down = input("Do you want to increase or decrease the volume? (up/down): ") > if up_or_down == "up": > amount = int(input("By how much? (Enter a number): ")) > volume += amount > if volume> 10: > volume = 10 > print("The volume is now",volume) > elif up_or_down == "down": > amount = int(input("By how much? (Enter a number): ")) > volume += amount > if volume< 0: > volume = 0 > print("The volume is now",volume) > else: > print("That is not a valid choice.") > > def channel_button(self, channel = 1): > new_channel = int(input("What channel do you want to watch? (Enter a number between 1 and 10.): ")) > if new_channel< 1 or new_channel> 10: > print("That is not a valid channel!") > else: > channel = new_channel > print("The channel is now",channel) > > #create the main part of the program, the television simulation > def main(): > tv = Television() > > choice = None > while choice != "0": > print \ > (""" > Television simulation > > 0 - Quit > 1 - Turn the television on or off > 2 - Change the volume > 3 - Change the channel > """) > > choice = input("Choice: ") > print() > > #exit > if choice == "0": > print("Good-bye.") > > #turn the television on or off > elif choice == "1": > tv.power_button() > > #increase or decrease the volume > elif choice == "2": > tv.volume_button() > > #change the channel > elif choice == "3": > tv.channel_button() > > else: > print("\nInvalid choice!") > > main() > ("\n\nPress the enter key to exit.") > > > It works fine but the problem im having is that when volume, channel or power are changed inside of their methods, their values dont change in the program if that makes sense. So i was just wondering if there was a way around this. > Normally when such values are changed in the method, you want a corresponding attribute of the instance to 'remember' the value. In your particular program you have one instance, called tv. Each time you call a method on that instance, such as tv.power_button(), you are implicitly passing that instance to the method, as the value 'self'. That's what you're not writing to correctly. Inside a method, you usually refer to such instance attributes as self.attribname. So let's try just one of them, the power button. def power_button(self): if self.power == "off": self.power = "on" else: self.power = 'off' print "Power is now ", self.power Notice I got rid of the unused parameter, since it was never referenced. One other thing we must do here: In the __init__() method, you need to initialize the state of the Television instance. You can't just print a statement saying it's initialized, you have to create each of the attributes comprising its initial state. In our case, we'd add a line self.power = "off" I'll leave the other two attributes to you. There are other things I could critique, but I want to give you the minimum push to make something that could run. -- DaveA From d at davea.name Fri Dec 23 22:57:19 2011 From: d at davea.name (Dave Angel) Date: Fri, 23 Dec 2011 16:57:19 -0500 Subject: [Tutor] Television simulation In-Reply-To: <4EF4F5FC.4060805@davea.name> References: <4EF4F5FC.4060805@davea.name> Message-ID: <4EF4F93F.7000403@davea.name> On 12/23/2011 04:43 PM, Dave Angel wrote: > On 12/23/2011 04:21 PM, myles broomes wrote: >> Im trying to create a 'Television simulation' program. Heres the code >> ive written for it: >> >> #television simulation >> #a program that simulates a television >> #the user can turn the television on or off, change the volume or >> change the channel >> >> #create the television class >> class Television(object): >> """A virtual television simulation""" >> def __init__(self): >> print("The television is off.") >> >> def power_button(self, power = "off"): >> if power == "off": >> power = "on" > The above line does nothing useful, as the value is thrown out when > the method returns. Same is true in several other places below. >> print("The power is now on.") >> else: >> power = "off" >> print("The power is now off.") >> >> def volume_button(self, volume = 0): >> up_or_down = input("Do you want to increase or >> decrease the volume? (up/down): ") >> if up_or_down == "up": >> amount = int(input("By how much? (Enter a >> number): ")) >> volume += amount >> if volume> 10: >> volume = 10 >> print("The volume is now",volume) >> elif up_or_down == "down": >> amount = int(input("By how much? (Enter a >> number): ")) >> volume += amount >> if volume< 0: >> volume = 0 >> print("The volume is now",volume) >> else: >> print("That is not a valid choice.") >> >> def channel_button(self, channel = 1): >> new_channel = int(input("What channel do you want to >> watch? (Enter a number between 1 and 10.): ")) >> if new_channel< 1 or new_channel> 10: >> print("That is not a valid channel!") >> else: >> channel = new_channel >> print("The channel is now",channel) >> >> #create the main part of the program, the television simulation >> def main(): >> tv = Television() >> >> choice = None >> while choice != "0": >> print \ >> (""" >> Television simulation >> >> 0 - Quit >> 1 - Turn the television on or off >> 2 - Change the volume >> 3 - Change the channel >> """) >> >> choice = input("Choice: ") >> print() >> >> #exit >> if choice == "0": >> print("Good-bye.") >> >> #turn the television on or off >> elif choice == "1": >> tv.power_button() >> >> #increase or decrease the volume >> elif choice == "2": >> tv.volume_button() >> >> #change the channel >> elif choice == "3": >> tv.channel_button() >> >> else: >> print("\nInvalid choice!") >> >> main() >> ("\n\nPress the enter key to exit.") >> >> >> It works fine but the problem im having is that when volume, channel >> or power are changed inside of their methods, their values dont >> change in the program if that makes sense. So i was just wondering if >> there was a way around this. >> > Normally when such values are changed in the method, you want a > corresponding attribute of the instance to 'remember' the value. In > your particular program you have one instance, called tv. Each time > you call a method on that instance, such as tv.power_button(), you are > implicitly passing that instance to the method, as the value 'self'. > That's what you're not writing to correctly. > > Inside a method, you usually refer to such instance attributes as > self.attribname. So let's try just one of them, the power button. > > def power_button(self): > if self.power == "off": > self.power = "on" > > else: > self.power = 'off' > print "Power is now ", self.power > > Notice I got rid of the unused parameter, since it was never referenced. > > One other thing we must do here: In the __init__() method, you need > to initialize the state of the Television instance. You can't just > print a statement saying it's initialized, you have to create each of > the attributes comprising its initial state. In our case, we'd add a > line > self.power = "off" > > > I'll leave the other two attributes to you. There are other things I > could critique, but I want to give you the minimum push to make > something that could run. > Bah - It lined up when I typed it, but I pasted some of the original, and typed the rest. Probably your email was html, when it should have been text. Let's try again, indenting 4 spaces instead, a much more reasonable number than 8. def power_button(self): if self.power == "off": self.power = "on" else: self.power = "off" print "Power is now ", self.power -- DaveA From m_harleman at hotmail.com Fri Dec 23 23:52:40 2011 From: m_harleman at hotmail.com (Michael Harleman) Date: Fri, 23 Dec 2011 17:52:40 -0500 Subject: [Tutor] possibly a version error In-Reply-To: <4EF47C51.4060205@gmail.com> References: , <4EF47C51.4060205@gmail.com> Message-ID: > Date: Fri, 23 Dec 2011 14:04:17 +0100 > From: jugurtha.hadjar at gmail.com > To: tutor at python.org > Subject: Re: [Tutor] possibly a version error > > On 22/12/2011 18:13, Cranky Frankie wrote: > > I got it to work: > > > > Use this for the import - import urllib.request > > > > the use this: dom = minidom.parse(urllib.request.urlopen(url)) > > > > Here's the code that works in 3.2: > > > > from pprint import pprint > > import urllib.request > > from xml.dom import minidom > > > > WEATHER_URL = 'http://xml.weather.yahoo.com/forecastrss?p=%s' > > WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0' > > > > def weather_for_zip(zip_code): > > url = WEATHER_URL % zip_code > > dom = minidom.parse(urllib.request.urlopen(url)) > > forecasts = [] > > for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'): > > forecasts.append({ > > 'date': node.getAttribute('date'), > > 'low': node.getAttribute('low'), > > 'high': node.getAttribute('high'), > > 'condition': node.getAttribute('text') > > }) > > ycondition = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0] > > return { > > 'current_condition': ycondition.getAttribute('text'), > > 'current_temp': ycondition.getAttribute('temp'), > > 'forecasts': forecasts, > > 'title': dom.getElementsByTagName('title')[0].firstChild.data > > } > > > > pprint(weather_for_zip(12303)) > > > > Hello, > > I tried it and it works fine (Python 3.2, Windows XP (5.1.2600) ) > > Here's what I got: > > {'current_condition': 'Light Rain', > 'current_temp': '37', > 'forecasts': [{'condition': 'AM Rain/Snow', > 'date': '23 Dec 2011', > 'high': '39', > 'low': '16'}, > {'condition': 'Partly Cloudy', > 'date': '24 Dec 2011', > 'high': '31', > 'low': '20'}], > 'title': 'Yahoo! Weather - Schenectady, NY'} > > > I'll probably tinker with it to make it show the weather here in Algiers > (Algeria, North Africa). > > Thanks, > > > -- > ~Jugurtha Hadjar, I'm a newbie, but I played around with your code to see if I could get it to work in 2.7 and it required changing the same line to: ???? dom = minidom.parse(urllib.URLopener().open(url)) Just in case someone here were to find that helpful. Mike Harleman From memilanuk at gmail.com Sat Dec 24 01:07:55 2011 From: memilanuk at gmail.com (Monte Milanuk) Date: Sat, 24 Dec 2011 00:07:55 +0000 (UTC) Subject: [Tutor] insert queries into related tables referencing foreign keys using python Message-ID: So... most python-sqlite tutorials concentrate on single tables. The few that deal with multiple tables and that mention foreign keys and such seem to demonstrate mainly using hard-coded data instead of parameterized insert queries into tables with auto-increment primary keys. For the most part I'm able to figure things out as I go using a variety of documents both print and electronic... but when I don't *know* the pk number (because its automatically assigned) it makes it tough to supply it as a foreign key for another insert query into related tables. Whats the 'right' way to do this sort of record insert or update query? Insert into the main table first, then do a select query to find the last rowid and store it in a python variable and then use that as a parameter for the rest of the insert queries to related tables? Pull the value from the seq column of the sqlite-sequence table for the table with the primary key, and use that (not sure how robust that would be down the road, or how portable it would be if I later moved to MySQL for the DB)? Or is this something an ORM like SQLalchemy would smooth over for me? In part I'm (also) wondering if this may be an artificial problem, as I'm trying to import data from a csv file i.e. one big table and then break it up and insert it into multiple tables in the sqlite database... From ajarncolin at gmail.com Sat Dec 24 01:32:12 2011 From: ajarncolin at gmail.com (col speed) Date: Sat, 24 Dec 2011 07:32:12 +0700 Subject: [Tutor] Python challenge and decryption In-Reply-To: References: Message-ID: > That's exactly the point. > Very few people know about maketrans before they take the Python Challenge. > > But that's the whole point of the challenge, as you go through it you will > discover new and powerful tools in the Python library that save you from > having to invent your own. (Look out for the hints and pointers in the > challenge!) > > If you try to complete the Python challenge without using new modules you > will have a very long project in front of you!! > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ Exactly. That's how I found out about it - after solving the challenge the other way! From lie.1296 at gmail.com Sat Dec 24 08:34:26 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 24 Dec 2011 18:34:26 +1100 Subject: [Tutor] insert queries into related tables referencing foreign keys using python In-Reply-To: References: Message-ID: On 12/24/2011 11:07 AM, Monte Milanuk wrote: > So... most python-sqlite tutorials concentrate on single tables. The few that > deal with multiple tables and that mention foreign keys and such seem to > demonstrate mainly using hard-coded data instead of parameterized insert queries > into tables with auto-increment primary keys. For the most part I'm able to > figure things out as I go using a variety of documents both print and > electronic... but when I don't *know* the pk number (because its automatically > assigned) it makes it tough to supply it as a foreign key for another insert > query into related tables. In sqlite, if a table contains a column of type INTEGER PRIMARY KEY, then that column becomes an alias for the ROWID (http://www.sqlite.org/autoinc.html). In python-sqlite, the rowid of the last insert operation can be queried using cursor.lastrowid. Therefore, you can query the lastrowid, right after the insert, to find the primary key of the value you had just inserted. So, in code: ... cur = conn.execute('INSERT ... ') pk = cur.lastrowid ... or even: ... pk = conn.execute('INSERT ... ').lastrowid ... Be careful that in multithreaded program, each thread should have their own cursors, or otherwise another thread could possibly do another insert before you can query the lastrowid. > Whats the 'right' way to do this sort of record insert or update query? Insert > into the main table first, then do a select query to find the last rowid and > store it in a python variable and then use that as a parameter for the rest of > the insert queries to related tables? Pull the value from the seq column of the > sqlite-sequence table for the table with the primary key, and use that (not sure > how robust that would be down the road, or how portable it would be if I later > moved to MySQL for the DB)? Or is this something an ORM like SQLalchemy would > smooth over for me? In part I'm (also) wondering if this may be an artificial > problem, as I'm trying to import data from a csv file i.e. one big table and > then break it up and insert it into multiple tables in the sqlite database... In general, despite the superficial similarities, most database engine wrappers have their own ways of doing stuffs. Generally, you need a full-blown ORM to smooth out the differences. From lie.1296 at gmail.com Sat Dec 24 08:47:25 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 24 Dec 2011 18:47:25 +1100 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF40171.9030508@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> Message-ID: On 12/23/2011 03:20 PM, Wayne Watson wrote: > Hi, I found it, but not in a place I would expect. It's under my > username, Wayne. It is a folder and has three files: > breakpoints.lst > recent-files.lst > ZZrecent-files.lst > > The last one has the odd ZZ, but is empty. breakpoints.lst is empty too. > That certainly is curious, have you tried renaming ZZrecent-files.lst to recent-file.lst? From memilanuk at gmail.com Sat Dec 24 15:57:56 2011 From: memilanuk at gmail.com (Monte Milanuk) Date: Sat, 24 Dec 2011 14:57:56 +0000 (UTC) Subject: [Tutor] insert queries into related tables referencing foreign keys using python References: Message-ID: Lie Ryan gmail.com> writes: > In python-sqlite, the rowid of the > last insert operation can be queried using cursor.lastrowid. Therefore, > you can query the lastrowid, right after the insert, to find the primary > key of the value you had just inserted. So, in code: > > ... > cur = conn.execute('INSERT ... ') > pk = cur.lastrowid > ... > > or even: > > ... > pk = conn.execute('INSERT ... ').lastrowid > ... > > Be careful that in multithreaded program, each thread should have their > own cursors, or otherwise another thread could possibly do another > insert before you can query the lastrowid. > okay, this touches on something that had been worrying me a bit... whether another insert could hit before I queried for the lastrowid, regardless of how I did it. So you're saying that as long as I have the one cursor open, the lastrowid it gets will be the lastrowid from its operations, regardless of other commits or transactions that may have happened in the meantime? > > In general, despite the superficial similarities, most database engine > wrappers have their own ways of doing stuffs. Generally, you need a > full-blown ORM to smooth out the differences. > So... what would be considered a 'full-blown' ORM? SQLobject or SQLalchemy... or something else? Thanks, Monte From joel.goldstick at gmail.com Sat Dec 24 17:34:32 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 24 Dec 2011 11:34:32 -0500 Subject: [Tutor] insert queries into related tables referencing foreign keys using python In-Reply-To: References: Message-ID: On Sat, Dec 24, 2011 at 9:57 AM, Monte Milanuk wrote: > Lie Ryan gmail.com> writes: > >> In python-sqlite, the rowid of the >> last insert operation can be queried using cursor.lastrowid. Therefore, >> you can query the lastrowid, right after the insert, to find the primary >> key of the value you had just inserted. So, in code: >> >> ... >> cur = conn.execute('INSERT ... ') >> pk = cur.lastrowid >> ... >> >> or even: >> >> ... >> pk = conn.execute('INSERT ... ').lastrowid >> ... >> >> Be careful that in multithreaded program, each thread should have their >> own cursors, or otherwise another thread could possibly do another >> insert before you can query the lastrowid. >> > > okay, this touches on something that had been worrying me a bit... whether > another insert could hit before I queried for the lastrowid, regardless of how I > did it. ?So you're saying that as long as I have the one cursor open, the > lastrowid it gets will be the lastrowid from its operations, regardless of other > commits or transactions that may have happened in the meantime? > >> >> In general, despite the superficial similarities, most database engine >> wrappers have their own ways of doing stuffs. Generally, you need a >> full-blown ORM to smooth out the differences. >> > > So... what would be considered a 'full-blown' ORM? ?SQLobject or SQLalchemy... > or something else? > > Thanks, > > Monte > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Django has an ORM and it works with sqlite3, mysql and I think postgress Although Django is a full framework for writing web apps the various modules can be used together or separately. http://www.djangobook.com/en/2.0/chapter05/ talks about models and the ORM -- Joel Goldstick From sierra_mtnview at sbcglobal.net Sat Dec 24 18:27:18 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Dec 2011 09:27:18 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> Message-ID: <4EF60B76.4030604@sbcglobal.net> My guess is that some months ago I looked at .idlerc on another "mission" to figure what ails my python install, and just more or less backed up the recent-files.lst. However, the important point here is, I think, how to change the permissions for the .idlerc folder. They vary by how I might login. On 12/23/2011 11:47 PM, Lie Ryan wrote: > On 12/23/2011 03:20 PM, Wayne Watson wrote: >> Hi, I found it, but not in a place I would expect. It's under my >> username, Wayne. It is a folder and has three files: >> breakpoints.lst >> recent-files.lst >> ZZrecent-files.lst >> >> The last one has the odd ZZ, but is empty. breakpoints.lst is empty too. >> > > That certainly is curious, have you tried renaming ZZrecent-files.lst > to recent-file.lst? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Sat Dec 24 18:37:57 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Dec 2011 09:37:57 -0800 Subject: [Tutor] Which libraries for Python 2.5.2 Message-ID: <4EF60DF5.7070100@sbcglobal.net> I'm trying to restore Python 2.5.2 on an old PC for a particular application that uses it from 4-5 years ago. According to the latest manual on it, the following should be installed. python-2.5.2.msi PIL-1.1.6.win32-py2.5.exe numpy-1.1.0-win32-superpack-python2.5.exe matplotlib-0.98.1.win32-py2.5.exe When I install them, and try to run the app program, Sentinel.py, some part of matplotlib complains (error msgs) and the program quits. The program begins with: from Tkinter import * from numpy import * import Image import ImageChops import ImageTk import time import binascii import tkMessageBox import tkSimpleDialog from pylab import plot, xlabel, ylabel, title, show, xticks, bar I tried numpy-1.2.0 and matplotlib-0.98.3 and had the same difficulty. What are wiser choices? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Sat Dec 24 19:07:41 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Dec 2011 10:07:41 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF60B76.4030604@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> Message-ID: <4EF614ED.9040607@sbcglobal.net> Permissions as follows: SYSTEM: All. From Full control to write Account Unknown(S-1-5-21...): read, exec, list folder contents, Read Wayne: (normal use) All. From Full control to write Admin: All. From Full control to write WMPNetwork: Read -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From hugo.yoshi at gmail.com Sat Dec 24 19:49:10 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sat, 24 Dec 2011 19:49:10 +0100 Subject: [Tutor] Which libraries for Python 2.5.2 In-Reply-To: <4EF60DF5.7070100@sbcglobal.net> References: <4EF60DF5.7070100@sbcglobal.net> Message-ID: On Sat, Dec 24, 2011 at 6:37 PM, Wayne Watson wrote: > I'm trying to restore Python 2.5.2 on an old PC for a particular application > that uses it from 4-5 years ago. > According to the latest manual on it, the following should be installed. > > python-2.5.2.msi > PIL-1.1.6.win32-py2.5.exe > numpy-1.1.0-win32-superpack-python2.5.exe > matplotlib-0.98.1.win32-py2.5.exe > > When I install them, and try to run the app program, Sentinel.py, some part > of matplotlib complains (error msgs) and the program quits. > If we are to give any kind of useful advice at all, we're going to need to see those error messages. > The program begins with: > from Tkinter import * > from numpy import * > import Image > import ImageChops > import ImageTk > import time > import binascii > import tkMessageBox > import tkSimpleDialog > from pylab import plot, xlabel, ylabel, title, show, xticks, bar > > I tried numpy-1.2.0 and matplotlib-0.98.3 and had the same difficulty. What > are wiser choices? > This question is based on the assumption that version mismatch is the cause of your problems. Even though that might be correct, it is not an assumption you can safely make. In general, when asking questions here (and anywhere really, imho) you should try to provide as much factual information and as little conjecture as you can. Hugo From sierra_mtnview at sbcglobal.net Sat Dec 24 19:58:24 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Dec 2011 10:58:24 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF614ED.9040607@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> <4EF614ED.9040607@sbcglobal.net> Message-ID: <4EF620D0.4020008@sbcglobal.net> Yikes. I gave the permissions for .idlerc above. The problem is with recent-files.py. IOError: [Errno 13] Permission denied: 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' These are for it. Same as before except for Account Unknown, which had "list folder contents". Permissions as follows: SYSTEM: All. From Full control to write Account Unknown(S-1-5-21...): read&exec, Read Wayne: (normal use) All. From Full control to write Admin: All. From Full control to write WMPNetwork: Read -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From alan.gauld at btinternet.com Sat Dec 24 20:24:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Dec 2011 19:24:54 +0000 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF620D0.4020008@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> <4EF614ED.9040607@sbcglobal.net> <4EF620D0.4020008@sbcglobal.net> Message-ID: On 24/12/11 18:58, Wayne Watson wrote: > Yikes. I gave the permissions for .idlerc above. The problem is with > recent-files.py. > > IOError: [Errno 13] Permission denied: > 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' > Can you open it in Notepad from the same command prompt? ie. is it just idle that can't open it, or is it any program? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lie.1296 at gmail.com Sun Dec 25 05:08:08 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 25 Dec 2011 15:08:08 +1100 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> <4EF614ED.9040607@sbcglobal.net> <4EF620D0.4020008@sbcglobal.net> Message-ID: On 12/25/2011 06:24 AM, Alan Gauld wrote: > On 24/12/11 18:58, Wayne Watson wrote: >> Yikes. I gave the permissions for .idlerc above. The problem is with >> recent-files.py. >> >> IOError: [Errno 13] Permission denied: >> 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' >> > > Can you open it in Notepad from the same command prompt? > ie. is it just idle that can't open it, or is it any program? also, try deleting the whole folder (or just in case, move the folder somewhere else), IDLE should create a new folder and config files, hopefully with the correct permission. From daedae11 at 126.com Sun Dec 25 06:02:30 2011 From: daedae11 at 126.com (daedae11) Date: Sun, 25 Dec 2011 13:02:30 +0800 Subject: [Tutor] question about the build-in function reversed in Python2.5 Message-ID: <201112251302304454227@126.com> The build-in function reversed() in Python2.5 returns a iterator. But I don't know how to use the iterator. Please give me a simple example about how to use bulid-in function reversed() to reverse a list. Thank you in advance. daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sun Dec 25 08:13:39 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 25 Dec 2011 18:13:39 +1100 Subject: [Tutor] insert queries into related tables referencing foreign keys using python In-Reply-To: References: Message-ID: On 12/25/2011 01:57 AM, Monte Milanuk wrote: > Lie Ryan gmail.com> writes: >> >> Be careful that in multithreaded program, each thread should have their >> own cursors, or otherwise another thread could possibly do another >> insert before you can query the lastrowid. >> > > okay, this touches on something that had been worrying me a bit... whether > another insert could hit before I queried for the lastrowid, regardless of how I > did it. So you're saying that as long as I have the one cursor open, the > lastrowid it gets will be the lastrowid from its operations, regardless of other > commits or transactions that may have happened in the meantime? Querying .lastrowid is pretty much safe as long as you don't use a single cursor from multiple threads. The .lastrowid attribute belongs to a cursor, so write operations from one cursor would not affect the .lastrowid of other cursors. However, note that multiple cursors created from a single connection will be able to see each other's changes immediately (as opposed to when commited). This might or might not always be desirable. In sqlite, it is more common to create one **connection** for each thread. Creating one connection for each thread prevents concurrency problems since each thread will not see uncommitted data from another thread. However, the recommended scenario is to avoid multithreading at all. sqlite developers have a strong opinion against multithreading (http://www.sqlite.org/faq.html#q6), even though they claimed that sqlite is the *embedded* SQL engine with the most concurrency (and it does very well in multithreaded scenarios). It is common pattern in sqlite-backed applications to have a single thread doing all the writes. >> In general, despite the superficial similarities, most database engine >> wrappers have their own ways of doing stuffs. Generally, you need a >> full-blown ORM to smooth out the differences. >> > > So... what would be considered a 'full-blown' ORM? SQLobject or SQLalchemy... > or something else? Most database engine thin-wrappers conforms to the Python Database API Specification (PEP249), including sqlite3; despite that these wrappers all conforms to a common API, you still need to be familiar with each database engine to do a lot of common stuffs and -- except on trivial cases -- code written for one PEP249-conforming database engine generally cannot be ported to another PEP249-conforming database engine without modification. Almost all ORM that supports multiple DB engine backends should be able to abstract the differences. From bgailer at gmail.com Sun Dec 25 08:43:56 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 25 Dec 2011 02:43:56 -0500 Subject: [Tutor] question about the build-in function reversed in Python2.5 In-Reply-To: <201112251302304454227@126.com> References: <201112251302304454227@126.com> Message-ID: <4EF6D43C.8020903@gmail.com> On 12/25/2011 12:02 AM, daedae11 wrote: > The build-in function reversed() in Python2.5 returns a iterator. But > I don't know how to use the iterator. > Please give me a simple example about how to use bulid-in function > reversed() to reverse a list. > >>> [x for x in reversed([1,2,3])] [3, 2, 1] >>> list(reversed([1,2,3])) [3, 2, 1] From the docs (it's all here though takes a bit of digging): iterator An object representing a stream of data. Repeated calls to the iterator's next() method return successive items in the stream. When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to its next() method just raise StopIteration again. Iterators are required to have an __iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list ) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container. More information can be found in /Iterator Types/ . iterable A container object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list , str , and tuple ) and some non-sequence types like dict and file and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip() , map() , ...). When an iterable object is passed as an argument to the built-in function iter() , it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also /iterator/ <#term-iterator>, /sequence/ <#term-sequence>, and /generator/ <#term-generator>. 7.3. The for <#for> statement The for <#for> statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object: *for_stmt* ::= "for"target_list "in"expression_list ":"suite <#grammar-token-suite> ["else" ":"suite <#grammar-token-suite>] The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. When the items are exhausted (which is immediately when the sequence is empty), the suite in the else <#else> clause, if present, is executed, and the loop terminates. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From daedae11 at 126.com Sun Dec 25 11:18:50 2011 From: daedae11 at 126.com (daedae11) Date: Sun, 25 Dec 2011 18:18:50 +0800 Subject: [Tutor] An unknown error in my program Message-ID: <2011122518185032016218@126.com> The following program has an error : new += lists[int(j)]+"-"; UnboundLocalError: local variable 'new' referenced before assignment But when I put the sentence " new = '' " in the main() function, the program run normally. Please tell me why? Isn't variable new in the following program is a global variable? the program is: lists = ['zero','one','two','three','four','five','six','seven','eight','nine']; new = ""; def main(): while True: try: iput = int(raw_input('Please input a int(0~1000): ')) if not 0<=iput<=1000: continue except: continue break iput = str(iput) for j in iput: new += lists[int(j)]+"-"; print new[0:-1]; if __name__ == "__main__": main(); daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Dec 25 11:46:23 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 25 Dec 2011 05:46:23 -0500 Subject: [Tutor] An unknown error in my program In-Reply-To: <2011122518185032016218@126.com> References: <2011122518185032016218@126.com> Message-ID: On Sun, Dec 25, 2011 at 5:18 AM, daedae11 wrote: > The following program has an error : > ????????????????????????????????????????? new?+=?lists[int(j)]+"-"; > UnboundLocalError:?local?variable?'new'?referenced?before?assignment > > But when I put the sentence? " new = '' " in the main() function, the > program run normally. > > Please tell me why?? Isn't variable new in the following program is a global > variable? > > the program is: > lists?=?['zero','one','two','three','four','five','six','seven','eight','nine']; > new?=?""; This new is global to your file. Within your main() function you can read the value of new. But inside main() you are creating another variable also called new when you do this: new += ..... Your code is trying to add something to a variable that doesn't yet have a value. 'new' is a name that is not bound to any value. You can either move the stuff at the top of your program into main, or you could pass the outer new into main as a parameter: main(new): > > > def?main(): > > ????while?True: > ????????try: > ????????????iput?=?int(raw_input('Please?input?a?int(0~1000):?')) > ????????????if?not?0<=iput<=1000: > ????????????????continue > ????????except: > ????????????continue > ????????break > > ????iput?=?str(iput) > ????for?j?in?iput: > ????????new?+=?lists[int(j)]+"-"; > ????print?new[0:-1]; > > if?__name__?==?"__main__": > ????main(); > > ________________________________ > daedae11 > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick From lie.1296 at gmail.com Sun Dec 25 12:00:53 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 25 Dec 2011 22:00:53 +1100 Subject: [Tutor] An unknown error in my program In-Reply-To: References: <2011122518185032016218@126.com> Message-ID: On 12/25/2011 09:46 PM, Joel Goldstick wrote: > > You can either move the stuff at the top of your program into main, or > you could pass the outer new > into main as a parameter: main(new): the third alternative is to use the global keyword, e.g. # declare a global named 'new' new = 0 def increment_new(): # tell python to use the global 'new' instead of # creating a local 'new' global new new += 1 print new increment_new() print new From joel.goldstick at gmail.com Sun Dec 25 12:26:15 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 25 Dec 2011 06:26:15 -0500 Subject: [Tutor] An unknown error in my program In-Reply-To: References: <2011122518185032016218@126.com> Message-ID: On Sun, Dec 25, 2011 at 6:00 AM, Lie Ryan wrote: > On 12/25/2011 09:46 PM, Joel Goldstick wrote: >> >> >> You can either move the stuff at the top of your program into main, or >> you could pass the outer new >> into main as a parameter: ? ?main(new): > > > the third alternative is to use the global keyword, e.g. > > # declare a global named 'new' > new = 0 > > def increment_new(): > ? ?# tell python to use the global 'new' instead of > ? ?# creating a local 'new' > ? ?global new > > ? ?new += 1 > > print new > increment_new() > print new > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Since this is a tutor mailing list, many questions come from people learning not only python, but programming in general. Lie is right in showing that you can let your function know that you want it to know about the global called new. But I think this is generally not a good approach. To get good at python you need to understand scope and namespaces. The value of using functions is that they let you write small self contained code that accomplishes some purpose. The purpose should be clear from the name of the function. Once your function works as you like it, you don't need to worry about how it works. You can just call it from somewhere else in your program, knowing that it will do what it does. Using a global messes this up. Now, when you call your function it will fail unless there is some variable named 'new' in some outer namespace. Your function is no longer self contained. Since the OPs code is so small, there may not be a need to use a function at all, but since he chose to go that route, the data that the function needs should be declared within the function. If that data is created elsewhere it should be passed to the function via parameters. If the function creates a result that will be needed later, it should be returned by the function. So, my point is that learning about the value of and aspects of writing good functions is more instructive than going with the global declaration. -- Joel Goldstick From steve at pearwood.info Sun Dec 25 14:40:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 26 Dec 2011 00:40:11 +1100 Subject: [Tutor] question about the build-in function reversed in Python2.5 In-Reply-To: <201112251302304454227@126.com> References: <201112251302304454227@126.com> Message-ID: <4EF727BB.4030101@pearwood.info> daedae11 wrote: > The build-in function reversed() in Python2.5 returns a iterator. But I don't know how to use the iterator. > Please give me a simple example about how to use bulid-in function reversed() to reverse a list. You use the iterator the same way you would any other iterator: * in for loops: for obj in reversed(my_list): print(obj) * pass it to functions which expect an iterator: a = reduce(function, reversed(my_list)) b = map(func, reversed(my_string)) * create a new sequence: my_list = list(reversed(my_list)) Note that the advantage of reversed is that it is lazy (it returns an iterator). If you just want a copy of a list in reverse order, you can use slicing: my_list[::-1] (also works on strings and tuples). If you want to reverse the list in place, instead of making a copy: my_list.reverse() # must be a list, not strings or tuples reversed() is more general: it can work on any finite iterable object, not just lists. -- Steven From alan.gauld at btinternet.com Sun Dec 25 15:49:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 Dec 2011 14:49:08 +0000 Subject: [Tutor] An unknown error in my program In-Reply-To: <2011122518185032016218@126.com> References: <2011122518185032016218@126.com> Message-ID: On 25/12/11 10:18, daedae11 wrote: > The following program has an error : > new += lists[int(j)]+"-"; > UnboundLocalError: local variable 'new' referenced before assignment Others have answered the question for you however there are two additional points to make: 1) Always send the complete erroir message not just the last line. 2) You do not need semi-colons at the end of lines in Python. > lists = > ['zero','one','two','three','four','five','six','seven','eight','nine']; > new = ""; No need for them here > for j in iput: > new += lists[int(j)]+"-"; > print new[0:-1]; > if __name__ == "__main__": > main(); Nor here. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From memilanuk at gmail.com Sun Dec 25 18:47:16 2011 From: memilanuk at gmail.com (Monte Milanuk) Date: Sun, 25 Dec 2011 09:47:16 -0800 Subject: [Tutor] insert queries into related tables referencing foreign keys using python In-Reply-To: References: Message-ID: On 12/24/2011 11:13 PM, Lie Ryan wrote: > Querying .lastrowid is pretty much safe as long as you don't use a > single cursor from multiple threads. The .lastrowid attribute belongs to > a cursor, so write operations from one cursor would not affect the > .lastrowid of other cursors. > > However, note that multiple cursors created from a single connection > will be able to see each other's changes immediately (as opposed to when > commited). This might or might not always be desirable. > > In sqlite, it is more common to create one **connection** for each > thread. Creating one connection for each thread prevents concurrency > problems since each thread will not see uncommitted data from another > thread. > > However, the recommended scenario is to avoid multithreading at all. > sqlite developers have a strong opinion against multithreading > (http://www.sqlite.org/faq.html#q6), even though they claimed that > sqlite is the *embedded* SQL engine with the most concurrency (and it > does very well in multithreaded scenarios). It is common pattern in > sqlite-backed applications to have a single thread doing all the writes. > Okay... sounds like I should be safe for the most part. Down the road (waaaaay down the road) I had some thoughts of working on an application that would in certain situations have multiple users (1-10) and had hoped that as long as I kept the sqlite insert/update activity wrapped in transactions there wouldn't be much problem with table locks, etc. and in this case, confusing lastrowid from one transaction with that from another. By the time I get to where I'm ready/willing/able to write that particular app, I might have moved on to an ORM, though. Thanks, Monte From stayvoid at gmail.com Sun Dec 25 23:55:06 2011 From: stayvoid at gmail.com (Stayvoid) Date: Mon, 26 Dec 2011 01:55:06 +0300 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: Hey there! I'm reading Lutz's Learning Python. Here is some code from the book. There is a module called lcclient_lutz.py: from lengthcounter_lutz import countLines, countChars print countLines('lengthcounter_lutz.py'), countChars('lengthcounter_lutz.py') And there is another one called lengthcounter_lutz.py: def countLines(name): file = open(name) return len(file.readlines()) def countChars(name): return len(open(name).read()) def test(name): return "Lines:", countLines(name), "Chars:", countChars(name) if __name__ == '__main__': print test('lengthcounter_lutz.py') I've got an error while trying to load lcclient_lutz module: python /Users/Username/Python_modules/lcclient_lutz.py Traceback (most recent call last): File "/Users/Username/Python_modules/lcclient_lutz.py", line 2, in print countLines('lengthcounter_lutz.py'), countChars('lengthcounter_lutz.py') File "/Users/Username/Python_modules/lengthcounter_lutz.py", line 2, in countLines file = open(name) IOError: [Errno 2] No such file or directory: 'lengthcounter_lutz.py' How to fix it? Is it connected with the PYTHONPATH variable? P.S. There might be an error in the lengthcounter_lutz module, because it makes mistakes while counting. Kind regards. From alan.gauld at btinternet.com Mon Dec 26 00:14:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 Dec 2011 23:14:29 +0000 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: On 25/12/11 22:55, Stayvoid wrote: > There is a module called lcclient_lutz.py: > > from lengthcounter_lutz import countLines, countChars > print countLines('lengthcounter_lutz.py'), countChars('lengthcounter_lutz.py') > > countChars('lengthcounter_lutz.py') > File "/Users/Username/Python_modules/lengthcounter_lutz.py", line 2, > in countLines > file = open(name) > IOError: [Errno 2] No such file or directory: 'lengthcounter_lutz.py' > How to fix it? Is it connected with the PYTHONPATH variable? PYTHONPATH only helps Python find the files to import. Since the error message is pointing at code insiude the imported functions then clearly PYTHONPATH is working just fine. So what is the error? Simply that python is saying it cannot find the file. So it is probably in a different folder to the one in which the program is running. You need to provide a valid path to the file, > P.S. There might be an error in the lengthcounter_lutz module, because > it makes mistakes while counting. Thats possible. Or it may e worlking to a different definition of success to the one you expect! Counting words and letters is quite a subjective past-time. So what is it doing exactly that seems wrong? What input? What output? What did you expect? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From paradox at pobox.com Mon Dec 26 12:42:34 2011 From: paradox at pobox.com (Thomas C. Hicks) Date: Mon, 26 Dec 2011 19:42:34 +0800 Subject: [Tutor] Wading through traceback output Message-ID: <20111226194234.5768f231@midgel> I have a script that I used to be quite proud of, up until today it was working great. Basically it reads in a directory tree of spreadsheets, extracts info from them then makes a new spreadsheet to output the info to. The spreadsheets are xls files so it uses xlrd and xlwt to manage the data extraction and spreadsheet creation. Today when I ran it (after a hiatus of about 3 months) I got this output: Traceback (most recent call last): File "./cttOverviewMain.0.03.2011.py", line 294, in monthData(searchList) File "./cttOverviewMain.0.03.2011.py", line 261, in monthData writeMonthlyHeader(writeSheet) File "./cttOverviewMain.0.03.2011.py", line 183, in writeMonthlyHeader sh.write(7,10,"# Locations",xlwt.easyxf('font: bold True')) File "/usr/local/lib/python2.6/dist-packages/xlwt/Worksheet.py", line 1003, in write self.row(r).write(c, label, style) File "/usr/local/lib/python2.6/dist-packages/xlwt/Row.py", line 227, in write style_index = self.__parent_wb.add_style(style) File "/usr/local/lib/python2.6/dist-packages/xlwt/Workbook.py", line 303, in add_style return self.__styles.add(style) File "/usr/local/lib/python2.6/dist-packages/xlwt/Style.py", line 90, in add return self._add_style(style)[1] File "/usr/local/lib/python2.6/dist-packages/xlwt/Style.py", line 149, in _add_style raise ValueError("More than 4094 XFs (styles)") ValueError: More than 4094 XFs (styles) I don't understand this very well at all - any pointers are appreciated. I think what it is saying is that there is a problem with my Python libraries but this is not a problem I have ever seen before. Is it possible the 2.6 libraries were updated in the hiatus time causing this problem? If so any ideas on how I can investigate fixing this are appreciated. thomas From alan.gauld at btinternet.com Mon Dec 26 13:10:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Dec 2011 12:10:45 +0000 Subject: [Tutor] Wading through traceback output In-Reply-To: <20111226194234.5768f231@midgel> References: <20111226194234.5768f231@midgel> Message-ID: On 26/12/11 11:42, Thomas C. Hicks wrote: Given it was working before and not now the obvious question is what has changed? It looks like you are on a Linux box so do you have automatic updates switched on? Or do you always just accept the recommendation to update? In which case try looking at the modification dates of the library files.... Also has the verion of Excel used to create the files changed? It looks like the point that the program leaves your code is here: > File "./cttOverviewMain.0.03.2011.py", line 183, in writeMonthlyHeader > sh.write(7,10,"# Locations",xlwt.easyxf('font: bold True')) So that points the finger at the xlwt module. If it has been updated has the format of that call changed - to a dictionary/tuple of values for example? These are all guesses but might give you a starting point. Incidentally cttOverviewMain.0.03.2011.py seems like a bizarre name for a file? I assume that's the date or somesuch? What is the thinking behind that? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From stayvoid at gmail.com Mon Dec 26 13:23:26 2011 From: stayvoid at gmail.com (Stayvoid) Date: Mon, 26 Dec 2011 15:23:26 +0300 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: >Simply that python is saying it cannot find the file. >So it is probably in a different folder to the one in which the program is running. You need to provide a valid path to the file, Those files are in the same folder: /Users/Username/Python_modules/ I don't want to write a full path here: if __name__ == '__main__': print test('lengthcounter_lutz.py') How to add this directory to the search path? >So what is it doing exactly that seems wrong? >What input? What output? What did you expect? I have a slightly different copy of this file: def countLines(name): file = open(name.__file__) return len(file.readlines()) def countChars(name): return len(open(name.__file__).read()) def test(name): return "Lines:", countLines(name), "Chars:", countChars(name) if __name__ == '__main__': import lengthcounter print test(lengthcounter) I've tried to run it in the interactive shell: import lengthcounter as lc lc.test(lengthcounter) And here is the output: ('Lines:', 5, 'Chars:', 885) But that code has 13 lines and 317 characters according to the Emacs' counter. Where is an error? Cheers. From d at davea.name Mon Dec 26 13:51:49 2011 From: d at davea.name (Dave Angel) Date: Mon, 26 Dec 2011 07:51:49 -0500 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: <4EF86DE5.8070200@davea.name> On 12/26/2011 07:23 AM, Stayvoid wrote: >> Simply that python is saying it cannot find the file. >> So it is probably in a different folder to the one in which the program is running. You need to provide a valid path to the file, > Those files are in the same folder: > /Users/Username/Python_modules/ > > I don't want to write a full path here: > if __name__ == '__main__': > print test('lengthcounter_lutz.py') > > How to add this directory to the search path? Once again, there is no search path for the open() function. You can either supply an absolute name (eg. starting with leading slash), or you can supply a path relative to the current directory. If you're not sure what the current directory is, you can fetch it with something like: import os print os.path.abspath(os.curdir) But if you're running the script from the terminal window, it should simply be the current directory for that window. If you're running it from some other shell, you'd have to consult that shell's docs. -- DaveA From paradox at pobox.com Mon Dec 26 13:52:39 2011 From: paradox at pobox.com (Thomas C. Hicks) Date: Mon, 26 Dec 2011 20:52:39 +0800 Subject: [Tutor] Wading through traceback output :p: In-Reply-To: References: <20111226194234.5768f231@midgel> Message-ID: <20111226205239.5f3f8e23@midgel> On Mon, 26 Dec 2011 07:10:45 -0500 Alan Gauld wrote: > On 26/12/11 11:42, Thomas C. Hicks wrote: > > Given it was working before and not now the obvious question is what > has changed? It looks like you are on a Linux box so do you have > automatic updates switched on? Or do you always just accept the > recommendation to update? > > In which case try looking at the modification dates of the > library files.... > > Also has the verion of Excel used to create the files changed? > > It looks like the point that the program leaves your code is here: > > > File "./cttOverviewMain.0.03.2011.py", line 183, in > > writeMonthlyHeader sh.write(7,10,"# Locations",xlwt.easyxf('font: > > bold True')) > > So that points the finger at the xlwt module. If it has been updated > has the format of that call changed - to a dictionary/tuple of values > for example? > > These are all guesses but might give you a starting point. > > > Incidentally cttOverviewMain.0.03.2011.py seems like a bizarre > name for a file? I assume that's the date or somesuch? What is the > thinking behind that? > Thanks so much for the input Alan, guesses on your part are far better than the ignorance on my part. I do get automatic updates (though xlwt is not part of that, OpenOffice and its xls writing is), will have to look at that. Also appreciate the thoughts about the file name. This is my first big project and I still have much to learn. If you can point me to a discussion of file naming when there are multiple files involved in a project I am game to do some reading! thomas From lie.1296 at gmail.com Mon Dec 26 14:15:51 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 27 Dec 2011 00:15:51 +1100 Subject: [Tutor] Wading through traceback output :p: In-Reply-To: <20111226205239.5f3f8e23@midgel> References: <20111226194234.5768f231@midgel> <20111226205239.5f3f8e23@midgel> Message-ID: On 12/26/2011 11:52 PM, Thomas C. Hicks wrote: > On Mon, 26 Dec 2011 07:10:45 -0500 > Alan Gauld wrote: > >> On 26/12/11 11:42, Thomas C. Hicks wrote: >> >> Given it was working before and not now the obvious question is what >> has changed? It looks like you are on a Linux box so do you have >> automatic updates switched on? Or do you always just accept the >> recommendation to update? >> >> In which case try looking at the modification dates of the >> library files.... >> >> Also has the verion of Excel used to create the files changed? >> >> It looks like the point that the program leaves your code is here: >> >>> File "./cttOverviewMain.0.03.2011.py", line 183, in >>> writeMonthlyHeader sh.write(7,10,"# Locations",xlwt.easyxf('font: >>> bold True')) >> >> So that points the finger at the xlwt module. If it has been updated >> has the format of that call changed - to a dictionary/tuple of values >> for example? >> >> These are all guesses but might give you a starting point. >> >> >> Incidentally cttOverviewMain.0.03.2011.py seems like a bizarre >> name for a file? I assume that's the date or somesuch? What is the >> thinking behind that? >> > > Thanks so much for the input Alan, guesses on your part are far better > than the ignorance on my part. I do get automatic updates (though > xlwt is not part of that, OpenOffice and its xls writing is), will have > to look at that. Many package managers keeps a history of what packages are installed/updated/removed. You might want to use those to find if OpenOffice or some other libraries had been updated since the last time the script worked. > Also appreciate the thoughts about the file name. This is my first big > project and I still have much to learn. If you can point me to a > discussion of file naming when there are multiple files involved in a > project I am game to do some reading! Use version control, it will relieve you of versioning headache. Nowadays it's pretty easy to setup a DVCS like mercurial or git even for small projects. From joel.goldstick at gmail.com Mon Dec 26 14:18:18 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 26 Dec 2011 08:18:18 -0500 Subject: [Tutor] Wading through traceback output In-Reply-To: References: <20111226194234.5768f231@midgel> Message-ID: On Mon, Dec 26, 2011 at 7:10 AM, Alan Gauld wrote: > On 26/12/11 11:42, Thomas C. Hicks wrote: > > Given it was working before and not now the obvious question is what has > changed? It looks like you are on a Linux box so do you have automatic > updates switched on? Or do you always just accept the recommendation to > update? > > In which case try looking at the modification dates of the > library files.... > > Also has the verion of Excel used to create the files changed? > > It looks like the point that the program leaves your code is here: > > >> ? File "./cttOverviewMain.0.03.2011.py", line 183, in writeMonthlyHeader >> ? ? sh.write(7,10,"# Locations",xlwt.easyxf('font: bold True')) > > > So that points the finger at the xlwt module. If it has been updated has the > format of that call changed - to a dictionary/tuple of values for example? > > These are all guesses but might give you a starting point. > > > Incidentally cttOverviewMain.0.03.2011.py seems like a bizarre > name for a file? I assume that's the date or somesuch? What is the thinking > behind that? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor It may be that there is something different about your data with this recent run. I googled your error message and came up with this link: http://groups.google.com/group/python-excel/browse_thread/thread/c717ad00c7acc848 I'm not familiar with the package, but ValueError: More than 4094 XFs (styles) has lots of links on google. To test my guess, would it be possible for you to set up your application to run it on files that it successfully worked on before? If it won't work on them, then I'd guess that a module may have updated. But if it does work, then you may have some condition in your new data that exercises your program in a way it hasn't be exercised before that raises the exception. The link I showed contains this little snippet: ------------------------- On 27/09/2010 00:46, Keyton Weissinger wrote: > if current_value_is_date: > s = XFStyle() > s.num_format_str = 'M/D/YY' > export_sheet.write(row_idx, col_idx, > current_value, s) ...and we have a winner. Create the style *once* in your outermost part of the function and re-used it, rather than creating a new style each and every time you write a date cell... ------------------------- I don't know if this situation applies to you, but maybe it will give you a clue -- Joel Goldstick From daedae11 at 126.com Mon Dec 26 14:18:20 2011 From: daedae11 at 126.com (daedae11) Date: Mon, 26 Dec 2011 21:18:20 +0800 Subject: [Tutor] question about pywin32 Message-ID: <2011122621182018488413@126.com> Does pywin32 provide a module for AES encryption algorithm ? The description of some module in pywin32 document is so simple that there is not introduction about the function of the function. For example, "CryptProtectData" function in module win32crypt. daedae11 -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Mon Dec 26 16:58:10 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 27 Dec 2011 02:58:10 +1100 Subject: [Tutor] question about pywin32 In-Reply-To: <2011122621182018488413@126.com> References: <2011122621182018488413@126.com> Message-ID: On 12/27/2011 12:18 AM, daedae11 wrote: > Does pywin32 provide a module for AES encryption algorithm ? > The description of some module in pywin32 document is so simple that > there is not introduction about the function of the function. > For example, "CryptProtectData" function in module win32crypt. > ------------------------------------------------------------------------ It is not the intent of pywin32 to document win32 functions. For each of pywin32 function, there is a corresponding C function with the same name in MSDN, for example, for CryptProtectData: http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx From lie.1296 at gmail.com Mon Dec 26 17:21:50 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 27 Dec 2011 03:21:50 +1100 Subject: [Tutor] question about pywin32 In-Reply-To: References: <2011122621182018488413@126.com> Message-ID: On 12/27/2011 02:58 AM, Lie Ryan wrote: > On 12/27/2011 12:18 AM, daedae11 wrote: >> Does pywin32 provide a module for AES encryption algorithm ? >> The description of some module in pywin32 document is so simple that >> there is not introduction about the function of the function. >> For example, "CryptProtectData" function in module win32crypt. >> ------------------------------------------------------------------------ > > It is not the intent of pywin32 to document win32 functions. For each of > pywin32 function, there is a corresponding C function with the same name > in MSDN, for example, for CryptProtectData: > http://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx a small correction: "...there is a corresponding C function with the same name in win32 library, which is documented in MSDN..." From alan.gauld at btinternet.com Mon Dec 26 18:04:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Dec 2011 17:04:15 +0000 Subject: [Tutor] Wading through traceback output :p: In-Reply-To: <20111226205239.5f3f8e23@midgel> References: <20111226194234.5768f231@midgel> <20111226205239.5f3f8e23@midgel> Message-ID: On 26/12/11 12:52, Thomas C. Hicks wrote: > Also appreciate the thoughts about the file name. This is my first big > project and I still have much to learn. If you can point me to a > discussion of file naming when there are multiple files involved in a > project I am game to do some reading! When dealing with multiple files the only p[roblem tends to e if you have duplicate names. In that case create separate folders (packages in Python) and use namespaces to kep them separate. If you have multiple versions of the same file it's probably better to keep separate folders for each project version. But better still is to use a version control tool (which does the same thing virtually with a friendly UI/CLI and copes with multiple versions etc). These can range from simple file based RCS to full project based control. Most folks these days tenmd to go with project based control. CVS, SVN. GIT, Mercurial are the big names for freeware. [MS SourceSafe, IBM ClearCase and AidedeCamp are the big commercial players - but they cost big bucks(apart from SourceSafe)] SVN and Mercurial would be my suggestion, GUI front ends exist for both and both have packages for most Linux distros. They both have web sites with tutorials, but whiole there are oodles of options etc there are only a few commands you need for normal use, especially for a single user: create, check out, check in, fork, diff, merge should cover it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Dec 26 18:12:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Dec 2011 17:12:17 +0000 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: On 26/12/11 12:23, Stayvoid wrote: >> Simply that python is saying it cannot find the file. >> So it is probably in a different folder ... > Those files are in the same folder: > /Users/Username/Python_modules/ And is that where you are running the code from? That is the critical factor. By just providing the filename Python assumes its in the same folder that you ran the program from. If you run it from somewhere else you *must* provide the full (or relative() path to the file. There is no option for Python to search for it. > I don't want to write a full path here: > if __name__ == '__main__': > print test('lengthcounter_lutz.py') You don't have any option. You either type in the full path or you get the user to tell you in some way - either with a prompt or via an input argument. > I have a slightly different copy of this file: > > def countLines(name): > file = open(name.__file__) > return len(file.readlines()) > > def countChars(name): > return len(open(name.__file__).read()) > > def test(name): > return "Lines:", countLines(name), "Chars:", countChars(name) > > if __name__ == '__main__': > import lengthcounter > print test(lengthcounter) > > I've tried to run it in the interactive shell: > > import lengthcounter as lc > lc.test(lengthcounter) Are you sure it is your version that's being picked up? Try renaming it to something guaranteed to be unique. See if the results are the same. Also I would expect the prompt to complain because you are passing lengthcounter as a name to the test function, but you imported lengthcounter as lc, so python should not know about lengthcounter unless you had already imported it (or another file?) eg. >>> import random as r >>> random.__file__ Traceback (most recent call last): File "", line 1, in NameError: name 'random' is not defined >>> Try starting a fresh interpreter session and repeating the test. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Mon Dec 26 18:50:35 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 26 Dec 2011 09:50:35 -0800 Subject: [Tutor] question about pywin32 In-Reply-To: <2011122621182018488413@126.com> References: <2011122621182018488413@126.com> Message-ID: On Mon, Dec 26, 2011 at 5:18 AM, daedae11 wrote: > ** > Does pywin32 provide a module for AES encryption algorithm ? > > The description of some module in pywin32 document is so simple that there > is not introduction about the function of the function. > For example, "CryptProtectData" function in module win32crypt. > Lie Ryan has already covered this pretty well, but I thought I'd re-state for clarification: pywin32 itself does not provide modules for ANYTHING. pywin32 is just a convenience wrapper for functions that already exist in the win32 library; without pywin it's a horrible task to call win32 functions from Python. Since pywin doesn't provide the functions, it also doesn't provide documentation. For that, you go to the people who actually wrote the functions: Microsoft. In fact, it might make more sense to turn your search around: look at MSDN _first_ to see what functions are available, and then look at the pywin docs to see how to call them. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Dec 26 20:00:09 2011 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 26 Dec 2011 14:00:09 -0500 Subject: [Tutor] Wading through traceback output :p: In-Reply-To: References: <20111226194234.5768f231@midgel> <20111226205239.5f3f8e23@midgel> Message-ID: On Mon, Dec 26, 2011 at 12:04 PM, Alan Gauld wrote: > On 26/12/11 12:52, Thomas C. Hicks wrote: > >> Also appreciate the thoughts about the file name. ?This is my first big >> project and I still have much to learn. ?If you can point me to a >> discussion of file naming when there are multiple files involved in a >> project I am game to do some reading! > > > When dealing with multiple files the only p[roblem tends to e if you have > duplicate names. In that case create separate folders (packages in Python) > and use namespaces to kep them separate. > > If you have multiple versions of the same file it's probably better to keep > separate folders for each project version. But better still is to use a > version control tool (which does the same thing virtually with a friendly > UI/CLI and copes with multiple versions etc). > > These can range from simple file based RCS to full project based control. > Most folks these days tenmd to go with project based > control. CVS, SVN. GIT, Mercurial are the big names for freeware. > [MS SourceSafe, IBM ClearCase and AidedeCamp are the big commercial players > - but they cost big bucks(apart from SourceSafe)] > > SVN and Mercurial would be my suggestion, GUI front ends exist for both and > both have packages for most Linux distros. They both have web sites with > tutorials, but whiole there are oodles of options etc there are only a few > commands you need for normal use, especially for a single user: > > create, > check out, > check in, > fork, > diff, > merge > > should cover it. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I sent this earlier but it doesn't look like it went through: It may be that there is something different about your data with this recent run. I googled your error message and came up with this link: http://groups.google.com/group/python-excel/browse_thread/thread/c717ad00c7acc848 I'm not familiar with the package, but ValueError: More than 4094 XFs (styles) has lots of links on google. To test my guess, would it be possible for you to set up your application to run it on files that it successfully worked on before? If it won't work on them, then I'd guess that a module may have updated. But if it does work, then you may have some condition in your new data that exercises your program in a way it hasn't be exercised before that raises the exception. The link I showed contains this little snippet: ------------------------- On 27/09/2010 00:46, Keyton Weissinger wrote: > if current_value_is_date: > s = XFStyle() > s.num_format_str = 'M/D/YY' > export_sheet.write(row_idx, col_idx, > current_value, s) ...and we have a winner. Create the style *once* in your outermost part of the function and re-used it, rather than creating a new style each and every time you write a date cell... ------------------------- I don't know if this situation applies to you, but maybe it will give you a clue -- Joel Goldstick From sierra_mtnview at sbcglobal.net Mon Dec 26 19:57:12 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Dec 2011 10:57:12 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> <4EF614ED.9040607@sbcglobal.net> <4EF620D0.4020008@sbcglobal.net> Message-ID: <4EF8C388.3000707@sbcglobal.net> On 12/24/2011 11:24 AM, Alan Gauld wrote: > On 24/12/11 18:58, Wayne Watson wrote: >> Yikes. I gave the permissions for .idlerc above. The problem is with >> recent-files.py. >> >> IOError: [Errno 13] Permission denied: >> 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' >> > > Can you open it in Notepad from the same command prompt? > ie. is it just idle that can't open it, or is it any program? > Opens with Notepad and jEdit from the menu off a py file. I'm suspicious of the "Unknown Account(S-1-21-lots of digits)" seen in Properties' Security tab. It seems bizarre and has read and read&execute properties only. "Unknown User" exits for txt and jpg files, so it's not isolated to py. Perhaps there's an ownership problem; however, Owner (recent-files.lst) is: solarblast\Wayne. That's me. I'm looking at the General tab of .idlerc. Attributes Read-only check box is blue. If I click on it, it goes white. If I click again, it shows the check mark. Eventually, I get back to blue. I'm now looking at Properties-General for recent-files.lst, and Read -only check box is white. Presently, I do not know if this amounts to anything. I see recent-files.lst is openable with Word. I see mydir_math.py is opened with python.exe!!?? True of other py files. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Mon Dec 26 20:20:56 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Dec 2011 11:20:56 -0800 Subject: [Tutor] A few Python Mysteries [SOLVED] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> <4EF614ED.9040607@sbcglobal.net> <4EF620D0.4020008@sbcglobal.net> Message-ID: <4EF8C918.4020702@sbcglobal.net> Excellent strategy!! It worked. I just examined the properties for each .idlerc, and noticed that the troublesome one was created in Feb 4,2010. Probably with Python 2.5.2. I don't know why or necessarily whether new installs shouldn't have changed the folder or recreated it. Thanks to all who followed this long perplexing thread. On 12/24/2011 8:08 PM, Lie Ryan wrote: > On 12/25/2011 06:24 AM, Alan Gauld wrote: >> On 24/12/11 18:58, Wayne Watson wrote: >>> Yikes. I gave the permissions for .idlerc above. The problem is with >>> recent-files.py. >>> >>> IOError: [Errno 13] Permission denied: >>> 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' >>> >> >> Can you open it in Notepad from the same command prompt? >> ie. is it just idle that can't open it, or is it any program? > > also, try deleting the whole folder (or just in case, move the folder > somewhere else), IDLE should create a new folder and config files, > hopefully with the correct permission. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Mon Dec 26 20:44:57 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Dec 2011 11:44:57 -0800 Subject: [Tutor] Which libraries for Python 2.5.2 In-Reply-To: References: <4EF60DF5.7070100@sbcglobal.net> Message-ID: <4EF8CEB9.5090505@sbcglobal.net> Yes, that's a reasonable request, and I expected it, but hoped it might be apparent from what I revealed. Why? It's on another PC this happened, and getting the messages of it is not easily done, but today I have time, so soon I will post the details. On 12/24/2011 10:49 AM, Hugo Arts wrote: > On Sat, Dec 24, 2011 at 6:37 PM, Wayne Watson > wrote: >> I'm trying to restore Python 2.5.2 on an old PC for a particular application >> that uses it from 4-5 years ago. >> According to the latest manual on it, the following should be installed. >> >> python-2.5.2.msi >> PIL-1.1.6.win32-py2.5.exe >> numpy-1.1.0-win32-superpack-python2.5.exe >> matplotlib-0.98.1.win32-py2.5.exe >> >> When I install them, and try to run the app program, Sentinel.py, some part >> of matplotlib complains (error msgs) and the program quits. >> > If we are to give any kind of useful advice at all, we're going to > need to see those error messages. > >> The program begins with: >> from Tkinter import * >> from numpy import * >> import Image >> import ImageChops >> import ImageTk >> import time >> import binascii >> import tkMessageBox >> import tkSimpleDialog >> from pylab import plot, xlabel, ylabel, title, show, xticks, bar >> >> I tried numpy-1.2.0 and matplotlib-0.98.3 and had the same difficulty. What >> are wiser choices? >> > This question is based on the assumption that version mismatch is the > cause of your problems. Even though that might be correct, it is not > an assumption you can safely make. In general, when asking questions > here (and anywhere really, imho) you should try to provide as much > factual information and as little conjecture as you can. > > Hugo > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From sierra_mtnview at sbcglobal.net Mon Dec 26 20:56:19 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Dec 2011 11:56:19 -0800 Subject: [Tutor] Which libraries for Python 2.5.2 In-Reply-To: <4EF8CEB9.5090505@sbcglobal.net> References: <4EF60DF5.7070100@sbcglobal.net> <4EF8CEB9.5090505@sbcglobal.net> Message-ID: <4EF8D163.1020007@sbcglobal.net> Here's the traceback. Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.2 ==== No Subprocess ==== >>> Traceback (most recent call last): File "C:\Sentinel\Sent_user-20080716.py", line 16, in from pylab import plot, xlabel, ylabel, title, show, xticks, bar File "C:\Python25\lib\site-packages\pylab.py", line 1, in from matplotlib.pylab import * File "C:\Python25\lib\site-packages\matplotlib\pylab.py", line 206, in from matplotlib import mpl # pulls in most modules File "C:\Python25\lib\site-packages\matplotlib\mpl.py", line 1, in from matplotlib import artist File "C:\Python25\lib\site-packages\matplotlib\artist.py", line 4, in from transforms import Bbox, IdentityTransform, TransformedBbox, TransformedPath File "C:\Python25\lib\site-packages\matplotlib\transforms.py", line 34, in from matplotlib._path import affine_transform ImportError: DLL load failed: The specified module could not be found. >>> On 12/26/2011 11:44 AM, Wayne Watson wrote: > Yes, that's a reasonable request, and I expected it, but hoped it > might be apparent from what I revealed. Why? It's on another PC this > happened, and getting the messages of it is not easily done, but today > I have time, so soon I will post the details. > > On 12/24/2011 10:49 AM, Hugo Arts wrote: >> On Sat, Dec 24, 2011 at 6:37 PM, Wayne Watson >> wrote: >>> I'm trying to restore Python 2.5.2 on an old PC for a particular >>> application >>> that uses it from 4-5 years ago. >>> According to the latest manual on it, the following should be >>> installed. >>> >>> python-2.5.2.msi >>> PIL-1.1.6.win32-py2.5.exe >>> numpy-1.1.0-win32-superpack-python2.5.exe >>> matplotlib-0.98.1.win32-py2.5.exe >>> >>> When I install them, and try to run the app program, Sentinel.py, >>> some part >>> of matplotlib complains (error msgs) and the program quits. >>> >> If we are to give any kind of useful advice at all, we're going to >> need to see those error messages. >> >>> The program begins with: >>> from Tkinter import * >>> from numpy import * >>> import Image >>> import ImageChops >>> import ImageTk >>> import time >>> import binascii >>> import tkMessageBox >>> import tkSimpleDialog >>> from pylab import plot, xlabel, ylabel, title, show, xticks, bar >>> >>> I tried numpy-1.2.0 and matplotlib-0.98.3 and had the same >>> difficulty. What >>> are wiser choices? >>> >> This question is based on the assumption that version mismatch is the >> cause of your problems. Even though that might be correct, it is not >> an assumption you can safely make. In general, when asking questions >> here (and anywhere really, imho) you should try to provide as much >> factual information and as little conjecture as you can. >> >> Hugo >> > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From alan.gauld at btinternet.com Mon Dec 26 22:28:27 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Dec 2011 21:28:27 +0000 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: <4EF8C388.3000707@sbcglobal.net> References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> <4EF614ED.9040607@sbcglobal.net> <4EF620D0.4020008@sbcglobal.net> <4EF8C388.3000707@sbcglobal.net> Message-ID: On 26/12/11 18:57, Wayne Watson wrote: >>> IOError: [Errno 13] Permission denied: >>> 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' >> >> Can you open it in Notepad from the same command prompt? >> > Opens with Notepad and jEdit from the menu off a py file. That's not what I asked. Does it open in Notepad from the same command prompt where you try to run python? Or indeed any command prompt: C:\WINDOWS> notepad C:\Users\Wayne\.idlerc\recent-files.lst > I see recent-files.lst is openable with Word. Thats nort a surprise, its probably just a text file, so Windows could associate just about anything! > I see mydir_math.py is opened with python.exe!!?? > True of other py files. Which is what you'd expect, after all the default behaviour for a python script should surely be to get executed by Python? What else would you expect? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Tue Dec 27 03:43:43 2011 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Dec 2011 18:43:43 -0800 Subject: [Tutor] A few Python Mysteries [Reset] In-Reply-To: References: <4EEF67B4.6090109@sbcglobal.net> <4EF2A24C.7070701@sbcglobal.net> <4EF34EF6.2030002@sbcglobal.net> <4EF35757.2030105@sbcglobal.net> <4EF35CD1.1040109@sbcglobal.net> <4EF3802A.2050300@sbcglobal.net> <4EF40171.9030508@sbcglobal.net> <4EF60B76.4030604@sbcglobal.net> <4EF614ED.9040607@sbcglobal.net> <4EF620D0.4020008@sbcglobal.net> <4EF8C388.3000707@sbcglobal.net> Message-ID: <4EF930DF.3030406@sbcglobal.net> Regardless, the problem is solved. See my [SOLVED] msg I put up this morning (USA). It's in response to Lie Ryan. However, I have no real idea how is was caused. On 12/26/2011 1:28 PM, Alan Gauld wrote: > On 26/12/11 18:57, Wayne Watson wrote: > >>>> IOError: [Errno 13] Permission denied: >>>> 'C:\\Users\\Wayne\\.idlerc\\recent-files.lst' >>> >>> Can you open it in Notepad from the same command prompt? >>> >> Opens with Notepad and jEdit from the menu off a py file. > > That's not what I asked. > Does it open in Notepad from the same command prompt > where you try to run python? Or indeed any command prompt: > > C:\WINDOWS> notepad C:\Users\Wayne\.idlerc\recent-files.lst > >> I see recent-files.lst is openable with Word. > > Thats nort a surprise, its probably just a text file, so Windows could > associate just about anything! > >> I see mydir_math.py is opened with python.exe!!?? > > True of other py files. > > Which is what you'd expect, after all the default behaviour for a > python script should surely be to get executed by Python? What else > would you expect? > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet CE 1955 October 20 07:53:32.6 UT -- "The Date" The mystery unfolds. Web Page: From rhettnaxel at gmail.com Tue Dec 27 16:17:55 2011 From: rhettnaxel at gmail.com (Alexander) Date: Tue, 27 Dec 2011 10:17:55 -0500 Subject: [Tutor] list mail formatting In-Reply-To: <4EF456D8.9040607@pearwood.info> References: <20111221114905.GA27863@kontrol.kode5.net> <4EF456D8.9040607@pearwood.info> Message-ID: On Fri, Dec 23, 2011 at 5:24 AM, Steven D'Aprano wrote: > Alexander Etter wrote: > > Ah I know of what you mentioned. On an GNU Emacs mailing list I was >> advised to avoid anything but plaintext. It just seems so archaic. But I'm >> a novice and will learn why eventually. >> > > There's a number of reasons. In no particular order, and in all cases > "you" is generic you, not you personally. > > * Mastery of your tools. Are you the master of your tools, or are they the > master of you? If the writer can't turn off HTML mail in common mail > clients, there is little hope that he can control a compiler, an editor, > source control, etc. And if he *won't* turn it off, that shows laziness and > carelessness to others that reflects badly. Especially in the open source > coding community, including here, your reputation is worth more than gold. > > * Code is plain text. Editors sometimes use colour and formatting to > highlight parts of the code, but fundamentally, programming is about > reading and writing code. If you need fancy fonts and formatting and > dancing paperclips to get your message across, chances are you will never > be more than a mediocre programmer. > > * Mail client independence. The people you are writing to use a wide > variety of mail clients, under many different circumstances. They might be > logged into a Unix server with only a primitive command-line mail app; they > might be using mutt, or Thunderbird, or Outlook, or possibly not even > reading it via mail at all, but via a newsgroup on Usenet. All of these > programs may display your message differently. You have no control over the > presentation that the user will see -- best to make the fewest assumptions, > namely, plain text, and not rely on features which may be missing. > > * Your readers may be colour blind, and your red and green lines may look > identical. Or they may be completely blind, and using a screen reader. Or > they might prefer to disable HTML emails, and avoid all the dangers and > problems with it (security vulnerabilities, privacy breaches, and the > rest). Or they might be sick and tired of straining to reading crappy > emails with light blue text on a slightly darker blue background. Either > way, your formatting is lost. Don't expect people to turn on HTML display > just for you. > > * Layout of code (especially Python code) is special. Your mail client may > mangle the layout. It is very common to see code posted where all > indentation is lost, or even line breaks, so everything is squashed into a > single line: > > def func(a, b): while b < 100: print b b += 1 print a-b > > Or every line is separated by a blank line, which makes it a PITA to paste > into the interactive interpreter. Even if the reader can fix the mangling, > they shouldn't have to. > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Thanks for the clarity Steven. -- Alexander 7D9C597B -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicktocco at comcast.net Wed Dec 28 02:31:57 2011 From: nicktocco at comcast.net (nicktocco at comcast.net) Date: Wed, 28 Dec 2011 01:31:57 +0000 (UTC) Subject: [Tutor] help with script In-Reply-To: <742371630.61334.1325035323706.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> Message-ID: <756528553.61617.1325035917739.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> hello, my name is nick. i got python for software design by Allen B. Downey as a gift for christmas. i am completely new to programming and i am having trouble figuring out how to do an exercise concerning script.. my problem 5 x=5 x+1 im ok when it comes to using python so far. but it has asked me to put the problem into a script and run it. my question is how do i put that problem into a script and then how do i run it in python. im learning by myself at home so im having trouble figuring this out on my own. my os is win 7 i have python 2.7 sorry about punctuation! -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Wed Dec 28 02:40:58 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 27 Dec 2011 20:40:58 -0500 Subject: [Tutor] help with script In-Reply-To: <756528553.61617.1325035917739.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> References: <742371630.61334.1325035323706.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> <756528553.61617.1325035917739.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> Message-ID: On Tue, Dec 27, 2011 at 8:31 PM, wrote: > hello, my name is nick. i got python for software design by Allen B. > Downey as a gift for christmas. i am completely new to programming and i am > having trouble figuring out how to do an exercise concerning script.. > my problem > 5 > x=5 > x+1 > im ok when it comes to using python so far. but it has asked me to put the > problem into a script and run it. my question is how do i put that problem > into a script and then how do i run it in python. im learning by myself at > home so im having trouble figuring this out on my own. my os is win 7 i > have python 2.7 > sorry about punctuation! > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Follow these steps: 1. Start 2. All Programs 3. Python > Python 2.7 This will open "Python Shell" 4. Go to File, New window 5. A new window (untitled) will open. Save this to your desktop. Call it "test" or "box" or "cloud" 5. You can now write python to a file. Go ahead and try it. You will need to save it before you run it. 6. Do this by pressing F5 or by going up to run (after you save) For example, by running this: x=5 print x print x+1 print x will print this in the shell: >>> 5 6 5 >>> You can also just run from the shell itself, but I mostly use this for simple one liners and stuff (which is what you are doing above) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Dec 28 03:08:30 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 27 Dec 2011 21:08:30 -0500 Subject: [Tutor] [Python-Help] What is lambdas in Python?? In-Reply-To: References: Message-ID: <4EFA7A1E.5090502@gmail.com> On 12/27/2011 8:36 PM, Hitesh Kumar wrote: > I really don't get it. What is lambda? I keep seeing it and I couldn't > understand anything online about it. lambda An anonymous inline function consisting of a single /expression/ <#term-expression> which is evaluated when the function is called. The syntax to create a lambda function is lambda [arguments]: expression It is a way to create a simple anonymous function. func = lambda x, y : x + y is the equivalent of def func(x, y): return x = y Handy when the function returns an expression (no compound statements) and does not need a name, e.g. map(lambda x, y : x + y, (1,2,3), (4,5,6)) OK now you wonder what is map so: map(/function/, /iterable/, /.../) Apply /function/ to every item of /iterable/ and return a list of the results. If additional /iterable/ arguments are passed, /function/ must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If /function/ is None, the identity function is assumed; if there are multiple arguments, map() <#map> returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). The /iterable/ arguments may be a sequence or any iterable object; the result is always a list. >>> print map(lambda x, y : x + y, (1,2,3), (4,5,6)) [5, 7, 9] -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Wed Dec 28 05:03:22 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 27 Dec 2011 23:03:22 -0500 Subject: [Tutor] [Python-Help] What is lambdas in Python?? In-Reply-To: <4EFA7A1E.5090502@gmail.com> References: <4EFA7A1E.5090502@gmail.com> Message-ID: <273646826.20111227230322@columbus.rr.com> > I really don't get it. What is lambda? I keep seeing it and I > couldn't understand anything online about it. It took me a while to get it too. It's for those rare times when you want a throwaway function. Like you want to do something kind of functioney without going to the trouble of writing a whole def statement for it. Personally, I usually use it when I need to do custom sorts. Alan From alan.gauld at btinternet.com Wed Dec 28 10:54:29 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Dec 2011 09:54:29 +0000 Subject: [Tutor] help with script In-Reply-To: <756528553.61617.1325035917739.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> References: <742371630.61334.1325035323706.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> <756528553.61617.1325035917739.JavaMail.root@sz0099a.westchester.pa.mail.comcast.net> Message-ID: On 28/12/11 01:31, nicktocco at comcast.net wrote: > hello, my name is nick. i got python for software design by Allen B. > Downey as a gift for christmas. i am completely new to programming Welcome, we are here to help :-) > 5 > x=5 > x+1 > im ok when it comes to using python so far. but it has asked me to put > the problem into a script and run it. my question is how do i put that > problem into a script and then how do i run it in python. The Python interpreter interactiove prompt (>>>) does a neat trick of evaluating expressions and printing the result. So the 3 expressions you have will evaluate to 2 values: 5 6 The x assignment will not print any result. When you put things in a script (just a text file containing python commands) and run it, the interpreter will not display the result of an expression, you have to tell it explicitly to do that, using print(). So to make your three lines of code into a script open up any text editor (Notepad will do for this one but you will probably find IDLE is better longer term) Into that file type print (5) x = 5 print (x+1) Now save the file. Give it any name you like but with a .py extension. Lets say you choose test1.py. Now if you double click that file in Windows explorer (I'm assuming you are on Windows, if MacOS or Linux suibstitute your own favourite File manager) the program will start up run and close down so quickly you won;t be able to read it. To get round that add a final line: input("Hit Enter to quit...") Don't worry what it does just yet, just make sure its the last line in the file. Now, when you start the test1.py it will pause before closing until you hit enter. Try that and let us know if you hit any problems. You might also like to browse the folowing topics in my tutorial, they all gradually introduce the idea of running Python scripts: - Getting Started - More Sequences - Add a little Style HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From rail.shafigulin at gmail.com Wed Dec 28 18:13:23 2011 From: rail.shafigulin at gmail.com (rail shafigulin) Date: Wed, 28 Dec 2011 12:13:23 -0500 Subject: [Tutor] python logger Message-ID: has anyone used python logger before? i'm trying to adapt it for my workplace. right now it is pretty simplistic for me. i'm trying to generate extra output by the LoggerAdapter. however i'm getting errors. specifically i get the following message: Traceback (most recent call last): File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit msg = self.format(record) File "/usr/lib/python3.1/logging/__init__.py", line 650, in format return fmt.format(record) File "/usr/lib/python3.1/logging/__init__.py", line 438, in format record.message = record.getMessage() File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage msg = msg % self.args TypeError: not all arguments converted during string formatting i'm using thisdocumentation. any here is my code import logging import logging.handlers class TestInfo(object): def __init__(self, test_name = None, description = '', notes = '', expected = None, actual = None, status = 'Fail', timestamp = None): self.__test_name = test_name self.__description = description self.__notes = notes self.__expected = expected self.__actual = actual self.__status = status self.__timestamp = timestamp def __getitem__(self, name): """ To allow this instance to look like a dict. """ result = None if 'test_name' == name: result = self.__test_name elif 'description' == name: result = self.__description elif 'notes' == name: result = self.__notes elif 'expected' == name: result = self.__expected elif 'actual' == name: result = self.__actual elif 'status' == name: status = self.__status elif 'timestamp' == name: timestamp = self.__timestamp else: result = self.__dict__.get(name, "?") return result def __iter__(self): """ To allow iteration over keys, which will be merged into the LogRecord dict before formatting and output. """ names = ['test_name', 'description', 'notes', 'expected', 'actual', 'status', 'timestamp'] names.extend(self.__dict__.keys()) return names.__iter__() def main(): testinfo = TestInfo( test_name = 'myname', description = 'mydescription', notes = 'mynotes', expected = 'myexpected', actual = 'myactual', status = 'Fail', timestamp = 'mystamp') mylogger = logging.getLogger('mylogger') mylogger.setLevel(logging.DEBUG) filehandler = logging.FileHandler('test.log') filehandler.setLevel(logging.DEBUG) mylogger.addHandler(filehandler) mylogadapter = logger.LoggerAdapter(mylogger, testinfo) mylogadapter.info('this is a log message', testinfo) if __name__ == "__main__": main() any help on how to add extra output parameters is appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Wed Dec 28 19:03:45 2011 From: timomlists at gmail.com (Timo) Date: Wed, 28 Dec 2011 19:03:45 +0100 Subject: [Tutor] python logger In-Reply-To: References: Message-ID: <4EFB5A01.2060901@gmail.com> Op 28-12-11 18:13, rail shafigulin schreef: > has anyone used python logger before? i'm trying to adapt it for my > workplace. right now it is pretty simplistic for me. i'm trying to > generate extra output by the LoggerAdapter. however i'm getting > errors. specifically i get the following message: > > Traceback (most recent call last): > File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit > msg = self.format(record) > File "/usr/lib/python3.1/logging/__init__.py", line 650, in format > return fmt.format(record) > File "/usr/lib/python3.1/logging/__init__.py", line 438, in format > record.message = record.getMessage() > File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage > msg = msg % self.args > TypeError: not all arguments converted during string formatting Without reading the code, you are passing too many arguments for a format string. >>> msg = 'one arg %s and a second %s' >>> msg % ('foo', 'bar', 'baz') # Pass 3 arguments Traceback (most recent call last): File "", line 1, in TypeError: not all arguments converted during string formatting Cheers, Timo > > i'm using this > > documentation. any > > here is my code > > import logging > import logging.handlers > > class TestInfo(object): > def __init__(self, test_name = None, > description = '', > notes = '', > expected = None, > actual = None, > status = 'Fail', > timestamp = None): > self.__test_name = test_name > self.__description = description > self.__notes = notes > self.__expected = expected > self.__actual = actual > self.__status = status > self.__timestamp = timestamp > > def __getitem__(self, name): > """ > To allow this instance to look like a dict. > """ > result = None > if 'test_name' == name: > result = self.__test_name > elif 'description' == name: > result = self.__description > elif 'notes' == name: > result = self.__notes > elif 'expected' == name: > result = self.__expected > elif 'actual' == name: > result = self.__actual > elif 'status' == name: > status = self.__status > elif 'timestamp' == name: > timestamp = self.__timestamp > else: > result = self.__dict__.get(name, "?") > return result > > def __iter__(self): > """ > To allow iteration over keys, which will be merged into > the LogRecord dict before formatting and output. > """ > names = ['test_name', 'description', 'notes', 'expected', > 'actual', 'status', 'timestamp'] > names.extend(self.__dict__.keys()) > return names.__iter__() > > def main(): > testinfo = TestInfo( > test_name = 'myname', > description = 'mydescription', > notes = 'mynotes', > expected = 'myexpected', > actual = 'myactual', > status = 'Fail', > timestamp = 'mystamp') > > mylogger = logging.getLogger('mylogger') > mylogger.setLevel(logging.DEBUG) > > filehandler = logging.FileHandler('test.log') > filehandler.setLevel(logging.DEBUG) > > mylogger.addHandler(filehandler) > mylogadapter = logger.LoggerAdapter(mylogger, testinfo) > mylogadapter.info ('this is a log message', > testinfo) > > if __name__ == "__main__": > main() > > any help on how to add extra output parameters is appreciated. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From __peter__ at web.de Wed Dec 28 19:40:50 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 Dec 2011 19:40:50 +0100 Subject: [Tutor] python logger References: Message-ID: rail shafigulin wrote: > has anyone used python logger before? i'm trying to adapt it for my > workplace. right now it is pretty simplistic for me. i'm trying to > generate > extra output by the LoggerAdapter. however i'm getting errors. > specifically i get the following message: > > Traceback (most recent call last): > File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit > msg = self.format(record) > File "/usr/lib/python3.1/logging/__init__.py", line 650, in format > return fmt.format(record) > File "/usr/lib/python3.1/logging/__init__.py", line 438, in format > record.message = record.getMessage() > File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage > msg = msg % self.args > TypeError: not all arguments converted during string formatting > > i'm using > thisdocumentation. > any > > here is my code [snip] That's not the actual code; it fails with another exception: Traceback (most recent call last): File "logger_orig.py", line 74, in main() File "logger_orig.py", line 70, in main mylogadapter = logger.LoggerAdapter(mylogger, testinfo) NameError: global name 'logger' is not defined In the actual code the line > mylogadapter = logger.LoggerAdapter(mylogger, testinfo) has probably logging instead of logger. Under that assumption: Technically you get an error because you have a format string without any placeholders. When the info() method of a Logger (or LoggerAdapter) receives more than one argument it tries to use the first argument as a format string as demonstrated below: >>> import logging >>> logging.basicConfig(level=logging.INFO) >>> logging.info("foo") INFO:root:foo >>> logging.info("foo", "bar") Traceback (most recent call last): File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit msg = self.format(record) File "/usr/lib/python3.1/logging/__init__.py", line 650, in format return fmt.format(record) File "/usr/lib/python3.1/logging/__init__.py", line 438, in format record.message = record.getMessage() File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage msg = msg % self.args TypeError: not all arguments converted during string formatting >>> logging.info("foo BAR:%s", "bar") INFO:root:foo BAR:bar >>> logging.info("foo BAR:%s BAZ:%s", "bar", "baz") INFO:root:foo BAR:bar BAZ:baz I've not used a LoggerAdapter myself, but as I read the docs it is meant to simplify the addition of extra data, e. g. if you have common_extra = {"notes": "whatever"} ... logger.info("one", extra_common_extra) ... logger.info("two", extra=common_extra) ... logger.info("three", extra=common_extra) ... you can simplify that to logger = logging.LoggingAdapter(logger, {"notes": "whatever"}) ... logger.info("one") ... logger.info("two") ... logger.info("three") Applying the principle to your code: def main(): # recommended indent is 4 spaces testinfo = TestInfo( test_name='myname', description='mydescription', notes='mynotes', expected='myexpected', actual='myactual', status='Fail', timestamp='mystamp') mylogger = logging.getLogger('mylogger') mylogger.setLevel(logging.DEBUG) filehandler = logging.FileHandler('test.log') filehandler.setLevel(logging.DEBUG) # added to verify that testinfo is indeed passed on: formatter = logging.Formatter(logging.BASIC_FORMAT + " notes: %(notes)s") filehandler.setFormatter(formatter) mylogger.addHandler(filehandler) mylogadapter = logging.LoggerAdapter(mylogger, testinfo) mylogadapter.info('this is a log message') #without adapter the above line would be: #mylogger.info('this is a log message', extra=testinfo) if __name__ == "__main__": main() From lie.1296 at gmail.com Wed Dec 28 20:01:10 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 29 Dec 2011 06:01:10 +1100 Subject: [Tutor] python logger In-Reply-To: References: Message-ID: On 12/29/2011 04:13 AM, rail shafigulin wrote: > has anyone used python logger before? i'm trying to adapt it for my > workplace. right now it is pretty simplistic for me. i'm trying to > generate extra output by the LoggerAdapter. however i'm getting errors. > specifically i get the following message: > > Traceback (most recent call last): > File "/usr/lib/python3.1/logging/__init__.py", line 770, in emit > msg = self.format(record) > File "/usr/lib/python3.1/logging/__init__.py", line 650, in format > return fmt.format(record) > File "/usr/lib/python3.1/logging/__init__.py", line 438, in format > record.message = record.getMessage() > File "/usr/lib/python3.1/logging/__init__.py", line 308, in getMessage > msg = msg % self.args > TypeError: not all arguments converted during string formatting Please don't trim the traceback, your traceback is missing the top-most trace which will be the most useful in identifying your current problem. Your problem is here: mylogadapter.info('this is a log message', testinfo) The first argument of the logging function is used as a format string for the following arguments. Since you're passing testinfo as a second argument to .info(), you need a placeholder in your first argument, e.g.: mylogadapter.info('this is a log message, testinfo: %s', testinfo) the logger will convert testinfo into a string and substitute that to %s in the format string. Also, for your TestInfo class, you may want to look into collections.namedtuple. From stayvoid at gmail.com Fri Dec 30 14:11:17 2011 From: stayvoid at gmail.com (Stayvoid) Date: Fri, 30 Dec 2011 16:11:17 +0300 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: >You don't have any option. >You either type in the full path or you get the user to tell you >in some way - either with a prompt or via an input argument. OK, now I get it. How can I tell this to the end-user? Should I write a README file or what? I've tried to run lengthcounter_lutz from the file's folder and this worked out. cd /Users/Username/Python_modules/ python /Users/Username/Python_modules/lengthcounter_lutz.py ('Lines:', 12, 'Chars:', 285) But I can't understand what's wrong with the second one: def countLines(name): file = open(name.__file__) return len(file.readlines()) def countChars(name): return len(open(name.__file__).read()) def test(name): return "Lines:", countLines(name), "Chars:", countChars(name) if __name__ == '__main__': import lengthcounter print test(lengthcounter) >>> import lengthcounter >>> lengthcounter.test(lengthcounter) ('Lines:', 5, 'Chars:', 885) That PYTHONPATH variable has no connection with the mess above. When should I use it? Thanks for your help. From alan.gauld at btinternet.com Fri Dec 30 15:07:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 Dec 2011 14:07:06 +0000 Subject: [Tutor] PYTHONPATH (Mac OS X) In-Reply-To: References: <4EEEA9D5.70605@gmail.com> Message-ID: On 30/12/11 13:11, Stayvoid wrote: > I've tried to run lengthcounter_lutz from the file's folder and this worked out. > cd /Users/Username/Python_modules/ > python /Users/Username/Python_modules/lengthcounter_lutz.py You should only have needed: > python ./lengthcounter_lutz.py the ./ tells Linux to use the current folder as startuing point. > ('Lines:', 12, 'Chars:', 285) > > > But I can't understand what's wrong with the second one: > def countLines(name): > file = open(name.__file__) > return len(file.readlines()) > > def countChars(name): > return len(open(name.__file__).read()) > > def test(name): > return "Lines:", countLines(name), "Chars:", countChars(name) > > if __name__ == '__main__': > import lengthcounter > print test(lengthcounter) > >>>> import lengthcounter >>>> lengthcounter.test(lengthcounter) > ('Lines:', 5, 'Chars:', 885) Neither do I but you can debug it easily from the >>> prompt by calling the individual lines/functions. Try: >>> import lengthcounter as lc >>> print lc.__file__ # to check it's using the expected file >>> # assuming it is... >>> print (open(lc.__name__),read()) # check the contents is what we expect >>> print ( len(open(lc.__name__),read()) ) # check the length result >>> print ( len(open(lc.__name__),readlines()) ) # check the lines > That PYTHONPATH variable has no connection with the mess above. When > should I use it? Python uses PYTHONPATH to find modules when you import them. So when we do import lengthcounter above we dont need to be in the same folder as lengthcounter.py to be able to import it. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From stayvoid at gmail.com Fri Dec 30 15:12:38 2011 From: stayvoid at gmail.com (Stayvoid) Date: Fri, 30 Dec 2011 17:12:38 +0300 Subject: [Tutor] Drawing a figure Message-ID: Hey there! I want to write a program that can draw a figure using the coordinates specified by the user and calculate its area. An output should be saved in tiff or png. What should I use for this? Cheers. From alan.gauld at btinternet.com Fri Dec 30 16:15:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 Dec 2011 15:15:22 +0000 Subject: [Tutor] Drawing a figure In-Reply-To: References: Message-ID: On 30/12/11 14:12, Stayvoid wrote: > I want to write a program that can draw a figure using the coordinates > specified by the user and calculate its area. An output should be > saved in tiff or png. > What should I use for this? You have lots of options. Since you are on a Mac you might want to try using the Mac native libraries or OpenGL. Both are available via the MacPython downloads. Or more generically you can use one of the several cross-platform GUI toolkits (GTk, Qt, wxPython, Tkinter) - they all have a Canvas widget that allows you to draw figures. But the easiest option is probably to use the turtle module which lets you draw graphics using turtle commands (like forward, rioght, left, pen up,down, etc. The documentation has several examples and you can find lots of web pages discussing turtle graphics in general terms. Calculating the area is probablybest done indepenmdantly of drawing the figure., Store the coordinates, calculate the shape and hyence its area and display the result. You can buuld this as a text based app first or get the turtle stuff working first, it really doesn;t matter which, then stitch the two elements together in a single UI. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From stayvoid at gmail.com Fri Dec 30 19:49:59 2011 From: stayvoid at gmail.com (Stayvoid) Date: Fri, 30 Dec 2011 21:49:59 +0300 Subject: [Tutor] Drawing a figure In-Reply-To: References: Message-ID: I think I'll stick with PyGTK. How to install it? This FAQ looks outdated: http://faq.pygtk.org/index.py?req=show&file=faq01.019.htp I've also tried to compile it from source: PyGTK asked for pkg-config and pygobject. Pygobject asked for pkg-config. Pkg-config asked for pkg-config and glib: configure: error: pkg-config and glib-2.0 not found, please set GLIB_CFLAGS and GLIB_LIBS to the correct values I know that there is no glib on Mac by default. Where can I get it? Cheers. From alan.gauld at btinternet.com Sat Dec 31 00:52:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 Dec 2011 23:52:59 +0000 Subject: [Tutor] Drawing a figure In-Reply-To: References: Message-ID: On 30/12/11 18:49, Stayvoid wrote: > I think I'll stick with PyGTK. I assume "stick with" implies you have previous experience with GTk? > How to install it? Sorry, can't help there, but there are some other GTk users on the list, maybe some of them use Mac and can help? > I know that there is no glib on Mac by default. Where can I get it? You could try some of the open source repositories for the Mac. The one I've used has been Fink, but there are at least 2 others. I don't know if fink has GTk though... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From brylie at gnumedia.org Sat Dec 31 17:38:02 2011 From: brylie at gnumedia.org (Brylie Oxley) Date: Sat, 31 Dec 2011 08:38:02 -0800 Subject: [Tutor] Drawing a figure In-Reply-To: References: Message-ID: <4EFF3A6A.6060700@gnumedia.org> There is a simple Python graphics library, written by John Zelle for his Python Programming textbook: http://mcsp.wartburg.edu/zelle/python/ http://mcsp.wartburg.edu/zelle/python/graphics/graphics/index.html The textbook is also worth reading. It is very well written. --Brylie Oxley -------------- next part -------------- An HTML attachment was scrubbed... URL: