From bgailer at gmail.com Fri Nov 1 03:36:12 2013 From: bgailer at gmail.com (bob gailer) Date: Thu, 31 Oct 2013 22:36:12 -0400 Subject: [Tutor] Help with converting a string into a integer In-Reply-To: References: <5272321C.7010607@gmail.com> <52723A59.5000002@gmail.com> <527254EE.2090206@gmail.com> <52728E68.1060502@gmail.com> Message-ID: <5273139C.2010804@gmail.com> On 10/31/2013 2:51 PM, Carmen Salcedo wrote: > Thanks Bob! :) I'm very new at programming in Python. I appreciate your feedback. Here are some improvements to consider: import string def main(): d = {"1" : phoneTranslator, "2" : backwardString} # map user selection to corresponding function while True: selection = raw_input("Enter you choice. Enter 1 " + "for Phone Translator or 2 for Backward String.") operation = d.get(selection, None) # retrieve corresponding function or None if operation: # did we get something? operation() # call it break # out of the while loop print "Invalid choice" def phoneTranslator(): trans = string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", "22233344455566677778889999") print "Phone Translator " phoneNumber = raw_input ("Please enter the phone number: ").upper() phoneNumber = phoneNumber.translate(trans) print phoneNumber[:3] + "-" + phoneNumber[3:] def backwardString(): print "not implemented" main() -- Bob Gailer 919-636-4239 Chapel Hill NC From breamoreboy at yahoo.co.uk Fri Nov 1 04:10:50 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 01 Nov 2013 03:10:50 +0000 Subject: [Tutor] Help with converting a string into a integer In-Reply-To: <5273139C.2010804@gmail.com> References: <5272321C.7010607@gmail.com> <52723A59.5000002@gmail.com> <527254EE.2090206@gmail.com> <52728E68.1060502@gmail.com> <5273139C.2010804@gmail.com> Message-ID: On 01/11/2013 02:36, bob gailer wrote: > On 10/31/2013 2:51 PM, Carmen Salcedo wrote: >> Thanks Bob! :) I'm very new at programming in Python. I appreciate >> your feedback. > Here are some improvements to consider: > > import string > def main(): > d = {"1" : phoneTranslator, "2" : backwardString} # map user > selection to corresponding function > while True: > selection = raw_input("Enter you choice. Enter 1 " + > "for Phone Translator or 2 for Backward String.") > operation = d.get(selection, None) # retrieve corresponding > function or None > if operation: # did we get something? > operation() # call it > break # out of the while loop > print "Invalid choice" > > def phoneTranslator(): > trans = string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", > "22233344455566677778889999") > print "Phone Translator " > phoneNumber = raw_input ("Please enter the phone number: ").upper() > phoneNumber = phoneNumber.translate(trans) > print phoneNumber[:3] + "-" + phoneNumber[3:] > > def backwardString(): > print "not implemented" > > main() > Better yet wrap the call to main() so it's not always called when the module gets imported, plus some error handling wouldn't go amiss. For anyone using Python 3 raw_input becomes input and you don't need the import string, it's simply str.maketrans(...). -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From fomcl at yahoo.com Fri Nov 1 10:51:19 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 1 Nov 2013 02:51:19 -0700 (PDT) Subject: [Tutor] load test a web application? Message-ID: <1383299479.32534.YahooMailBasic@web163804.mail.gq1.yahoo.com> Hi, I am looking at three Github-like programs (Stash, Gitbucket and Trac) to see if they could be used in our company. I would like to test the reliability and stability of at least one of them (I won't do any tests if some required functionality is missing). I am curious whether the program will crash under certain circumstances (e.g. multiple users checking code at *exactly* the same moment). What approach could I follow here? Though this does not *necessarily* have to involve Python, I would prefer this. The way I see it, it would carry out certain common usage patterns many usage patterns to simulate many users. I thought about using mechanize/subprocess, the multimechanize package, or the twill package. Very curious to hear your thoughts about this and I hope this is not too vague. Thank you in advance! Regards, 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 breamoreboy at yahoo.co.uk Fri Nov 1 15:05:55 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 01 Nov 2013 14:05:55 +0000 Subject: [Tutor] load test a web application? In-Reply-To: <1383299479.32534.YahooMailBasic@web163804.mail.gq1.yahoo.com> References: <1383299479.32534.YahooMailBasic@web163804.mail.gq1.yahoo.com> Message-ID: On 01/11/2013 09:51, Albert-Jan Roskam wrote: > Hi, > > I am looking at three Github-like programs (Stash, Gitbucket and Trac) to see if they could be used in our company. I would like to test the reliability and stability of at least one of them (I won't do any tests if some required functionality is missing). > > I am curious whether the program will crash under certain circumstances (e.g. multiple users checking code at *exactly* the same moment). What approach could I follow here? Though this does not *necessarily* have to involve Python, I would prefer this. The way I see it, it would carry out certain common usage patterns many usage patterns to simulate many users. I thought about using mechanize/subprocess, the multimechanize package, or the twill package. > > Very curious to hear your thoughts about this and I hope this is not too vague. Thank you in advance! > > Regards, > 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? > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > It's my belief that this request is way beyond the remit of a tutor mailing list. The main mailing list is one obvious place to go, but maybe better yet would be the specialist testing list. This is available at gmane.comp.python.testing.general. Regardless of this I wish you the best of luck with your endeavours :) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From jennyallar at gmail.com Fri Nov 1 19:43:25 2013 From: jennyallar at gmail.com (Jenny Allar) Date: Fri, 1 Nov 2013 14:43:25 -0400 Subject: [Tutor] Positional Arguments Message-ID: Hi everyone, I'm onto my next assignment and I think I have the basics together, but I'm having issues passing values from one function to another. I'm using Python 3.3.2 on Windows 7 and below is my assignment and code with the error that's got me hung up. Thanks in advance for your help. Assignment: 6. Assignment (after Chapter 6) Write a payroll program that pays time and a half for anything over 40 hours. This should have 3 functions in addition to main. 1. The first function asks the user how many total hours were worked and the pay rate and returns this information to main. These values must be validated. Hours worked must be at least 8 and no more than 86. Pay rate cannot be less than $7.00 or more than $50.00. 2. The second function calculates the regular hours and overtime hours and returns this information to main. A person might work less than 40 hours so you must allow for that situation. 3. The third function calculates the regular pay, (regular hours times pay rate); overtime pay, (overtime hours times overtime pay rate) and the total pay and returns this information to main. 4. Main will then display this information on the screen like the sample below. (Values will have to be passed and returned). The output should look something like the following: Payroll Information Pay rate $10.00 Regular Hours 40 Overtime hours 20 Regular pay $400.00 Overtime pay $300.00 Total Pay $700.00 My code: #This program calculates pay for time and a half for hours worked over 49. #This program uses three functions in addition to main to accomplish the task. def main(): print() print("This program calculates your payroll information.") print() gethours() #Call the function that gets the hours worked payrate print() calcandprint() # Call the function that calculates and prints the information calc_pay() # Call the function that calculates the total pay #This function asks for and accepts the hours worked. # #Variable Type Purpose #hrswrkd int hold for number of hours worked #payrate int hold for rate of pay per hour def gethours(): print('Please enter the number of hours worked.') hrswrkd=int(input('The number must be at least 8 and no more than 86. ')) print() while hrswrkd < 8 or hrswrkd > 86: #Validate the number of hours worked print('Error --- The number of hours worked must be no less than 8 and no more than 86.') hrswrkd=int(input('Please try again. ')) print() print('Please enter the rate of pay.') payrate=int(input('The number must be at least $7.00 and no more than $50.00. ')) while payrate < 7.00 or payrate > 50.00: #Validate the rate of pay print('Error --- The rate of pay must be more than $7.00 and no more than $50.00. ') print() return hrswrkd, payrate # Return values to main function #This function calculates the number of straight time hours and over time hours # and prints the information. # #Variable Type Purpose #strthrs int hold for hours paid at straight time #overhrs int hold for hours paid at time and a half # def calcandprint (hrswrkd, payrate): if hrswrkd <= 40: calc_pay(hrswrkd, payrate) print('You have worked', hrswrkd, 'hours paid in straight time for this pay period.') print('You have worked 0 hours paid in overtime pay for this pay period.') else: calc_pay(hrswrkd, payrate) print('You have worked 40 hours paid in straight time for this pay period.') print('You have worked', hrswrkd - 40, 'hours paid in overtime pay for this pay period.') return hrswrkd, payrate def calc_pay(hrswrkd, payrate): # #This function calculates the pay for hours worked earning straight time pay and #pay for hours worked earning overtime pay, and caclulated the total pay. #This function also returns the information to main. # #Variable Type Purpose #regpay int hold for regular time pay #overtimepay int hold for overtime pay #totalpay int hold for total pay for time period # if hrswrkd <= 40: regpay=hrswrkd * payrate overtimepay=0 else: overtimepay=(hrswrkd-40) * (payrate * 1.5) regpay=40 * payrate totalpay=regpay+overtimepay return regpay, overtimepay, totalpay print() print(' Payroll Information') print('Pay Rate: ', format(payrate, '.2f')) print('Regular Hours: ', format(regpay // payrate, '.2f')) print('Overtime Hours: ', format(overtimepay // (payrate * 1.5), '.2f')) print('Regular Pay: ', format(regpay, '.2f')) print('Overtime Pay: ', format(overtimepay, '.2f')) print('Total Pay: ', format(totalpay, '.2f')) main() Error: Traceback (most recent call last): File "C:\", line 93, in main() File "C:\", line 15, in main calcandprint() # Call the function that calculates and prints the information TypeError: calcandprint() missing 2 required positional arguments: 'hrswrkd' and 'payrate' Again, thank you. From breamoreboy at yahoo.co.uk Fri Nov 1 23:46:33 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 01 Nov 2013 22:46:33 +0000 Subject: [Tutor] Positional Arguments In-Reply-To: References: Message-ID: On 01/11/2013 18:43, Jenny Allar wrote: > gethours() #Call the function that gets the hours worked payrate You throw away hrswrkd and payrate from gethours here > print() > calcandprint() # Call the function that calculates and prints the Then you call calcandprint with no arguments at all, but you've defined it to take two, hence your error below. So:- hrswrkd, payrate = gethours() print() x, y = calcandprint(hrswrkd, payrate) etc. > def calcandprint (hrswrkd, payrate): > Error: > > Traceback (most recent call last): > File "C:\", line 93, in > main() > File "C:\", line 15, in main > calcandprint() # Call the function that calculates and prints the > information > TypeError: calcandprint() missing 2 required positional arguments: > 'hrswrkd' and 'payrate' > Again, thank you. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From emile at fenx.com Fri Nov 1 23:47:08 2013 From: emile at fenx.com (Emile van Sebille) Date: Fri, 01 Nov 2013 15:47:08 -0700 Subject: [Tutor] Positional Arguments In-Reply-To: References: Message-ID: The traceback shows: > TypeError: calcandprint() missing 2 required positional arguments: > 'hrswrkd' and 'payrate' and the definition of calcandprint is > def calcandprint (hrswrkd, payrate): which shows it requiring two parameters: 'hrswrkd' and 'payrate' so the proper way to call the function would be: calcandprint (86, 11.50) which would (presumably) calculate and print the result of having worked 86 hours at a payrate of 11.50/hr But-I-didn't-read-all-your-code-ly y'rs, Emile On 11/1/2013 11:43 AM, Jenny Allar wrote: > Hi everyone, > > I'm onto my next assignment and I think I have the basics together, > but I'm having issues passing values from one function to another. I'm > using Python 3.3.2 on Windows 7 and below is my assignment and code > with the error that's got me hung up. > > Thanks in advance for your help. > > Assignment: 6. Assignment (after Chapter 6) > Write a payroll program that pays time and a half for anything over 40 > hours. This should have 3 functions in addition to main. > 1. The first function asks the user how many total hours were > worked and the pay rate and returns this information to main. These > values must be validated. Hours worked must be at least 8 and no more > than 86. Pay rate cannot be less than $7.00 or more than $50.00. > 2. The second function calculates the regular hours and overtime > hours and returns this information to main. A person might work less > than 40 hours so you must allow for that situation. > 3. The third function calculates the regular pay, (regular hours > times pay rate); overtime pay, (overtime hours times overtime pay > rate) and the total pay and returns this information to main. > 4. Main will then display this information on the screen like the > sample below. (Values will have to be passed and returned). > > The output should look something like the following: > > Payroll Information > > Pay rate > $10.00 > > Regular Hours > 40 > > Overtime hours > 20 > > Regular pay > $400.00 > > Overtime pay > $300.00 > > Total Pay > $700.00 > > > > > My code: > > #This program calculates pay for time and a half for hours worked over 49. > #This program uses three functions in addition to main to accomplish the task. > > def main(): > print() > print("This program calculates your payroll information.") > print() > > gethours() #Call the function that gets the hours worked payrate > print() > calcandprint() # Call the function that calculates and prints the > information > calc_pay() # Call the function that calculates the total pay > > #This function asks for and accepts the hours worked. > # > #Variable Type Purpose > #hrswrkd int hold for number > of hours worked > #payrate int hold for rate > of pay per hour > def gethours(): > print('Please enter the number of hours worked.') > hrswrkd=int(input('The number must be at least 8 and no more than 86. ')) > print() > > while hrswrkd < 8 or hrswrkd > 86: #Validate the number of hours worked > print('Error --- The number of hours worked must be no less > than 8 and no more than 86.') > hrswrkd=int(input('Please try again. ')) > print() > print('Please enter the rate of pay.') > payrate=int(input('The number must be at least $7.00 and no more > than $50.00. ')) > while payrate < 7.00 or payrate > 50.00: #Validate the rate of pay > print('Error --- The rate of pay must be more than $7.00 and > no more than $50.00. ') > > print() > > return hrswrkd, payrate # Return values to main function > > #This function calculates the number of straight time hours and over time hours > # and prints the information. > # > #Variable Type Purpose > #strthrs int hold > for hours paid at straight time > #overhrs int hold > for hours paid at time and a half > # > def calcandprint (hrswrkd, payrate): > if hrswrkd <= 40: > calc_pay(hrswrkd, payrate) > print('You have worked', hrswrkd, 'hours paid in straight time > for this pay period.') > print('You have worked 0 hours paid in overtime pay for this > pay period.') > else: > calc_pay(hrswrkd, payrate) > print('You have worked 40 hours paid in straight time for this > pay period.') > print('You have worked', hrswrkd - 40, 'hours paid in overtime > pay for this pay period.') > > > return hrswrkd, payrate > > def calc_pay(hrswrkd, payrate): > # > #This function calculates the pay for hours worked earning straight time pay and > #pay for hours worked earning overtime pay, and caclulated the total pay. > #This function also returns the information to main. > # > #Variable Type Purpose > #regpay int hold for > regular time pay > #overtimepay int hold for overtime pay > #totalpay int hold for > total pay for time period > # > if hrswrkd <= 40: > regpay=hrswrkd * payrate > overtimepay=0 > else: > overtimepay=(hrswrkd-40) * (payrate * 1.5) > regpay=40 * payrate > > totalpay=regpay+overtimepay > > return regpay, overtimepay, totalpay > > print() > print(' Payroll Information') > print('Pay Rate: ', > format(payrate, '.2f')) > print('Regular Hours: ', > format(regpay // payrate, '.2f')) > print('Overtime Hours: ', > format(overtimepay // (payrate * 1.5), '.2f')) > print('Regular Pay: ', > format(regpay, '.2f')) > print('Overtime Pay: ', > format(overtimepay, '.2f')) > print('Total Pay: ', > format(totalpay, '.2f')) > main() > > > > > Error: > > Traceback (most recent call last): > File "C:\", line 93, in > main() > File "C:\", line 15, in main > calcandprint() # Call the function that calculates and prints the > information > TypeError: calcandprint() missing 2 required positional arguments: > 'hrswrkd' and 'payrate' > > > > Again, thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Nov 1 23:53:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Nov 2013 22:53:07 +0000 Subject: [Tutor] Positional Arguments In-Reply-To: References: Message-ID: On 01/11/13 18:43, Jenny Allar wrote: > but I'm having issues passing values from one function to another. I'm not sure what you are asking. The error is pretty clear and the cause is as described - you don;t pass any arguments to the function... > def main(): > gethours() > print() > calcandprint() > calc_pay() You don't pass any values to the functions, hence the error > def calcandprint (hrswrkd, payrate): But you define it to take two values in. > return hrswrkd, payrate And it returns two values but you don't assign them anywhere in your main() function. > def calc_pay(hrswrkd, payrate): Also expects two values. > return regpay, overtimepay, totalpay And returns 3 values but again in main() you don't pass any values in and you don't do anything with the values returned. Also as a general rule its better not to mix calculation and printing in a single function. Better to pass in the data, calculate the results and pass those back to another function to print them. It makes the code easier to read and easier to reuse in another program (such as a web app or GUI maybe) > Traceback (most recent call last): > File "C:\", line 93, in > main() > File "C:\", line 15, in main > calcandprint() # Call the function that calculates and prints the > information > TypeError: calcandprint() missing 2 required positional arguments: > 'hrswrkd' and 'payrate' It tells you the problem and your code clearly doesn't pass the values. So what part do you not understand? Can we simplify the exercise a bit and just write a short function that takes in a two arguments and returns a single value? How about Pythagoras theorem? Write a function called hypotenuse that takes two sides of a right angle triangle and returns the hypotenuse? [ ie c = sqrt(a**2 + b**2) ] And then write a main function that asks the user for the two values and prints the result? Can you do that just to check that you understand the mechanics? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From noponus at yahoo.com Sat Nov 2 00:27:13 2013 From: noponus at yahoo.com (olatunde Adebayo) Date: Fri, 1 Nov 2013 16:27:13 -0700 (PDT) Subject: [Tutor] simplegui problem Message-ID: <1383348433.93399.YahooMailNeo@web125605.mail.ne1.yahoo.com> Hi everybody. I am trying to run a program that has been successfully run on codeskulptor using window power shell: The problem is "import simplegui", How can I access"import simplegui" using powershell thank you Olatunde -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 2 01:29:06 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Nov 2013 00:29:06 +0000 Subject: [Tutor] simplegui problem In-Reply-To: <1383348433.93399.YahooMailNeo@web125605.mail.ne1.yahoo.com> References: <1383348433.93399.YahooMailNeo@web125605.mail.ne1.yahoo.com> Message-ID: On 01/11/13 23:27, olatunde Adebayo wrote: > I am trying to run a program that has been successfully run on > codeskulptor using window power shell: This list is for people learning Python and its standard library. Neither of the above are part of that, therefore we need more information to help you. What is codeskulptor? And is that the same "Window Powershell" that is used to write programs on Windows as a replacement for DOS batch files? Or something else? What is their relationship to Python? Neither are part of the standard distribution. Don't assume we will know or that we will be motivated to search the web looking for answers. More likely we will just move onto the next message... > The problem is "import simplegui", > How can I access"import simplegui" using powershell No idea. Until you explain what you are doing in more detail it's hard to say, especially since there is no program except for the single import line. Do you get an error? If so, please post the entire error text. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From shireenrao at gmail.com Sat Nov 2 02:21:45 2013 From: shireenrao at gmail.com (Srinivas Nyayapati) Date: Fri, 1 Nov 2013 21:21:45 -0400 Subject: [Tutor] simplegui problem In-Reply-To: <1383348433.93399.YahooMailNeo@web125605.mail.ne1.yahoo.com> References: <1383348433.93399.YahooMailNeo@web125605.mail.ne1.yahoo.com> Message-ID: On Fri, Nov 1, 2013 at 7:27 PM, olatunde Adebayo wrote: > Hi everybody. > I am trying to run a program that has been successfully run on > codeskulptor using window power shell: > The problem is "import simplegui", > How can I access"import simplegui" using powershell > > SimpleGui is a python module which was developed for the Python course on Coursera. As Alan mentioned, it is not part of the python standard distribution. That module only works when code is written and execute on their online code editor - http://www.codeskulptor.org. I did find a python package called SimpleGUICS2Pygame available at https://pypi.python.org/pypi/SimpleGUICS2Pygame/ which is a re-implementation of the SimpleGui module. As it says on the module page - Simply change import simplegui by import SimpleGUICS2Pygame.simpleguics2pygame as simplegui in your CodeSkulptor program and run it in standard Python with this module Hope that help -Srini -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sat Nov 2 12:11:10 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 2 Nov 2013 04:11:10 -0700 (PDT) Subject: [Tutor] load test a web application? In-Reply-To: Message-ID: <1383390670.20191.YahooMailBasic@web163803.mail.gq1.yahoo.com> ------------------------------------------- On Fri, 11/1/13, Mark Lawrence wrote: Subject: Re: [Tutor] load test a web application? To: tutor at python.org Date: Friday, November 1, 2013, 3:05 PM On 01/11/2013 09:51, Albert-Jan Roskam wrote: > Hi, > > I am looking at three Github-like programs (Stash, Gitbucket and Trac) to see if they could be used in our company. I would like to test the reliability and stability of at least one of them (I won't do any tests if some required functionality is missing). > > I am curious whether the program will crash under certain circumstances (e.g. multiple users checking code at *exactly* the same moment). What approach could I follow here? Though this does not *necessarily* have to involve Python, I would prefer this. The way I see it, it would carry out certain common usage patterns many usage patterns to simulate many users. I thought about using mechanize/subprocess, the multimechanize package, or the twill package. > It's my belief that this request is way beyond the remit of a tutor mailing list.? The main mailing list is one obvious > place to go, but maybe better yet would be the specialist testing list.?This is available at gmane.comp.python.testing.general.? Hi Mark, Thanks. As you may have noticed I have posted this message on the main Python list. I received one off-list reply (a suggestion to use Github Enterprise). I could still try gmane.comp.python.testing.general. It is surprising that, unlike unittests, load/stress tests apparently are a more obscure domain. I have a book about Python testing (http://www.packtpub.com/python-testing-beginners-guide/book) and as far I can remember it does not cover this topic at all. A little googling does reveal some promising packages, e.g. http://locust.io/, https://pypi.python.org/pypi/funkload, or this overview: https://wiki.python.org/moin/PythonTestingToolsTaxonomy regards, Albert-Jan From breamoreboy at yahoo.co.uk Sat Nov 2 13:38:27 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 02 Nov 2013 12:38:27 +0000 Subject: [Tutor] load test a web application? In-Reply-To: <1383390670.20191.YahooMailBasic@web163803.mail.gq1.yahoo.com> References: <1383390670.20191.YahooMailBasic@web163803.mail.gq1.yahoo.com> Message-ID: On 02/11/2013 11:11, Albert-Jan Roskam wrote: > > ------------------------------------------- > On Fri, 11/1/13, Mark Lawrence wrote: > > Subject: Re: [Tutor] load test a web application? > To: tutor at python.org > Date: Friday, November 1, 2013, 3:05 PM > > On 01/11/2013 09:51, Albert-Jan > Roskam wrote: > > Hi, > > > > I am looking at three Github-like programs (Stash, > Gitbucket and Trac) to see if they could be used in our > company. I would like to test the reliability and stability > of at least one of them (I won't do any tests if some > required functionality is missing). > > > > I am curious whether the program will crash under > certain circumstances (e.g. multiple users checking code at > *exactly* the same moment). What approach could I follow > here? Though this does not *necessarily* have to involve > Python, I would prefer this. The way I see it, it would > carry out certain common usage patterns many usage patterns > to simulate many users. I thought about using > mechanize/subprocess, the multimechanize package, or the > twill package. > > > > >> It's my belief that this request is way beyond the remit of a tutor mailing list. The main mailing list is one obvious >> place to go, but maybe better yet would be the specialist testing list. This is available at gmane.comp.python.testing.general. > > Hi Mark, > > Thanks. As you may have noticed I have posted this message on the main Python list. I received one off-list reply (a suggestion to use Github Enterprise). I could still try gmane.comp.python.testing.general. It is surprising that, unlike unittests, load/stress tests apparently are a more obscure domain. I have a book about Python testing (http://www.packtpub.com/python-testing-beginners-guide/book) and as far I can remember it does not cover this topic at all. A little googling does reveal some promising packages, e.g. http://locust.io/, https://pypi.python.org/pypi/funkload, or this overview: https://wiki.python.org/moin/PythonTestingToolsTaxonomy > > regards, > Albert-Jan > I did see your message. Outside of my knowledge base unfortunately :( Give the testing specialist list a try, nothing ventured, nothing gained, it's available via mechanisms other than the gmane one referenced above. As they say on the stage, go break a leg :) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From alan.gauld at btinternet.com Sat Nov 2 17:51:33 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Nov 2013 16:51:33 +0000 Subject: [Tutor] load test a web application? In-Reply-To: <1383390670.20191.YahooMailBasic@web163803.mail.gq1.yahoo.com> References: <1383390670.20191.YahooMailBasic@web163803.mail.gq1.yahoo.com> Message-ID: On 02/11/13 11:11, Albert-Jan Roskam wrote: > ...It is surprising that, unlike unittests, load/stress tests apparently > are a more obscure domain. Probably because, to do them well, they are incredibly complex and difficult to perform. Even with banks of rack mounted computers and specialised load simulators you still have to get your data build and transaction gapping tuned exactly right to replicate the real world. And then you have the network aspects to simulate and it gets even more complex. If you have to handle clustered deployments, or worse, cloud based, virtual environments it becomes next to impossible. I've worked on maybe 50 major projects over the last 30 years of which only about 5 or 6 even attempted any realistic load/performamce testing. And they all had mega budgets to throw at it. It's just too hard, so most folk just give up or do some token robotics which doesn't really prove anything. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From vincentphua at yahoo.com Sun Nov 3 04:10:13 2013 From: vincentphua at yahoo.com (phua hock choon) Date: Sat, 2 Nov 2013 20:10:13 -0700 (PDT) Subject: [Tutor] Project 4: Parsing rhinoceros sightings Message-ID: <1383448213.13072.YahooMailNeo@web142403.mail.bf1.yahoo.com> Hi Bob , ? I was looking at the a/m project from penn Uni with interest while learning ArcGis?python scripting. ? Would like to enquire whether you still have the solution (Script) for the?" Parsing rhinoceros sightings " ? ? Awaiting for your favourable reply. ? ? tks ? vincent -------------- next part -------------- An HTML attachment was scrubbed... URL: From byron.ruffin at g.austincc.edu Sun Nov 3 04:18:01 2013 From: byron.ruffin at g.austincc.edu (Byron Ruffin) Date: Sat, 2 Nov 2013 22:18:01 -0500 Subject: [Tutor] space between words printed Message-ID: The output generates a sentence made up of words chosen randomly from lists. I am having trouble getting a space between each of the words. Should I be thinking about .split? Here is the code (ignore indent errors as it was copied and pasted) Thank you: import random def wordList(): adj1 = ["Big", "Small", "Early", "Late", "Red", "Tall", "Short"] subj = ["politician", "man", "woman", "whale", "company", "child", "soldier"] obj = ["budget", "money", "box", "gift", "gun", "tank", "drone"] adj2 = ["hot", "crazy", "stupid", "fast", "worthless", "awesome", "dirty"] verb = ["spends", "shoots", "evades", "pursues", "subverts", "passes", "flirts"] y = adj1[generate()], subj[generate()] + obj[generate()] + adj2[generate()] + verb[generate()] return y def generate(): random0_6 = random.randint(0, 6) return random0_6 def main(): print (wordList(), ".", sep="") main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 3 10:08:03 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 03 Nov 2013 09:08:03 +0000 Subject: [Tutor] Project 4: Parsing rhinoceros sightings In-Reply-To: <1383448213.13072.YahooMailNeo@web142403.mail.bf1.yahoo.com> References: <1383448213.13072.YahooMailNeo@web142403.mail.bf1.yahoo.com> Message-ID: On 03/11/13 03:10, phua hock choon wrote: > /Hi Bob ,/ > // > /I was looking at the a/m project from penn Uni with interest while > learning ArcGis python scripting./ > // > /Would like to enquire whether you still have the solution (Script) for > the " Parsing rhinoceros sightings "/ If you read Bob's post(6th Oct) he doesn't have the solution. He asked the original requestor to post his question on the list. That person declined to do so, even though it was probably the best way for him to get the help he needed. His choice. But we did not see the problem, let alone the solution. In fact an earlier request for help on the same problem also failed to reach a public conclusion. I'm not quite sure what the reluctance to discuss this problem is caused by, but it seems that we will be forever teased but never satisfied. :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Sun Nov 3 10:13:36 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 03 Nov 2013 09:13:36 +0000 Subject: [Tutor] space between words printed In-Reply-To: References: Message-ID: On 03/11/2013 03:18, Byron Ruffin wrote: > The output generates a sentence made up of words chosen randomly from > lists. I am having trouble getting a space between each of the words. > Should I be thinking about .split? Here is the code (ignore indent > errors as it was copied and pasted) Thank you: > > import random > > def wordList(): > > adj1 = ["Big", "Small", "Early", "Late", "Red", > "Tall", "Short"] > subj = ["politician", "man", "woman", "whale", "company", > "child", "soldier"] > obj = ["budget", "money", "box", "gift", "gun", > "tank", "drone"] > adj2 = ["hot", "crazy", "stupid", "fast", "worthless", > "awesome", "dirty"] > verb = ["spends", "shoots", "evades", "pursues", "subverts", > "passes", "flirts"] > > y = adj1[generate()], subj[generate()] + obj[generate()] + > adj2[generate()] + verb[generate()] > > return y > > > def generate(): > random0_6 = random.randint(0, 6) > return random0_6 > > > def main(): > > print (wordList(), ".", sep="") > > > main() > Look very carefully at your assignment to y in wordList and you'll eventually answer your own question. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From alan.gauld at btinternet.com Sun Nov 3 10:20:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 03 Nov 2013 09:20:38 +0000 Subject: [Tutor] space between words printed In-Reply-To: References: Message-ID: On 03/11/13 03:18, Byron Ruffin wrote: > The output generates a sentence made up of words chosen randomly from > lists. I am having trouble getting a space between each of the words. You probably want to look at the join() method of strings. It joins a list of strings together using a separator... You might also find string formatting helpful for some elements. Alternatively you could just insert spaces into your string as you assemble it, but I think your wordlist() would be better returning a list of chosen words and you can then assemble/format that into as printable string outside the function. HTH, > import random > > def wordList(): > adj1 = ["Big", "Small", "Early", "Late", "Red", > "Tall", "Short"] > subj = ["politician", "man", "woman", "whale", "company", > "child", "soldier"] > obj = ["budget", "money", "box", "gift", "gun", > "tank", "drone"] > adj2 = ["hot", "crazy", "stupid", "fast", "worthless", > "awesome", "dirty"] > verb = ["spends", "shoots", "evades", "pursues", "subverts", > "passes", "flirts"] > > y = adj1[generate()], subj[generate()] + obj[generate()] + > adj2[generate()] + verb[generate()] > > return y Notice that the first term is not added, it is returned as a separate value. Is that deliberate? I suspect ypou'd be better returning them all that way. > def generate(): > random0_6 = random.randint(0, 6) > return random0_6 > > def main(): > print (wordList(), ".", sep="") > > > main() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sun Nov 3 10:56:11 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 3 Nov 2013 20:56:11 +1100 Subject: [Tutor] space between words printed In-Reply-To: References: Message-ID: <20131103095611.GD15615@ando> On Sat, Nov 02, 2013 at 10:18:01PM -0500, Byron Ruffin wrote: > The output generates a sentence made up of words chosen randomly from > lists. I am having trouble getting a space between each of the words. > Should I be thinking about .split? Here is the code (ignore indent errors > as it was copied and pasted) Thank you: > > import random > > def wordList(): > > adj1 = ["Big", "Small", "Early", "Late", "Red", > "Tall", "Short"] > subj = ["politician", "man", "woman", "whale", "company", > "child", "soldier"] > obj = ["budget", "money", "box", "gift", "gun", > "tank", "drone"] > adj2 = ["hot", "crazy", "stupid", "fast", "worthless", > "awesome", "dirty"] > verb = ["spends", "shoots", "evades", "pursues", "subverts", > "passes", "flirts"] > > y = adj1[generate()], subj[generate()] + obj[generate()] + > adj2[generate()] + verb[generate()] Here you choose random words and concatenate them together without any space. For example, if you choose "crazy" from adj2 and "flirts" from verb, you get "crazyflirts". Solution #1: try adding a space in between each word, like this: adj1[generate()] + " " + subj[generate()] + ... That's a bit tedious when you have more than one or two words to add, so Python gives you a short cut: Solution #2: join a list of words, like this: # Note the commas not plus signs list_of_words = [adj1[generate()], subj[generate()], ... ] sentence = " ".join(list_of_words) By the way, in English you don't normally follow an *adjective* by a verb. Adjectives come before nouns: hot coffee, crazy cat, fast car, worthless trash, and so forth. It is adverbs that come before verbs: quickly run, carefully prepared, slowly drove, and so forth. There is a problem with your generate function: > def generate(): > random0_6 = random.randint(0, 6) > return random0_6 This assumes that each word list has exactly 6 words. If it has fewer than 6, then sometimes choosing a word will fail. If it has more than 6, then words 7, 8, 9, ... will never be choosen. Instead of using: verb[generate()] to choose a random verb, a better solution is: random.choice(verb) and similarly for nouns, adjectives and so forth: list_of_words = [random.choice(adj1), random.choice(subj), random.choice(obj), ... ] That will ensure that each word from each word-list is equally likely to be chosen. -- Steven From akleider at sonic.net Sun Nov 3 17:14:40 2013 From: akleider at sonic.net (Alex Kleider) Date: Sun, 03 Nov 2013 08:14:40 -0800 Subject: [Tutor] space between words printed In-Reply-To: References: Message-ID: <12e2c66229687531896e7d41baa2ae16@sonic.net> On 2013-11-02 20:18, Byron Ruffin wrote: > The output generates a sentence made up of words chosen randomly from > lists.? I am having trouble getting a space between each of the > words.? Should I be thinking about .split?? Here is the code (ignore > indent errors as it was copied and pasted) Thank you: > > import random > > def wordList(): > > ??? adj1 = ["Big",??????? "Small",? "Early",? > "Late",??? "Red",?????? "Tall",??? "Short"] > ??? subj = ["politician", "man",??? "woman",? "whale",?? > "company",?? "child",?? "soldier"] > ??? obj =? ["budget",???? "money",? "box",??? > "gift",??? "gun",?????? "tank",??? "drone"] > ??? adj2 = ["hot",??????? "crazy",? "stupid", "fast",??? > "worthless", "awesome", "dirty"] > ??? verb = ["spends",???? "shoots", "evades", "pursues", > "subverts",? "passes",? "flirts"] > > ??? y = adj1[generate()], subj[generate()] + obj[generate()] + > adj2[generate()] + verb[generate()] > > ??? return y > > def generate(): > ??? random0_6 = random.randint(0, 6) > ??? return random0_6 > > def main(): > ??? > ??? print (wordList(), ".", sep="") > > main() I would suggest that 'wordList' return a tuple (which it sort of does but not quite what I have in mind:-) making eventual printing much easier as in """ print "%s %s %s %s %s." % wordList """. (Modification needed to make it Python3 vs 2.7, I believe.) From bgailer at gmail.com Mon Nov 4 01:21:44 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 03 Nov 2013 19:21:44 -0500 Subject: [Tutor] Automation In-Reply-To: References: <5a74c3f8-b4d8-4927-87f6-82466f93a65b@googlegroups.com> <5276D0DB.5060304@gmail.com> Message-ID: <5276E898.4010603@gmail.com> Always reply in such a way that a copy goes to the tutor list. On 11/3/2013 5:56 PM, Renato Barbosa Pim Pereira wrote: > Solved: > > for row in column: > print row[0] > > Sorry for my ignorance, by now, how can I locate the min/max value for > the printed row?, thanks for patience. Collect the elements in a list. Apply min() and max() to the list. Use list.index() to get the position of the value in the list. Or write your own program to examine each value, tracking when it gets smaller (bigger) and also tracking the index where that change occurs, -- Bob Gailer 919-636-4239 Chapel Hill NC From amalthomas111 at gmail.com Mon Nov 4 12:07:17 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 16:37:17 +0530 Subject: [Tutor] Load Entire File into memory Message-ID: Hi, I am new to python. I am working in computational biology and I have to deal with text files of huge size. I know how to read line by line from a text file. I want to know the best method in *python3* to load the enire file into ram and do the operations.(since this saves time) I am currently using this method to load my text file: *f = open("output.txt")content=io.StringIO(f.read())f.close()* But I have found that this method uses 4 times the size of text file.( if output.txt is 1 gb total ram usage of the code is approx 3.5 gb :( ). Kindly suggest me a better way to do this. Working on Python 3.3.1,ubuntu 13.04(Linux 3.8.0-29-generic x64) Thanks -- *AMAL THOMAS * -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 4 12:35:34 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 04 Nov 2013 11:35:34 +0000 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: On 04/11/13 11:07, Amal Thomas wrote: > I am currently using this method to load my text file: > *f = open("output.txt") > content=io.StringIO(f.read()) > f.close()* > But I have found that this method uses 4 times the size of text file. So why not use f = open("output.txt") content=f.read() f.close() And process the file as a raw string? Is there a reason for using the StringIO? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From amalthomas111 at gmail.com Mon Nov 4 14:06:05 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 18:36:05 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: Hi, Thanks Alan. Now I have made changes in code : Present code: *f = open("output.txt")content=f.read().split('\n') f.close()for lines in content:* * * *content.clear()* Previous code: *f = open("output.txt") content=io.StringIO(f.read()) f.close()for lines in content: * *content.close()* Now I have found that memory use is roughly 1.5 times the size of text file. Previously it was around 4-5 times. Its remarkable change. Waiting for more suggestions. Thanks, On Mon, Nov 4, 2013 at 5:05 PM, Alan Gauld wrote: > On 04/11/13 11:07, Amal Thomas wrote: > > I am currently using this method to load my text file: >> *f = open("output.txt") >> content=io.StringIO(f.read()) >> f.close()* >> >> But I have found that this method uses 4 times the size of text file. >> > > So why not use > > > f = open("output.txt") > content=f.read() > f.close() > > And process the file as a raw string? > > Is there a reason for using the StringIO? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 4 14:16:36 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 04 Nov 2013 13:16:36 +0000 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: On 04/11/13 13:06, Amal Thomas wrote: > Present code: > > *f = open("output.txt") > content=f.read().split('\n') > f.close() If your objective is to save time, then you should replace this with f.readlines() which will save you reprocesasing the entire file to remove the newlines. > for lines in content: > * * > *content.clear()* But if you are processing line by line what makes you think that reading the entire file into RAM and then reprocessing it is faster than reading it line by line? Have you tried that on aqnother file and measutred any significant improvement? There are times when reading into RAM is faster but I'm not sure this will be one of them. for line in f: process line may be your best bet. > *f = open("output.txt") > content=io.StringIO(f.read()) > f.close() > for lines in content: > > * > *content.close()* -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From amalthomas111 at gmail.com Mon Nov 4 14:30:29 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 19:00:29 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: Yes I have found that after loading to RAM and then reading lines by lines saves a huge amount of time since my text files are very huge. On Mon, Nov 4, 2013 at 6:46 PM, Alan Gauld wrote: > On 04/11/13 13:06, Amal Thomas wrote: > > Present code: >> >> >> *f = open("output.txt") >> content=f.read().split('\n') >> f.close() >> > > If your objective is to save time, then you should replace this with > f.readlines() which will save you reprocesasing the entire file to remove > the newlines. > > for lines in content: >> * * >> *content.clear()* >> > > But if you are processing line by line what makes you think that reading > the entire file into RAM and then reprocessing it is faster than reading it > line by line? > > Have you tried that on aqnother file and measutred any significant > improvement? There are times when reading into RAM is faster but I'm not > sure this will be one of them. > > for line in f: > process line > > may be your best bet. > > *f = open("output.txt") >> content=io.StringIO(f.read()) >> f.close() >> for lines in content: >> >> * >> *content.close()* >> > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Mon Nov 4 14:41:11 2013 From: __peter__ at web.de (Peter Otten) Date: Mon, 04 Nov 2013 14:41:11 +0100 Subject: [Tutor] Load Entire File into memory References: Message-ID: Amal Thomas wrote: > Yes I have found that after loading to RAM and then reading lines by lines > saves a huge amount of time since my text files are very huge. How exactly did you find out? You should only see a speed-up if you iterate over the data at least twice. From wrw at mac.com Mon Nov 4 14:46:29 2013 From: wrw at mac.com (William Ray Wing) Date: Mon, 04 Nov 2013 08:46:29 -0500 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> On Nov 4, 2013, at 8:30 AM, Amal Thomas wrote: > Yes I have found that after loading to RAM and then reading lines by lines saves a huge amount of time since my text files are very huge. > [huge snip] > -- > AMAL THOMAS > Fourth Year Undergraduate Student > Department of Biotechnology > IIT KHARAGPUR-721302 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor How long are the lines in your file? In particular, are they many hundreds or thousands of characters long, or are they only few hundred characters, say 200 or less? Unless they are so long as to exceed the normal buffer size of your OS's read-ahead buffer, I strongly suspect that the big time sink in your attempt to read line-by-line was some inadvertent inefficiency that you introduced. Normally, when reading from a text file, python buffers the reads (or uses the host OS buffering). Those reads pull in huge chunks of text WAY ahead of where the actual python processing is going on, and are VERY efficient. -Bill From amalthomas111 at gmail.com Mon Nov 4 14:55:49 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 19:25:49 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: Hi, @Peter: I have checked the execution time manually as well as I found it through my code. During execution of my code, at start, I stored my initial time(start time) to a variable and at the end calculated time taken to run the code = end time - start time. There was a significance difference in time. Thanks, On Mon, Nov 4, 2013 at 7:11 PM, Peter Otten <__peter__ at web.de> wrote: > Amal Thomas wrote: > > > Yes I have found that after loading to RAM and then reading lines by > lines > > saves a huge amount of time since my text files are very huge. > > How exactly did you find out? You should only see a speed-up if you iterate > over the data at least twice. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* -------------- next part -------------- An HTML attachment was scrubbed... URL: From amalthomas111 at gmail.com Mon Nov 4 15:04:46 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 19:34:46 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> Message-ID: @William: Thanks, My Line size varies from 40 to 550 characters. Please note that text file which I have to process is in gigabytes ( approx 50 GB ) . This was the code which i used to process line by line without loading into memory. *for lines in open('uniqname.txt'): * * * On Mon, Nov 4, 2013 at 7:16 PM, William Ray Wing wrote: > On Nov 4, 2013, at 8:30 AM, Amal Thomas wrote: > How long are the lines in your file? In particular, are they many > hundreds or thousands of characters long, or are they only few hundred > characters, say 200 or less? > > Unless they are so long as to exceed the normal buffer size of your OS's > read-ahead buffer, I strongly suspect that the big time sink in your > attempt to read line-by-line was some inadvertent inefficiency that you > introduced. Normally, when reading from a text file, python buffers the > reads (or uses the host OS buffering). Those reads pull in huge chunks of > text WAY ahead of where the actual python processing is going on, and are > VERY efficient. > > -Bill -- *AMAL THOMAS* -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Nov 4 15:48:11 2013 From: davea at davea.name (Dave Angel) Date: Mon, 4 Nov 2013 14:48:11 +0000 (UTC) Subject: [Tutor] Load Entire File into memory References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> Message-ID: On 4/11/2013 09:04, Amal Thomas wrote: > @William: > Thanks, > > My Line size varies from 40 to 550 characters. Please note that text file > which I have to process is in gigabytes ( approx 50 GB ) . This was the > code which i used to process line by line without loading into memory. Now I understand. Processing line by line is slower because it actually reads the whole file. The code you showed earlier: > I am currently using this method to load my text file: > *f = open("output.txt") > content=io.StringIO(f.read()) > f.close()* > But I have found that this method uses 4 times the size of text file. will only read a tiny portion of the file. You don't have any loop on the read() statement, you just read the first buffer full. So naturally it'll be much faster. I am of course assuming you don't have a machine with 100+ gig of RAM. By the way, would you please stop posting html messages to a text newsgroup? They come out completely blank on my other newsreader (except for the Tutor maillist trailer, which IS text), and I end up having to fire up this one just to read your messages. But even if you don't care about me, you should realize that messages sent as html as very frequently garbled when they're interpreted as text. -- DaveA From steve at pearwood.info Mon Nov 4 16:53:41 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Nov 2013 02:53:41 +1100 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> Message-ID: <20131104155340.GE15615@ando> On Mon, Nov 04, 2013 at 02:48:11PM +0000, Dave Angel wrote: > Now I understand. Processing line by line is slower because it actually > reads the whole file. The code you showed earlier: > > > I am currently using this method to load my text file: > > *f = open("output.txt") > > content=io.StringIO(f.read()) > > f.close()* > > But I have found that this method uses 4 times the size of text file. > > will only read a tiny portion of the file. You don't have any loop on > the read() statement, you just read the first buffer full. So naturally > it'll be much faster. Dave, do you have a reference for that? As far as I can tell, read() will read to EOF unless you open the file in non-blocking mode. http://docs.python.org/3/library/io.html#io.BufferedIOBase.read > I am of course assuming you don't have a machine with 100+ gig of RAM. There is that, of course. High-end servers can have multiple hundreds of GB of RAM, but desktop and laptop machines rarely have anywhere near that. -- Steven From amalthomas111 at gmail.com Mon Nov 4 17:26:37 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 21:56:37 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: <20131104155340.GE15615@ando> References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: @Dave: thanks.. By the way I am running my codes on a server with about 100GB ram but I cant afford my code to use 4-5 times the size of the text file. Now I am using read() / readlines() , these seems to be more efficient in memory usage than io.StringIO(f.read()). On Mon, Nov 4, 2013 at 9:23 PM, Steven D'Aprano wrote: > On Mon, Nov 04, 2013 at 02:48:11PM +0000, Dave Angel wrote: > > > Now I understand. Processing line by line is slower because it actually > > reads the whole file. The code you showed earlier: > > > > > I am currently using this method to load my text file: > > > *f = open("output.txt") > > > content=io.StringIO(f.read()) > > > f.close()* > > > But I have found that this method uses 4 times the size of text file. > > > > will only read a tiny portion of the file. You don't have any loop on > > the read() statement, you just read the first buffer full. So naturally > > it'll be much faster. > > > Dave, do you have a reference for that? As far as I can tell, read() > will read to EOF unless you open the file in non-blocking mode. > > http://docs.python.org/3/library/io.html#io.BufferedIOBase.read > > > > I am of course assuming you don't have a machine with 100+ gig of RAM. > > There is that, of course. High-end servers can have multiple hundreds of > GB of RAM, but desktop and laptop machines rarely have anywhere near > that. > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- *AMAL THOMASFourth Year Undergraduate Student Department of Biotechnology IIT KHARAGPUR-721302* -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Nov 4 17:27:52 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 4 Nov 2013 11:27:52 -0500 Subject: [Tutor] Load Entire File into memory In-Reply-To: <20131104155340.GE15615@ando> References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: "I am new to python. I am working in computational biology and I have to deal with text files of huge size. I know how to read line by line from a text file. I want to know the best method in python3 to load the enire file into ram and do the operations.(since this saves time)" If you are new to python why are you so concerned about the speed of your code. You never say how long it takes. Do these files take hours to process? or minutes or seconds? I suggest you write your code in a way that is clear and understandable, then try to optimize it if necessary. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From steve at pearwood.info Mon Nov 4 17:30:10 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Nov 2013 03:30:10 +1100 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: <20131104163009.GF15615@ando> On Mon, Nov 04, 2013 at 07:00:29PM +0530, Amal Thomas wrote: > Yes I have found that after loading to RAM and then reading lines by lines > saves a huge amount of time since my text files are very huge. This is remarkable, and quite frankly incredible. I wonder whether you are misinterpreting what you are seeing? Under normal circumstances, with all but quite high-end machines, trying to read a 50GB file into memory all at once will be effectively impossible. Suppose your computer has 24GB of RAM. The OS and other running applications can be expected to use some of that, but even ignoring this, it is impossible to read a 50GB file into memory all at once with only 24GB. What I would expect is that unless you have *at least* double the amount of memory as the size of the file (in this case, at least 100GB), either Python will give you a MemoryError, or the operating system will try paging memory into swap-space, which is *painfully* slooooow. I've been in the situation where I accidently tried reading a file bigger than the installed RAM, and it ran overnight (14+ hours), locked up and stopped responding, and I finally had to unplug the power and restart the machine. So unless you have 100+ GB in your computer, which would put it in seriously high-end server class, I find it difficult to believe that you are actually reading the entire file into memory. Please try this little bit of code, replacing the file name with the actual name of your 50GB data file: import os filename = "YOUR FILE NAME HERE" print("File size:", os.stat(filename).st_size) f = open(filename) content = f.read() print("Length of content actually read:", len(content)) print("Current file position:", f.tell()) f.close() and send us the output. Thanks, -- Steven From amalthomas111 at gmail.com Mon Nov 4 17:34:46 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 22:04:46 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: @Joel: The code runs for weeks..input file which I have to process in very huge(in 50 gbs). So its not a matter of hours.its matter of days and weeks..I was using C++. Recently I switched over to Python. I am trying to optimize my code to get the outputs in less time and memory efficiently. On Mon, Nov 4, 2013 at 9:57 PM, Joel Goldstick wrote: > > > > If you are new to python why are you so concerned about the speed of > your code. You never say how long it takes. Do these files take > hours to process? or minutes or seconds? I suggest you write your > code in a way that is clear and understandable, then try to optimize > it if necessary. > > -- *AMAL THOMAS* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 4 17:54:16 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 04 Nov 2013 16:54:16 +0000 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: On 04/11/13 16:34, Amal Thomas wrote: > @Joel: The code runs for weeks..input file which I have to process in > very huge(in 50 gbs). So its not a matter of hours.its matter of days > and weeks.. OK, but that's not down to reading the file from disk. Reading a 50G file will only take a few minutes if you have enough RAM, which seems to be the case. If it's taking days/weeks you must be doing some incredibly time consuming processing. It's probably worth putting some more timing statements into your code to see where the time is going because it's not the reading from the disk that's the problem. > trying to optimize my code to get the outputs in less time and memory > efficiently. Memory efficiency is easy, do it line by line off the disk. time efficiency is most likely down to your processing algorithm if we are talking about days. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From amalthomas111 at gmail.com Mon Nov 4 17:56:30 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 22:26:30 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: @Steven: Thanks... Right now I cant access the files. I will send you the output when I can. ------ Please try this little bit of code, replacing the file name with the actual name of your 50GB data file: import os filename = "YOUR FILE NAME HERE" print("File size:", os.stat(filename).st_size) f = open(filename) content = f.read() print("Length of content actually read:", len(content)) print("Current file position:", f.tell()) f.close() and send us the output. -- *AMAL THOMAS* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Nov 4 18:11:52 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Nov 2013 04:11:52 +1100 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: <20131104171152.GG15615@ando> On Mon, Nov 04, 2013 at 11:27:52AM -0500, Joel Goldstick wrote: > If you are new to python why are you so concerned about the speed of > your code. Amal is new to Python but he's not new to biology, he's a 4th year student. With a 50GB file, I expect he is analysing something to do with DNA sequencing, which depending on exactly what he is trying to do could involve O(N) or even O(N**2) algorithms. An O(N) algorithm on a 50GB file, assuming 100,000 steps per second, will take over 5 days to complete. An O(N**2) algorithm, well, it's nearly unthinkable: nearly 800 million years. You *really* don't want O(N**2) algorithms with big data. I would expect that with a big DNA sequencing problem, running time would be measured in days rather than minutes or hours. So yes, this is probably a case where optimizing for speed is not premature. We really don't know enough about his problem to advise him on how to speed it up. If the data file is guaranteed to be nothing but GCTA bases, and newlines, it may be better to read the data file into memory as a bytearray rather than a string. Especially if he needs to modify it in place. But this is getting into some fairly advanced territory, I wouldn't like to predict what will be faster without testing on real data. -- Steven From steve at pearwood.info Mon Nov 4 18:30:11 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Nov 2013 04:30:11 +1100 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: <20131104173011.GH15615@ando> On Mon, Nov 04, 2013 at 04:54:16PM +0000, Alan Gauld wrote: > On 04/11/13 16:34, Amal Thomas wrote: > >@Joel: The code runs for weeks..input file which I have to process in > >very huge(in 50 gbs). So its not a matter of hours.its matter of days > >and weeks.. > > OK, but that's not down to reading the file from disk. > Reading a 50G file will only take a few minutes if you have enough RAM, > which seems to be the case. Not really. There is still some uncertainty (at least in my mind!). For instance, I assume that Amal doesn't have sole access to the server. So there could be another dozen users all trying to read 50GB files at once, in a machine with only 100GB of memory... Once the server starts paging, performance will plummett. > If it's taking days/weeks you must be doing > some incredibly time consuming processing. Well, yes, it's biology :-) > It's probably worth putting some more timing statements into your code > to see where the time is going because it's not the reading from the > disk that's the problem. The first thing I would do is run the code on three smaller sample files: 50MB 100MB 200MB The time taken should approximately double as you double the size of the file: say it takes 2 hours to process the 50MB file, 4 hours for the 100MB file and 8 hours for the 200 MB file, that's linear performance and isn't too bad. But if performance isn't linear, say 2 hours, 4 hours, 16 hours, then you're in trouble and you *desperately* need to reconsider the algorithm being used. Either that, or just accept that this is an inherently slow calculation and it will take a week or two. Amal, another thing you should try is use the Python profiler on your code (again, on a smaller sample file). The profiler will show you where the time is being spent. Unfortunately the profiler may slow your code down, so it is important to use it on manageable sized data. The profiler is explained here: http://docs.python.org/3/library/profile.html If you need any help, don't hesitate to ask. > >trying to optimize my code to get the outputs in less time and memory > >efficiently. > > Memory efficiency is easy, do it line by line off the disk. This assumes that you can process one line at a time, sequentially. I expect that is not the case. -- Steven From amalthomas111 at gmail.com Mon Nov 4 18:41:58 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Mon, 4 Nov 2013 23:11:58 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: <20131104173011.GH15615@ando> References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <20131104173011.GH15615@ando> Message-ID: @Steven: Thank you...My input data is basically AUGC and newlines... I would like to know about bytearray technique. Please suggest me some links or reference.. I will go through the profiler and check whether the code maintains linearity with the input files. > > It's probably worth putting some more timing statements into your code > > to see where the time is going because it's not the reading from the > > disk that's the problem. > > The first thing I would do is run the code on three smaller sample > files: > > 50MB > 100MB > 200MB > > The time taken should approximately double as you double the size of the > file: say it takes 2 hours to process the 50MB file, 4 hours for the > 100MB file and 8 hours for the 200 MB file, that's linear performance > and isn't too bad. > > But if performance isn't linear, say 2 hours, 4 hours, 16 hours, then > you're in trouble and you *desperately* need to reconsider the algorithm > being used. Either that, or just accept that this is an inherently slow > calculation and it will take a week or two. > > Amal, another thing you should try is use the Python profiler on your > code (again, on a smaller sample file). The profiler will show you where > the time is being spent. > > Unfortunately the profiler may slow your code down, so it is important > to use it on manageable sized data. The profiler is explained here: > > http://docs.python.org/3/library/profile.html > > If you need any help, don't hesitate to ask. > > > > >trying to optimize my code to get the outputs in less time and memory > > >efficiently. > > > > Memory efficiency is easy, do it line by line off the disk. > > This assumes that you can process one line at a time, sequentially. I > expect that is not the case. > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- *AMAL THOMAS* -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Nov 4 22:07:54 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Nov 2013 15:07:54 -0600 Subject: [Tutor] Load Entire File into memory In-Reply-To: <20131104155340.GE15615@ando> References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: On Tue, 5 Nov 2013 02:53:41 +1100, Steven D'Aprano wrote: > Dave, do you have a reference for that? As far as I can tell, read() > will read to EOF unless you open the file in non-blocking mode. No. I must be just remembering something from another language. Sorry. -- DaveA From davea at davea.name Mon Nov 4 22:35:01 2013 From: davea at davea.name (Dave Angel) Date: Mon, 4 Nov 2013 21:35:01 +0000 (UTC) Subject: [Tutor] Load Entire File into memory References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: On 4/11/2013 11:26, Amal Thomas wrote: > @Dave: thanks.. By the way I am running my codes on a server with about > 100GB ram but I cant afford my code to use 4-5 times the size of the text > file. Now I am using read() / readlines() , these seems to be more > efficient in memory usage than io.StringIO(f.read()). > Sorry I misspoke about read() on a large file. I was confusing it with something else. However, note that in any environment if you have a large buffer, and you force the system to copy that large buffer, you'll be using (temporarily at least) twice the space. And usually the original can't be freed, for various technical reasons. The real question is how you're going to be addressing the data, and wha.t constraints are on that data. Since you think you need it all in memory, you clearly are planning to access it randomly. Since the data is apparently ASCII characters, and you're running at least 3.3, you won't be paying the penalty if it turns out to be strings. But there may be alternate ways of encoding each line which save space and/or make it faster to use. One big buffer imaging the file is likely to be one of the worst. Are the lines variable length? Do you ever deal randomly with a portion of a line, or only the whole thing? If the line is multiple ASCII characters, are their order significant? how many different symbols can appear in a single line? how many different ones total? (probably excluding the newline). What's the average line length? Each of these questions may lead to exploring different optimzation strategies. But I've done enough speculating. -- DaveA From dyoo at hashcollision.org Mon Nov 4 22:38:46 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 4 Nov 2013 13:38:46 -0800 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <20131104173011.GH15615@ando> Message-ID: On Mon, Nov 4, 2013 at 9:41 AM, Amal Thomas wrote: > @Steven: Thank you...My input data is basically AUGC and newlines... I > would like to know about bytearray technique. Please suggest me some links > or reference.. I will go through the profiler and check whether the code > maintains linearity with the input files. > > Hi Amal, I suspect that what's been missing here throughout this thread is more concrete information about the problem's background. I would strongly suggest we make sure that we understand the problem before making more assumptions. 1. What is the nature of the operation that you are doing on your data? Can you briefly discuss its details? Does it involve random-access, or is it a sequential operation? Are the operations independent regardless of what line you are on, or is there some kind of dependency across lines? Does it involve pattern matching, or...? Are you maintaining some in-memory data structure as you're walking through the file? The reason why we need to know this is because it can affect file access patterns. It may provide a hint as to whether or not you can avoid loading the whole file into memory or not. It may even effect whether or not you can distribute your work among several computers. Here's also why it's important to talk more about what the problem is trying to solve. Your question has been assuming that the dominating factor in your program's runtime is the access of your data, and that loading the entire file into memory will improve performance. But I see no evidence to support that assumption yet. Why should I not believe that the time that's being spent isn't being spent paging in virtual memory, for example, due to something else in your program's operations? In which case, then trying to load the file entirely into memory will be counterproductive. 2. What is the format of your input data? You mention it is AUGC and newlines, but more details would be really helpful. Why is it line-oriented, for example? I mean that as a serious question. Is it significant? Is it a FASTA file? Is it some kind of homebrewed format? Please be as specific as you can be here: you may be duplicating effort that folks who have spent _years_ on sequence-reading libraries have already done for you. Specifically, you might be able to reuse Biopython's libraries for sequence IO. http://biopython.org/wiki/SeqIO By trying to cook up file parsing by yourself, you may be making a mistake. For example, there might be issues in Python 3 due to Unicode encodings: http://docs.python.org/3.0/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit which might contribute to an unexpected increase in the size of a string's memory representation. Hard to say, since it depends on a host of factors. But knowing that, other folks have probably encountered and solved this problem already. Concretely, I'm pretty sure Biopython's SeqIO does the Right Thing in terms of reading files in binary mode and reading the line contents as bytes, as opposed to regular strings, and representing the sequence in some memory-efficient way. At the very least, I know that they think about these kind of problems a lot: http://web.archiveorange.com/archive/v/5dAwXDMfufikePQqtPgx Probably a lot more than us. :P So if it's possible, try to leverage what's already out there. You should almost certainly not be writing your own sequence-reading code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 5 02:10:39 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 5 Nov 2013 01:10:39 +0000 (GMT) Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Forwarding to tutor list. Please use Reply All in responses. From: Amal Thomas >To: Alan Gauld >Sent: Monday, 4 November 2013, 17:26 >Subject: Re: [Tutor] Load Entire File into memory > > > >@Alan: Thanks.. I have checked the both ways( reading line by line by not loading into ram ,? > other loading entire file to ram and then reading line by line)? for files with 2-3GB.? OK, But 2-3G will nearly always live entirely in RAM on a modern computer. > Only change which i have done is in the reading part , rest of the code was kept same.? > There was significant time difference. Please note that I started this thread stating that? > when I am using io.StringIO(f.read()) in code it uses a memory of almost 4-5 times the? > input file size. Now using read() or readlines() it has reduced to 1.5 times...? Yes a raw string is always going to be more efficient in memory use than StringIO. > Also as I have mentioned I cant afford to run my code using 4-5 times memory.? > Total resource available in my server is about 180 GB memory (approx 64 GB RAM + 128GB swap).? OK, There is a huge difference between having 100G of RAM and having 64G+128G swap. swap is basically disk so if you are reading your data into memory and that memory is? bouncing in and out of swap things will slow down by an order of magnitude.? You need to try to optimise to use real RAM and minimise use of swap.? > So before starting to process my 30-50GB input files I am keen to know the best way. Performance tuning is always a tricky topic and needs to be done on a case by case? basis. There are simply too many factors to try to say that method (A) will always be? faster than method (B) It depends on the nature of the data, its source, your target? data structures, your algorithms, your output format and target etc as well as the? physical machines being used... We need a lot?more detail about the task before? we can give any solid advice. And even then you?should verify it before assuming? you are done. Alan G. From dyoo at hashcollision.org Tue Nov 5 02:44:22 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 4 Nov 2013 17:44:22 -0800 Subject: [Tutor] Load Entire File into memory In-Reply-To: <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: > > > > Also as I have mentioned I cant afford to run my code using 4-5 times > memory. > > Total resource available in my server is about 180 GB memory (approx 64 > GB RAM + 128GB swap). > > OK, There is a huge difference between having 100G of RAM and having > 64G+128G swap. > swap is basically disk so if you are reading your data into memory and > that memory is > bouncing in and out of swap things will slow down by an order of > magnitude. > You need to try to optimise to use real RAM and minimise use of swap. > I concur with Alan, and want to state his point more forcefully. If you are hitting swap, you are computationally DOOMED and must do something different. You _must_ avoid swap at all costs here. You may not understand the point, so a little more explanation: touching swap is several orders of magnitude more expensive than anything else you are doing in your program. CPU operations are on the order of nanoseconds. (10^-9) Disk operations are on the order of milliseconds. (10^-3) References: http://en.wikipedia.org/wiki/Instructions_per_second http://en.wikipedia.org/wiki/Hard_disk_drive_performance_characteristics As soon as you start touching your swap space to simulate virtual memory, you've lost the battle. We were trying not to leap to conclusions till we knew more. Now we know more. If your system has much less RAM than can fit your dataset at once, trying to read it all at once on your single machine, into an in-memory buffer, is wrong. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Nov 5 03:02:47 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 4 Nov 2013 18:02:47 -0800 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: > > You _must_ avoid swap at all costs here. You may not understand the > point, so a little more explanation: touching swap is several orders of > magnitude more expensive than anything else you are doing in your program. > > CPU operations are on the order of nanoseconds. (10^-9) > > Disk operations are on the order of milliseconds. (10^-3) > > References: > > http://en.wikipedia.org/wiki/Instructions_per_second > > http://en.wikipedia.org/wiki/Hard_disk_drive_performance_characteristics > > To visualize the sheer scale of the problem, see: http://i.imgur.com/X1Hi1.gif which would normally be funny, except that it's not quite a joke. :P So you want to minimize hard disk usage as much as possible. "Thrashing" is precisely the situation you do not want to have when running a large analysis. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 5 04:28:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Nov 2013 14:28:24 +1100 Subject: [Tutor] Load Entire File into memory In-Reply-To: <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: <20131105032823.GJ15615@ando> I mustly agree with Alan, but a couple of little quibbles: On Tue, Nov 05, 2013 at 01:10:39AM +0000, ALAN GAULD wrote: > >@Alan: Thanks.. I have checked the both ways( reading line by line by not loading into ram ,? > > other loading entire file to ram and then reading line by line)? for files with 2-3GB.? > > OK, But 2-3G will nearly always live entirely in RAM on a modern computer. Speak for yourself. Some of us are still using "modern computers" with 1-2 GB of RAM :-( > > Only change which i have done is in the reading part , rest of the code was kept same.? > > There was significant time difference. Please note that I started this thread stating that? > > when I am using io.StringIO(f.read()) in code it uses a memory of almost 4-5 times the? > > input file size. Now using read() or readlines() it has reduced to 1.5 times...? > > Yes a raw string is always going to be more efficient in memory use than StringIO. It depends what you're doing with it. The beauty of StringIO is that it emulates an in-memory file, so you can modify it in place. String objects are immutable and cannot be modified in place, so if you have to make changes to it, you have to make a copy with the change. For large strings, say, over 100MB, the overhead can get painful. > > Also as I have mentioned I cant afford to run my code using 4-5 times memory.? > > Total resource available in my server is about 180 GB memory (approx 64 GB RAM + 128GB swap).? > > OK, There is a huge difference between having 100G of RAM and having 64G+128G swap. > swap is basically disk so if you are reading your data into memory and that memory is? > bouncing in and out of swap things will slow down by an order of magnitude.? At least. Hard drive technology is more like two or even three orders of magnitude slower than RAM access (100 or 1000 times slower), and including the overhead of the memory manager moving things about, there is no upper limit to how large the penalty can be. If you get away with only 10 times slower, you're lucky. In my experience, 100-1000 times slower is more common (although my experience is on machines with fairly small amounts of RAM in the first place) and sometimes slow enough that even the operating system stops responding. Plan to avoid using swap space :-) > You need to try to optimise to use real RAM and minimise use of swap.? Agreed. -- Steven From steve at pearwood.info Tue Nov 5 08:12:27 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 5 Nov 2013 18:12:27 +1100 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <20131104155340.GE15615@ando> <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: <20131105071226.GK15615@ando> On Mon, Nov 04, 2013 at 06:02:47PM -0800, Danny Yoo wrote: > To visualize the sheer scale of the problem, see: > > http://i.imgur.com/X1Hi1.gif > > which would normally be funny, except that it's not quite a joke. :P Nice visualisation! Was that yours? > So you want to minimize hard disk usage as much as possible. "Thrashing" > is precisely the situation you do not want to have when running a large > analysis. Yes, thrashing is a disaster for performance. But I think that hard drive latency fails to demonstrate just how big a disaster. True, hard drive access time is about 100 times slower than RAM. But that's just a constant scale factor. What really, really kills performance with thrashing is that the memory manager is trying to move chunks of memory around, and the overall "move smaller blocks of memory around to make space for a really big block" algorithm ends up with quadratic (or worse!) performance. -- Steven From stefan_ml at behnel.de Tue Nov 5 08:28:32 2013 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 05 Nov 2013 08:28:32 +0100 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: Message-ID: Amal Thomas, 04.11.2013 14:55: > I have checked the execution time manually as well as I found it through my > code. During execution of my code, at start, I stored my initial time(start > time) to a variable and at the end calculated time taken to run the code = > end time - start time. There was a significance difference in time. You should make sure that there are no caching effects here. Your operating system may have loaded the file into memory (assuming that you have enough of that) after the first read and then served it from there when you ran the second benchmark. So, make sure you measure the time twice for both, preferably running both benchmarks in reverse order the second time. That being said, it's not impossible that f.readlines() is faster than line-wise iteration, because it knows right from the start that it will read the entire file, so it can optimise for it (didn't check if it actually does, this might have changed in Py3.3, for example). Stefan From amalthomas111 at gmail.com Tue Nov 5 14:20:33 2013 From: amalthomas111 at gmail.com (Amal Thomas) Date: Tue, 5 Nov 2013 18:50:33 +0530 Subject: [Tutor] Load Entire File into memory In-Reply-To: <20131104163009.GF15615@ando> References: <20131104163009.GF15615@ando> Message-ID: On Mon, Nov 4, 2013 at 10:00 PM, Steven D'Aprano wrote: > > > import os > filename = "YOUR FILE NAME HERE" > print("File size:", os.stat(filename).st_size) > f = open(filename) > content = f.read() > print("Length of content actually read:", len(content)) > print("Current file position:", f.tell()) > f.close() > > > and send us the output. This is the output: File size: 50297501884 Length of content actually read: 50297501884 Current file position: 50297501884 This Code used 61.4 GB RAM and 59.6 GB swap (I had ensured that no other important process were running in my server before running this :D) -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Nov 5 14:22:11 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 5 Nov 2013 13:22:11 +0000 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <20131104173011.GH15615@ando> Message-ID: On 4 November 2013 17:41, Amal Thomas wrote: > @Steven: Thank you...My input data is basically AUGC and newlines... I would > like to know about bytearray technique. Please suggest me some links or > reference.. I will go through the profiler and check whether the code > maintains linearity with the input files. Amal can you just give *some* explanation of what you're doing? I can think of many possible ways to optimise it or to use less memory but it depends on what you're actually doing and you really haven't given enough information. If you show a short data sample and a short piece of code that is similar to what you are doing then people here would be in a better position to help. Please read this: http://sscce.org/ You have repeatedly made claims such as "X is faster than Y" but you've also said that you are a beginner to Python. Be aware that testing speeds on a small file is completely different from testing on a large file or that testing speeds on a file that is already cached by the OS is completely different from testing on one that is not. There are many things that can make the difference. Oscar From oscar.j.benjamin at gmail.com Tue Nov 5 14:24:17 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 5 Nov 2013 13:24:17 +0000 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <20131104163009.GF15615@ando> Message-ID: On 5 November 2013 13:20, Amal Thomas wrote: > On Mon, Nov 4, 2013 at 10:00 PM, Steven D'Aprano > wrote: >> > >> >> import os >> filename = "YOUR FILE NAME HERE" >> print("File size:", os.stat(filename).st_size) >> f = open(filename) >> content = f.read() >> print("Length of content actually read:", len(content)) >> print("Current file position:", f.tell()) >> f.close() >> >> >> and send us the output. > > > This is the output: > File size: 50297501884 > Length of content actually read: 50297501884 > Current file position: 50297501884 > This Code used 61.4 GB RAM and 59.6 GB swap (I had ensured that no other > important process were running in my server before running this :D) If you are using the swap then this will almost certainly be the biggest slowdown in your program (and any other program on the same machine). If there is some way to reorganise your code so that you don't need to load everything into memory then (if you do it right) you should be able to make it *much* faster. Oscar From alan.gauld at btinternet.com Tue Nov 5 17:12:51 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 05 Nov 2013 16:12:51 +0000 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: On 05/11/13 02:02, Danny Yoo wrote: > To visualize the sheer scale of the problem, see: > > http://i.imgur.com/X1Hi1.gif > > which would normally be funny, except that it's not quite a joke. :P I think I'm missing something. All I see in Firefox is a vertical red bar. And in Chrome I don't even get that, just a blank screen... ??? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From mikablom at yahoo.com Mon Nov 4 23:52:52 2013 From: mikablom at yahoo.com (Blomquist Mikael) Date: Mon, 4 Nov 2013 22:52:52 +0000 (GMT) Subject: [Tutor] output generates a sentence made up of words Message-ID: <1383605572.99850.YahooMailNeo@web172402.mail.ir2.yahoo.com> Hi, here is the new code ... just leave a space behind every word. import random def wordList(): adj1 = ["Big ", "Small ", "Early ", "Late ", "Red ", "Tall ", "Short "] subj = ["politician ", "man ", "woman ", "whale ", "company ", "child ", "soldier "] obj = ["budget ", "money ", "box ", "gift ", "gun ", "tank ", "drone "] adj2 = ["hot ", "crazy ", "stupid ", "fast ", "worthless ", "awesome ", "dirty "] verb = ["spends ", "shoots ", "evades ", "pursues ", "subverts ", "passes ", "flirts "] y = adj1[generate()], subj[generate()] + obj[generate()] + adj2[generate()] + verb[generate()] return y def generate(): random0_6 = random.randint(0, 6) return random0_6 def main(): print (wordList(), ".", sep="") main() I?ve tested it. Have fun ... mika Byron Ruffin schrieb am 10:00 Sonntag, 3.November 2013: The output generates a sentence made up of words chosen randomly from lists. I am having trouble getting a space between each of the words. Should I be thinking about .split? Here is the code (ignore indent errors as it was copied and pasted) Thank you: import random def wordList(): adj1 = ["Big", "Small", "Early", "Late", "Red", "Tall", "Short"] subj = ["politician", "man", "woman", "whale", "company", "child", "soldier"] obj = ["budget", "money", "box", "gift", "gun", "tank", "drone"] adj2 = ["hot", "crazy", "stupid", "fast", "worthless", "awesome", "dirty"] verb = ["spends", "shoots", "evades", "pursues", "subverts", "passes", "flirts"] y = adj1[generate()], subj[generate()] + obj[generate()] + adj2[generate()] + verb[generate()] return y def generate(): random0_6 = random.randint(0, 6) return random0_6 def main(): print (wordList(), ".", sep="") main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From ml at fam-goebel.de Mon Nov 4 11:34:01 2013 From: ml at fam-goebel.de (Ulrich Goebel) Date: Mon, 04 Nov 2013 11:34:01 +0100 Subject: [Tutor] String representation of NULL (non type) values Message-ID: <52777819.8040105@fam-goebel.de> Hallo, from a SQLite database I get a value by SELECT s from... which normaly is a string, but can be the NULL value, wich means it is not defined. To put the value into a form (made by QT) I need a string representation. str(s) gives either the string itself (which is good) or "None" (which is not so good) in the case of NULL. Instead of "None" I would prefer an empty string "". How to get that? Possibly there is a build in function smart(s1, s2, s3,...) which returns the first s which is a useable string, or even "" if there isn't any string in the arguments? Thanks for help Ulrich -- Ulrich Goebel Paracelsusstr. 120, 53177 Bonn From joel.goldstick at gmail.com Tue Nov 5 17:21:49 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 5 Nov 2013 11:21:49 -0500 Subject: [Tutor] String representation of NULL (non type) values In-Reply-To: <52777819.8040105@fam-goebel.de> References: <52777819.8040105@fam-goebel.de> Message-ID: On Mon, Nov 4, 2013 at 5:34 AM, Ulrich Goebel wrote: > Hallo, > > from a SQLite database I get a value by SELECT s from... which normaly is a > string, but can be the NULL value, wich means it is not defined. To put the > value into a form (made by QT) I need a string representation. > > str(s) gives either the string itself (which is good) or "None" (which is > not so good) in the case of NULL. Instead of "None" I would prefer an empty > string "". How to get that? > > Possibly there is a build in function smart(s1, s2, s3,...) which returns > the first s which is a useable string, or even "" if there isn't any string > in the arguments? > > Thanks for help > Ulrich > > > -- > Ulrich Goebel > Paracelsusstr. 120, 53177 Bonn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor In python you can do this: >>> a = None >>> b = a or "" >>> b '' >>> a = "text here" >>> b = a or "" >>> b 'text here' >>> If a is None (false in python), it will check the value after or and return that. If a is a string (hence true in python) it will return the string -- Joel Goldstick http://joelgoldstick.com From wrw at mac.com Tue Nov 5 17:25:10 2013 From: wrw at mac.com (William Ray Wing) Date: Tue, 05 Nov 2013 11:25:10 -0500 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: <72F8752E-B7BF-4E49-B03F-73E20813A5C0@mac.com> On Nov 5, 2013, at 11:12 AM, Alan Gauld wrote: > On 05/11/13 02:02, Danny Yoo wrote: > >> To visualize the sheer scale of the problem, see: >> >> http://i.imgur.com/X1Hi1.gif >> >> which would normally be funny, except that it's not quite a joke. :P > > I think I'm missing something. All I see in Firefox is > a vertical red bar. And in Chrome I don't even get that, > just a blank screen... > > ??? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos It took me a while? If you put your cursor up in the extreme upper left hand corner of that red bar, you get a + sign that allows you to expand the image. In the expansion you will see text that explains the graphical scales in question. A pixel (L1 cache), a short bar of pixels (L2 cache), a longer bar (RAM) and finally that huge block of pixels that represent disk latency. -Bill From steve at pearwood.info Tue Nov 5 17:30:01 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 6 Nov 2013 03:30:01 +1100 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <20131104155340.GE15615@ando> <1383613839.67266.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: <20131105163000.GL15615@ando> On Tue, Nov 05, 2013 at 04:12:51PM +0000, Alan Gauld wrote: > On 05/11/13 02:02, Danny Yoo wrote: > > >To visualize the sheer scale of the problem, see: > > > >http://i.imgur.com/X1Hi1.gif > > > >which would normally be funny, except that it's not quite a joke. :P > > I think I'm missing something. All I see in Firefox is > a vertical red bar. And in Chrome I don't even get that, > just a blank screen... Can't speak for Chrome, sounds like a bug. But Firefox defaults to scaling pictures to fit within the window. If you mouse over the image, you'll get a magnifying glass pointer. Click on the image, and it will redisplay at full size. Scroll to the very top, and you will find a little bit of text, a single red pixel representing the latency of cache memory, a dozen or so red pixels representing the latency of RAM, and a monsterously huge block of thousands and thousands and thousands of red pixels representing the latency of hard drives. Feel free to scroll and count the pixels :-) -- Steven From steve at pearwood.info Tue Nov 5 17:37:52 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 6 Nov 2013 03:37:52 +1100 Subject: [Tutor] String representation of NULL (non type) values In-Reply-To: <52777819.8040105@fam-goebel.de> References: <52777819.8040105@fam-goebel.de> Message-ID: <20131105163752.GM15615@ando> On Mon, Nov 04, 2013 at 11:34:01AM +0100, Ulrich Goebel wrote: > Hallo, > > from a SQLite database I get a value by SELECT s from... which normaly > is a string, but can be the NULL value, wich means it is not defined. To > put the value into a form (made by QT) I need a string representation. > > str(s) gives either the string itself (which is good) or "None" (which > is not so good) in the case of NULL. Instead of "None" I would prefer an > empty string "". How to get that? if s is None: value = '' else: value = str(s) But since s is already a string (except for the None case), there's no need to call str() again. If you plan of doing this a lot, turn it into a function: def convert(s): if s is None: s = '' return s then use it like this: s = convert(s) > Possibly there is a build in function smart(s1, s2, s3,...) which > returns the first s which is a useable string, or even "" if there isn't > any string in the arguments? No, but it's trivial to make one yourself: def smart(*args): for arg in args: if arg is not None: return arg return '' -- Steven From __peter__ at web.de Tue Nov 5 17:37:56 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 05 Nov 2013 17:37:56 +0100 Subject: [Tutor] String representation of NULL (non type) values References: <52777819.8040105@fam-goebel.de> Message-ID: Ulrich Goebel wrote: > Hallo, > > from a SQLite database I get a value by SELECT s from... which normaly > is a string, but can be the NULL value, wich means it is not defined. To > put the value into a form (made by QT) I need a string representation. > > str(s) gives either the string itself (which is good) or "None" (which > is not so good) in the case of NULL. Instead of "None" I would prefer an > empty string "". How to get that? > > Possibly there is a build in function smart(s1, s2, s3,...) which > returns the first s which is a useable string, or even "" if there isn't > any string in the arguments? coalesce(arg1, arg2, arg3, ...) returns the first non-NULL argument; you'll get the empty string by providing it as the last argument: >>> db = sqlite3.connect(":memory:") >>> cs = db.cursor() >>> next(cs.execute("select coalesce('could be a field', '');")) (u'could be a field',) >>> next(cs.execute("select coalesce(NULL, '');")) (u'',) See http://sqlite.org/lang_corefunc.html From eryksun at gmail.com Tue Nov 5 19:37:05 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 5 Nov 2013 13:37:05 -0500 Subject: [Tutor] Load Entire File into memory In-Reply-To: References: <33FF1107-7750-4B4E-85AB-6630BACE07A0@mac.com> <20131104155340.GE15615@ando> Message-ID: On Mon, Nov 4, 2013 at 11:26 AM, Amal Thomas wrote: > @Dave: thanks.. By the way I am running my codes on a server with about > 100GB ram but I cant afford my code to use 4-5 times the size of the text > file. Now I am using read() / readlines() , these seems to be more > efficient in memory usage than io.StringIO(f.read()). f.read() creates a string to initialize a StringIO object. You could instead initialize a BytesIO object with a mapped file; that should cut the peak RSS down by half. If you need decoded text, add a TextIOWrapper. import io import mmap with open('output.txt') as f: with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mf: content = io.TextIOWrapper(io.BytesIO(mf)) for line in content: 'process line' However, before you do something extreme (like say... loading a 50 GiB file into RAM), try tweaking the TextIOWrapper object's readline() by increasing _CHUNK_SIZE. This can be up to 2**63-1 in a 64-bit process. with open('output.txt') as content: content._CHUNK_SIZE = 65536 for line in content: 'process line' Check content.buffer.tell() to confirm that the file pointer is increasing in steps of the given chunk size. Built-in open() also lets you set the "buffering" size for the BufferedReader, content.buffer. However, in this case I don't think you need to worry about it. content.readline() calls content.buffer.read1() to read directly from the FileIO object, content.buffer.raw. From dyoo at hashcollision.org Tue Nov 5 20:02:53 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 5 Nov 2013 11:02:53 -0800 Subject: [Tutor] String representation of NULL (non type) values In-Reply-To: <52777819.8040105@fam-goebel.de> References: <52777819.8040105@fam-goebel.de> Message-ID: > > > from a SQLite database I get a value by SELECT s from... which normaly is > a string, but can be the NULL value, wich means it is not defined. To put > the value into a form (made by QT) I need a string representation. > > str(s) gives either the string itself (which is good) or "None" (which is > not so good) in the case of NULL. Instead of "None" I would prefer an empty > string "". How to get that? > > Possibly there is a build in function smart(s1, s2, s3,...) which returns > the first s which is a useable string, or even "" if there isn't any string > in the arguments? > > Be extra careful if you're constructing SQL statements from user input. You have probably heard of the term "SQL Injection" or "Bobby Tables", both of which are pretty much the same thing: your user may, intentionally or not, input values that can be interpreted as SQL commands rather than as literal data. If you know up front what what possible values you're allowing for your column selection, I'd recommend explicitly enumerating them in a function, and then guarantee that your code will deal with just those columns. E.g. ################################################ SAFE_COLUMNS = ['name', 'age', 'phone', 'favorite_pokemon'] # # ... later in the code # if s in SAFE_COLUMNS: # ... we're good to go. else: raise ValueError('Unknown column', s) ################################################ That is, prevent insertion of arbitrary, user-defined values in your SQL query string unless you really have no other choice. Also see: http://stackoverflow.com/questions/6514274/how-do-you-escape-strings-for-sqlite-table-column-names-in-python Best of wishes! -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Nov 5 20:40:12 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 5 Nov 2013 19:40:12 +0000 Subject: [Tutor] String representation of NULL (non type) values In-Reply-To: References: <52777819.8040105@fam-goebel.de> Message-ID: Hi, On 5 November 2013 19:02, Danny Yoo wrote: > Be extra careful if you're constructing SQL statements from user input. >> You have probably heard of the term "SQL Injection" or "Bobby Tables", >> both of which are pretty much the same thing: your user may, intentionally >> or not, input values that can be interpreted as SQL commands rather than as >> literal data. > > For those not familiar: http://xkcd.com/327/ :) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Nov 5 20:48:47 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 5 Nov 2013 14:48:47 -0500 Subject: [Tutor] String representation of NULL (non type) values In-Reply-To: References: <52777819.8040105@fam-goebel.de> Message-ID: On Tue, Nov 5, 2013 at 2:40 PM, Walter Prins wrote: > Hi, > > > On 5 November 2013 19:02, Danny Yoo wrote: >>> >>> Be extra careful if you're constructing SQL statements from user input. >>> You have probably heard of the term "SQL Injection" or "Bobby Tables", both >>> of which are pretty much the same thing: your user may, intentionally or >>> not, input values that can be interpreted as SQL commands rather than as >>> literal data. > > > For those not familiar: > http://xkcd.com/327/ > > :) > > Walter > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > thanks for that link. I'd seen it before. So succinct. -- Joel Goldstick http://joelgoldstick.com From jmartiee at gmail.com Wed Nov 6 00:55:05 2013 From: jmartiee at gmail.com (Johan Martinez) Date: Tue, 5 Nov 2013 15:55:05 -0800 Subject: [Tutor] Creating class / OOP structure Message-ID: I need help in modifying my program. Right now it looks as follows: class Filedict(): def __init__(self, fname): self.fname =fname def parse(self): with open(self.fname, 'r') as f: .... # some file search and parsing logic return parsed_file def process(self, parsed_object): for k in parsed_obj.keys(): .... return processed_file I instantiate Filedict and use it as follows: f = Filedict('sales.txt') parsed_f = f.parse() processed_f = f.process(parsed_f) So I need to pass parsed_f again to the process method. I would like to use process method directly on initialized object. For example: f = Filedict('sales.txt') f.process() Can someone help me in improving my code? Should I store parsed_file as an object attribute as follows? class Filedict(): def __init__(self, fname): self.fname =fname self.parsed_file = self.parse() Any help? -Jm -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Nov 6 01:55:06 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Nov 2013 00:55:06 +0000 Subject: [Tutor] Creating class / OOP structure In-Reply-To: References: Message-ID: On 05/11/13 23:55, Johan Martinez wrote: > > I need help in modifying my program. Right now it looks as follows: > > > class Filedict(): > def __init__(self, fname): > self.fname =fname > > def parse(self): > with open(self.fname, 'r') as f: > .... > # some file search and parsing logic > return parsed_file change this to self.parsed = parsed_file > > def process(self, parsed_object): remove the parsed_object parameter > for k in parsed_obj.keys(): replace with for k in self.parsed.keys(): or more simply for k in self.parsed: > return processed_file And maybe make this self.processed = processed_file > f = Filedict('sales.txt') > parsed_f = f.parse() > processed_f = f.process(parsed_f) > > So I need to pass parsed_f again to the process method. I would like to > use process method directly on initialized object. For example: > > f = Filedict('sales.txt') > f.process() my suggestions would lead to f = Filedict('sales.txt') f.parse() f.process() > Should I store parsed_file as an object attribute as follows? yes, but you can do it inside parse() which ensures the attribute is kept updated ifg you call parse a second time and, for any reason, get a different result. > class Filedict(): > def __init__(self, fname): > self.fname =fname > self.parsed_file = self.parse() That then becomes class Filedict(): def __init__(self, fname): self.fname =fname self.parse() And you can remove the parse() line from my 3 liner above... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Wed Nov 6 03:19:33 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 6 Nov 2013 13:19:33 +1100 Subject: [Tutor] Creating class / OOP structure In-Reply-To: References: Message-ID: <20131106021932.GN15615@ando> On Tue, Nov 05, 2013 at 03:55:05PM -0800, Johan Martinez wrote: > I need help in modifying my program. Right now it looks as follows: [snip code] > Can someone help me in improving my code? Yes! The first thing to do is get rid of the unnecessary class. This is not Java where you have to write classes for everything. From the sample code that you show below, using OOP here accomplishes nothing except making the code more complicated and less efficient. Please don't think I am *against* OOP. But it is a tool, nothing more, and you should always use the right tool for the job. And in this case, I think the right tool is to create two functions: def parse(filename): with open(filename, 'r') as f: ... return parsed_file def process(parsed_file): for k in parsed_file: # Iteration automatically uses keys. ... return processed_file And then simply call them like this: processed = process(parse('sales.txt')) Why is this better? In the code you show, you don't use the object-oriented structure, so why waste time building an object-ordiented structure? Similarly, after you have read the file once, the class solution holds onto the contents forever. But you don't need it forever, once you have parsed the contents they are no longer needed. So why hold on to them longer than necessary? Classes should only be used when you need to encapsulate state plus behaviour, in other words, when they represent a *thing*. Classes should be nouns: BankAccount, User, DecimalNumber all make good classes. Your class *needs* only behaviour -- the class doesn't need to store either self.fname nor self.parsed_file, since they are both only used once. In effect, they are temporary variables that are given names and made long-living: # no need for this filename = "sales.txt" parsed_file = parse(filename) processed = process(parsed_file) # now go on to use processed but not filename or parsed_file ... Since those two variables are only used once, there is no need to keep them as named variables. Get rid of them! processed = process(parse('sales.txt')) Now, obviously there are parts of the code you haven't shown us. Perhaps you do have good reason for storing parsed_file and filename for later use. If so, then my objection to using a class will be reduced, or even eliminated. But even then, there is one last problem with your class: it has a dangerously misleading name, which hints that it is not a well-designed class. "Filedict" is neither a file nor a dict -- it doesn't inherit from file, or behave like a file; it doesn't inherit from dict, or behave like a dict. It is, in fact, *not* a file/dict at all. What you really have is something with a nasty compound name: FileParserAndDictProcessor When your classes have nasty compound names like this, it is a very strong clue that the class doesn't actually represent a thing and probably shouldn't exist. Don't use classes just as a wrapper around a few functions and unrelated variables. (What does the file name have to do with the process() method? Why are they stored together?) For a very entertaining -- although quite long -- look at this issue, have a read of this: http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html You don't need to be a Java developer to get value from it. > Should I store parsed_file as an object attribute as follows? > > class Filedict(): > def __init__(self, fname): > self.fname =fname > self.parsed_file = self.parse() Should you? No. Can you? Yes. But follow the logic -- you could continue the process of pushing more code into the __init__ method: class Filedict(): # Terrible name... def __init__(self, fname): self.fname =fname self.parsed_file = self.parse() self.processed = self.process() f = Filedict("sales.txt") processed = f.processed But now the instance f has no reason to exist, so dump it: processed = Filedict("sales.txt").processed which basically means you are using __init__ just as a wrapper to hide away a couple of function calls. -- Steven From antongilb at gmail.com Wed Nov 6 04:10:20 2013 From: antongilb at gmail.com (Anton Gilb) Date: Tue, 5 Nov 2013 21:10:20 -0600 Subject: [Tutor] Can someone please help me with this? Message-ID: Hi everyone, I'm a novice student struggling through my first python course. Currently stuck on how to tackle this exercise. Any input would be appreciated, and I know you guys can not just give me the answer, I'm just looking for help to understand how to work through this. This is the exercise: It is often adventageous to be able to transfere data between multiple lists while rearranging their order. For instance, say that list1 = [1,2,3,4,5,6,7,8,9] and you wish to add the numbers in the index range 4:7 of list1 to another list, list2, in reverse order while simulataneously removing them from list1. If list2 = [100,200], the result will be list2 = [100,200,7,6,5]. Write a function named transform that takes as arguments list1, list2, r1, and r2, that removes items from list1 in the slice r1:r2, appends them onto list2 in reverse order, and returns the resulting list. For example, in this case, the function call will be transform(list1, list2, 4,7). This is what I've come up with so far, it looks like garbage I know. list1 = [1,2,3,4,5,6,7,8,9] list2 = [100,200] final_list2 = [] def transform(list1, list2, r1, r2): temp_list = list1[4:7:-1] final_list2 = list2.append(temp_list) print(final_list2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Nov 6 09:58:59 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 06 Nov 2013 08:58:59 +0000 Subject: [Tutor] Creating class / OOP structure In-Reply-To: <20131106021932.GN15615@ando> References: <20131106021932.GN15615@ando> Message-ID: On 06/11/2013 02:19, Steven D'Aprano wrote: > On Tue, Nov 05, 2013 at 03:55:05PM -0800, Johan Martinez wrote: >> I need help in modifying my program. Right now it looks as follows: > [snip code] >> Can someone help me in improving my code? > > Yes! The first thing to do is get rid of the unnecessary class. This is > not Java where you have to write classes for everything. From the sample > code that you show below, using OOP here accomplishes nothing except > making the code more complicated and less efficient. > Big +1 from me :) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From alan.gauld at btinternet.com Wed Nov 6 10:23:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Nov 2013 09:23:53 +0000 Subject: [Tutor] Creating class / OOP structure In-Reply-To: <20131106021932.GN15615@ando> References: <20131106021932.GN15615@ando> Message-ID: On 06/11/13 02:19, Steven D'Aprano wrote: > Yes! The first thing to do is get rid of the unnecessary class. This is > not Java where you have to write classes for everything. From the sample > code that you show below, using OOP here accomplishes nothing except > making the code more complicated and less efficient. If that's true I agree, but I assumed that since he called it filedict he was intending to make it into a filedict and only showed us the methods that he was asking about (which is what we encourage people to do...) > class *needs* only behaviour -- the class doesn't need to store either > self.fname nor self.parsed_file, since they are both only used once. Its hard to say that if the OP does intend to implement a filedict. If the dict is being written back to a file at some point it may need to store the original name - or to mangle it and store the new target name... > "Filedict" is neither a file nor a dict -- it doesn't inherit from file, > or behave like a file; it doesn't inherit from dict, or behave like a > dict. It is, in fact, *not* a file/dict at all. Again, I assumed (possibly wrongly!) that tyhe intent ws to produce a filedict (which sounds like it might be based on a shelve?). > What you really have is something with a nasty compound name: > > FileParserAndDictProcessor But if you are right and I'm wrong about the intent then I agree! > When your classes have nasty compound names like this, it is a very > strong clue that the class doesn't actually represent a thing and > probably shouldn't exist.... > For a very entertaining -- although quite long -- look at this issue, > have a read of this: > > http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html I agreed with about half of this, but strongly disagreed with some of it too. Much of it is Java focused and so I understand his frustrations, but his comments are a bit to generalised IMHO. In particular his list of verbs before nouns is completely misguided since he uses the imperative case which in English has an implied subject - the person carrying out the command. This his examples should all be prefixed by a noun to become, for example: YOU get the garbage bag from under the sink YOU carry it out to the garage YOU dump it in the garbage can And the equivalent OOP constructs become Person.get(item, location) Person,put(item, location) Person.dump(item,receptacle) In fact in most English sentences the noun does come before the verb. is the most common structure. The bit of his rant thats valid, and often seen in Java, is that the verbs get applied to the object of the sentence rather than the subject. Thus we see Garbage.get(location) Which I agree makes no sense. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From wprins at gmail.com Wed Nov 6 10:26:48 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 6 Nov 2013 09:26:48 +0000 Subject: [Tutor] Creating class / OOP structure In-Reply-To: References: <20131106021932.GN15615@ando> Message-ID: Hi, On 6 November 2013 08:58, Mark Lawrence wrote: > On 06/11/2013 02:19, Steven D'Aprano wrote: > >> On Tue, Nov 05, 2013 at 03:55:05PM -0800, Johan Martinez wrote: >> >>> I need help in modifying my program. Right now it looks as follows: >>> >> [snip code] >> >>> Can someone help me in improving my code? >>> >> >> Yes! The first thing to do is get rid of the unnecessary class. This is >> not Java where you have to write classes for everything. From the sample >> code that you show below, using OOP here accomplishes nothing except >> making the code more complicated and less efficient. >> >> > Big +1 from me :) To belabor the point further, watch this video by Jack Diederich from Pycon 2012 entitled "Stop writing classes": http://www.youtube.com/watch?v=o9pEzgHorH0 (Don't get me or this video wrong -- classes have their uses but too often developers try to fit stuff into class structures when the code/problem really isn't asking for/suits it.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Nov 6 10:52:32 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 6 Nov 2013 09:52:32 +0000 Subject: [Tutor] Can someone please help me with this? In-Reply-To: References: Message-ID: On 6 November 2013 03:10, Anton Gilb wrote: > Hi everyone, I'm a novice student struggling through my first python course. > Currently stuck on how to tackle this exercise. Any input would be > appreciated, and I know you guys can not just give me the answer, I'm just > looking for help to understand how to work through this. That's fine. > This is the exercise: > > It is often adventageous to be able to transfere data between multiple lists > while rearranging their order. For instance, say that list1 = > [1,2,3,4,5,6,7,8,9] and you wish to add the numbers in the index range 4:7 > of list1 to another list, list2, in reverse order while simulataneously > removing them from list1. If list2 = [100,200], the result will be list2 = > [100,200,7,6,5]. Write a function named transform that takes as arguments > list1, list2, r1, and r2, that removes items from list1 in the slice r1:r2, > appends them onto list2 in reverse order, and returns the resulting list. > For example, in this case, the function call will be transform(list1, list2, > 4,7). > > This is what I've come up with so far, it looks like garbage I know. > > list1 = [1,2,3,4,5,6,7,8,9] > list2 = [100,200] > final_list2 = [] > > def transform(list1, list2, r1, r2): > temp_list = list1[4:7:-1] > final_list2 = list2.append(temp_list) > > > print(final_list2) Which part don't you get? You should say what the code does, why it's not what you want it to do and whether or not you understand the behaviour you see. I'll give one suggestion which is that to concatenate one list onto the end of another you would use the .extend() method rather than the .append() method. Oscar From eryksun at gmail.com Wed Nov 6 16:15:38 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 6 Nov 2013 10:15:38 -0500 Subject: [Tutor] Can someone please help me with this? In-Reply-To: References: Message-ID: On Tue, Nov 5, 2013 at 10:10 PM, Anton Gilb wrote: > Write a function named transform that takes as arguments > list1, list2, r1, and r2, that removes items from list1 in the slice r1:r2, > appends them onto list2 in reverse order, and returns the resulting list. > For example, in this case, the function call will be transform(list1, list2, > 4,7). > > list1 = [1,2,3,4,5,6,7,8,9] > list2 = [100,200] For the slice 4 to 7, the reversed slice is 6 down to 3. list2 += list1[6:3:-1] >>> list2 [100, 200, 7, 6, 5] Then del the slice from list1: del list1[4:7] >>> list1 [1, 2, 3, 4, 8, 9] Alternatively you could use pop() and append() in a loop over the reversed range, though it's not as efficient: for i in xrange(6, 3, -1): list2.append(list1.pop(i)) From alan.gauld at btinternet.com Wed Nov 6 18:19:37 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Nov 2013 17:19:37 +0000 Subject: [Tutor] Can someone please help me with this? In-Reply-To: References: Message-ID: On 06/11/13 03:10, Anton Gilb wrote: > This is what I've come up with so far, it looks like garbage I know. On the contrary its not too far away. But we'd rather see a garbage first attempt than no attempt at all, at least we then know where the problems lie! > list1 = [1,2,3,4,5,6,7,8,9] > list2 = [100,200] > final_list2 = [] You don't need the final_list here > def transform(list1, list2, r1, r2): > temp_list = list1[4:7:-1] > final_list2 = list2.append(temp_list) But you should *return* this value here. This is creating a new local variable inside the function, it's not using the global value you defined above. Also since append() (and extend() for that matter) do not return a list value final_list2 will always equal None. You are modifying list2 directly. Others have commented on the other code inside the function. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jmartiee at gmail.com Wed Nov 6 19:27:20 2013 From: jmartiee at gmail.com (Johan Martinez) Date: Wed, 6 Nov 2013 10:27:20 -0800 Subject: [Tutor] Creating class / OOP structure In-Reply-To: <20131106021932.GN15615@ando> References: <20131106021932.GN15615@ando> Message-ID: On Tue, Nov 5, 2013 at 6:19 PM, Steven D'Aprano wrote: > On Tue, Nov 05, 2013 at 03:55:05PM -0800, Johan Martinez wrote: > > I need help in modifying my program. Right now it looks as follows: > [snip code] > > Can someone help me in improving my code? > > Yes! The first thing to do is get rid of the unnecessary class. This is > not Java where you have to write classes for everything. From the sample > code that you show below, using OOP here accomplishes nothing except > making the code more complicated and less efficient. > > Please don't think I am *against* OOP. But it is a tool, nothing more, > and you should always use the right tool for the job. And in this case, > I think the right tool is to create two functions: > > def parse(filename): > with open(filename, 'r') as f: > ... > return parsed_file > > def process(parsed_file): > for k in parsed_file: # Iteration automatically uses keys. > ... > return processed_file > > > And then simply call them like this: > > processed = process(parse('sales.txt')) > > Why is this better? > > In the code you show, you don't use the object-oriented structure, so > why waste time building an object-ordiented structure? Similarly, after > you have read the file once, the class solution holds onto the contents > forever. But you don't need it forever, once you have parsed the > contents they are no longer needed. So why hold on to them longer than > necessary? > > Classes should only be used when you need to encapsulate state plus > behaviour, in other words, when they represent a *thing*. Classes should > be nouns: BankAccount, User, DecimalNumber all make good classes. Your > class *needs* only behaviour -- the class doesn't need to store either > self.fname nor self.parsed_file, since they are both only used once. In > effect, they are temporary variables that are given names and made > long-living: > > # no need for this > filename = "sales.txt" > parsed_file = parse(filename) > processed = process(parsed_file) > > # now go on to use processed but not filename or parsed_file > ... > > Since those two variables are only used once, there is no need to keep > them as named variables. Get rid of them! > > processed = process(parse('sales.txt')) > > > Now, obviously there are parts of the code you haven't shown us. Perhaps > you do have good reason for storing parsed_file and filename for later > use. If so, then my objection to using a class will be reduced, or even > eliminated. > > But even then, there is one last problem with your class: it has a > dangerously misleading name, which hints that it is not a well-designed > class. > > "Filedict" is neither a file nor a dict -- it doesn't inherit from file, > or behave like a file; it doesn't inherit from dict, or behave like a > dict. It is, in fact, *not* a file/dict at all. What you really have is > something with a nasty compound name: > > FileParserAndDictProcessor > > > When your classes have nasty compound names like this, it is a very > strong clue that the class doesn't actually represent a thing and > probably shouldn't exist. Don't use classes just as a wrapper around a > few functions and unrelated variables. (What does the file name have to > do with the process() method? Why are they stored together?) > > For a very entertaining -- although quite long -- look at this issue, > have a read of this: > > > http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html > > > You don't need to be a Java developer to get value from it. > > > > Should I store parsed_file as an object attribute as follows? > > > > class Filedict(): > > def __init__(self, fname): > > self.fname =fname > > self.parsed_file = self.parse() > > Should you? No. Can you? Yes. But follow the logic -- you could continue > the process of pushing more code into the __init__ method: > > class Filedict(): # Terrible name... > def __init__(self, fname): > self.fname =fname > self.parsed_file = self.parse() > self.processed = self.process() > > f = Filedict("sales.txt") > processed = f.processed > > But now the instance f has no reason to exist, so dump it: > > processed = Filedict("sales.txt").processed > > which basically means you are using __init__ just as a wrapper to hide > away a couple of function calls. > > > > -- > Steven Thanks for the detailed reply Steven. I am trying to learn class/OOP structure and selected file parsing and processing as a use case. I wanted to implement something as follows: # Create Filedict object - which will return parsed file in dict format # Where, dict keys are entries in second column and # dict values are matching lines and number of matching lines f = Filedict('sales.txt') The dict representation contains everything I want to know from that file, however, it's still in raw format. So I need to process it further. f.process() The process method splits gives dictionary object in four distinct dict objects based on some conditions. These four dicts can then be dumped in JSON format or we can perform more select/filter actions on them. I was doing it using simple functions, but I added class/OOP for learning. I thought parsed file object should be created when Filedict was initialized and then 'process' or other methods can be called on the object directly. I am going through suggested resources and hopefully come up with a better code structure. -jM -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Thu Nov 7 03:56:59 2013 From: akleider at sonic.net (Alex Kleider) Date: Wed, 06 Nov 2013 18:56:59 -0800 Subject: [Tutor] =?utf-8?q?Can_someone_please_help_me_with_this=3F?= In-Reply-To: References: Message-ID: <91bd1664a6fbde88c19265c38b2753d9@sonic.net> On 2013-11-06 01:52, Oscar Benjamin wrote: > > I'll give one suggestion which is that to concatenate one list onto > the end of another you would use the .extend() method rather than the > .append() method. What would be the advantage/disadvantage of what you suggest vs using the plus (+) operand as in l = l1 + l2 ?? From davea at davea.name Thu Nov 7 05:21:23 2013 From: davea at davea.name (Dave Angel) Date: Wed, 06 Nov 2013 22:21:23 -0600 Subject: [Tutor] Can someone please help me with this? References: <91bd1664a6fbde88c19265c38b2753d9@sonic.net> Message-ID: Alex Kleider wrote: > On 2013-11-06 01:52, Oscar Benjamin wrote: > > > > I'll give one suggestion which is that to concatenate one list onto > > the end of another you would use the .extend() method rather than the > > .append() method. > What would be the advantage/disadvantage of what you suggest vs using > the plus (+) operand as in > l = l1 + l2 > ?? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor The plus operator doesn't append to the list; it makes a new one. Doesn't meet spec. -- Android Usenet Reader http://android.newsgroupstats.hk From akleider at sonic.net Thu Nov 7 06:42:01 2013 From: akleider at sonic.net (Alex Kleider) Date: Wed, 06 Nov 2013 21:42:01 -0800 Subject: [Tutor] =?utf-8?q?Can_someone_please_help_me_with_this=3F?= In-Reply-To: References: <91bd1664a6fbde88c19265c38b2753d9@sonic.net> Message-ID: <5156f9d4b3e24fcce5c5efca4fabb542@sonic.net> On 2013-11-06 20:21, Dave Angel wrote: > The plus operator doesn't append to the list; it makes a new one. > Doesn't meet spec. Right. It seems then that one could be critical of the assignment in that it is requiring a function that has side effects which is something that should be discouraged. To be fair, the name of the function ('transform') does suggest that it will change something (but does not suggest that anything will be returned.) Comments? From davea at davea.name Thu Nov 7 07:14:02 2013 From: davea at davea.name (Dave Angel) Date: Thu, 07 Nov 2013 00:14:02 -0600 Subject: [Tutor] Can someone please help me with this? In-Reply-To: <5156f9d4b3e24fcce5c5efca4fabb542@sonic.net> References: <91bd1664a6fbde88c19265c38b2753d9@sonic.net> <5156f9d4b3e24fcce5c5efca4fabb542@sonic.net> Message-ID: On Wed, 06 Nov 2013 21:42:01 -0800, Alex Kleider wrote: > It seems then that one could be critical of the assignment in that it is > requiring a function that has side effects which is something that > should be discouraged. Classroom assignments are frequently like that. But without context it's hard to know which "rule" should be followed. The real key is not in critiquing style but realizing exactly what's being asked for. -- DaveA From oscar.j.benjamin at gmail.com Thu Nov 7 10:23:31 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 7 Nov 2013 09:23:31 +0000 Subject: [Tutor] Can someone please help me with this? In-Reply-To: <91bd1664a6fbde88c19265c38b2753d9@sonic.net> References: <91bd1664a6fbde88c19265c38b2753d9@sonic.net> Message-ID: On 7 November 2013 02:56, Alex Kleider wrote: > On 2013-11-06 01:52, Oscar Benjamin wrote: > >> >> I'll give one suggestion which is that to concatenate one list onto >> the end of another you would use the .extend() method rather than the >> .append() method. > > > What would be the advantage/disadvantage of what you suggest vs using the > plus (+) operand as in > l = l1 + l2 > ?? As Dave says l1 + l2 creates a new list. However l1 += l2 does the same as the extend method and mutates l1 in place. Oscar From oscar.j.benjamin at gmail.com Thu Nov 7 14:45:27 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 7 Nov 2013 13:45:27 +0000 Subject: [Tutor] Can someone please help me with this? In-Reply-To: References: Message-ID: On 7 November 2013 13:28, Anton Gilb wrote: > > I don't know how to reach all of you that helped me out, but I just want to extend a huge thank you! You guys are a big help and your time and input is well appreciated! Hi Anton, you can reach everyone by sending your reply email to tutor at python.org (or just using reply-all) as I have for this email. I'm glad you appreciate the help. Oscar From donsuni at gmail.com Thu Nov 7 23:25:29 2013 From: donsuni at gmail.com (donsuni) Date: Thu, 7 Nov 2013 14:25:29 -0800 (PST) Subject: [Tutor] Finding a nearest perfect cube Message-ID: <1383863129765-5038336.post@n6.nabble.com> Hi, I am new to python and i have to write a following code without using any inbuilt function or a for loop. Only while and if loops are allowed. If i input a number, i should get a perfect cube nearest to it. For eg: if input=4, output=8 input=8, output=27 and so on.... can some one help with the code? -- View this message in context: http://python.6.x6.nabble.com/Finding-a-nearest-perfect-cube-tp5038336.html Sent from the Python - tutor mailing list archive at Nabble.com. From marc.tompkins at gmail.com Fri Nov 8 00:24:33 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 7 Nov 2013 15:24:33 -0800 Subject: [Tutor] Finding a nearest perfect cube In-Reply-To: <1383863129765-5038336.post@n6.nabble.com> References: <1383863129765-5038336.post@n6.nabble.com> Message-ID: On Thu, Nov 7, 2013 at 2:25 PM, donsuni wrote: > Hi, I am new to python and i have to write a following code without using > any > inbuilt function or a for loop. Only while and if loops are allowed. > > If i input a number, i should get a perfect cube nearest to it. > For eg: if > input=4, output=8 > input=8, output=27 > and so on.... > can some one help with the code? > You're about to get a deluge of responses just like this, but: We don't do people's homework for them. If you've made some effort and you're stuck, show us what you've done and a LOT of people will be happy to help. But doing it for you? Not so much. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 8 00:38:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 07 Nov 2013 23:38:53 +0000 Subject: [Tutor] Finding a nearest perfect cube In-Reply-To: <1383863129765-5038336.post@n6.nabble.com> References: <1383863129765-5038336.post@n6.nabble.com> Message-ID: On 07/11/13 22:25, donsuni wrote: > Hi, I am new to python and i have to write a following code without using any > inbuilt function or a for loop. Only while and if loops are allowed. > > If i input a number, i should get a perfect cube nearest to it. > For eg: if > input=4, output=8 > input=8, output=27 > and so on.... > can some one help with the code? We will help YOU write the code but we won't do it for you. So what have you got so far? If you don't have code do you know how to solve it in your mind? Can you write down the algorithm you would use to solve it? As for the restrictions, don't worry about them too much. Anything you can do with a for loop you can do with a while loop, just with a little more effort. The restriction on not using inbuilt functions is a bit more severe because you can't do a lot without using inbuilt functions, but I assume they mean that using things like +, -,*,etc is OK. As would be printing. BTW it also helps to know which Python version you are using (v2 or v3) and sometimes what OS you are running. Finally, some questions about the problem: The examples you give you always take the next cube up the scale, but inputting 8 should surely give 8 as an answer since 8 is a cube? And what if I input 9? Can I count back down to 8 or must I go upwards to the next cube? In which case it may not really be the "nearest" cube but the "next" cube. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From dyoo at hashcollision.org Fri Nov 8 03:07:00 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 7 Nov 2013 18:07:00 -0800 Subject: [Tutor] Finding a nearest perfect cube In-Reply-To: <1383863129765-5038336.post@n6.nabble.com> References: <1383863129765-5038336.post@n6.nabble.com> Message-ID: > > > If i input a number, i should get a perfect cube nearest to it. > For eg: if > input=4, output=8 > input=8, output=27 > and so on.... > Let's consider those examples. Pretend you were given: input = 4 and the description of the problem. Forget computers for a brief moment. What would YOU do do solve this problem? Why should I believe that "8" is an acceptable answer to this? This is one of the first steps to understanding the problem, to understand the sample inputs and outputs. If you find that those outputs make no sense, then you've got to stop right now: no amount of coding will help if you don't understand what you're trying to code. Same question to 'input = 8'. Why would "27" be an acceptable answer? In fact, I would argue that the expected answer here is wrong if we pay attention to the problem statement. 8 is a perfect cube, and 8 is closest to 8, as math.abs(8 - 8) == 0! So you must define what you mean by "closest". -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Nov 8 10:36:14 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 08 Nov 2013 09:36:14 +0000 Subject: [Tutor] Finding a nearest perfect cube In-Reply-To: <1383863129765-5038336.post@n6.nabble.com> References: <1383863129765-5038336.post@n6.nabble.com> Message-ID: On 07/11/2013 22:25, donsuni wrote: > Hi, I am new to python and i have to write a following code without using any > inbuilt function or a for loop. Only while and if loops are allowed. > > If i input a number, i should get a perfect cube nearest to it. > For eg: if > input=4, output=8 > input=8, output=27 > and so on.... > can some one help with the code? > Impossible as stated above, how do you get input without using an inbuilt function? I'd also like to see you write an if loop. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From joel.goldstick at gmail.com Fri Nov 8 11:12:39 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 8 Nov 2013 05:12:39 -0500 Subject: [Tutor] Finding a nearest perfect cube In-Reply-To: References: <1383863129765-5038336.post@n6.nabble.com> Message-ID: On Fri, Nov 8, 2013 at 4:36 AM, Mark Lawrence wrote: > On 07/11/2013 22:25, donsuni wrote: >> >> Hi, I am new to python and i have to write a following code without using >> any >> inbuilt function or a for loop. Only while and if loops are allowed. This is confusing. What is an 'if loop'? Of course your instructor didn't say that that. Well, if he did, you should get your money back and drop the course. It will be better to help you if you actually print the exact assignment. >> >> If i input a number, i should get a perfect cube nearest to it. >> For eg: if >> input=4, output=8 >> input=8, output=27 >> and so on.... >> can some one help with the code? >> > > Impossible as stated above, how do you get input without using an inbuilt > function? I'd also like to see you write an if loop. > > -- > Python is the second best programming language in the world. > But the best has yet to be invented. Christian Tismer > > Mark Lawrence > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick http://joelgoldstick.com From breamoreboy at yahoo.co.uk Fri Nov 8 14:48:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 08 Nov 2013 13:48:24 +0000 Subject: [Tutor] Finding a nearest perfect cube In-Reply-To: References: <1383863129765-5038336.post@n6.nabble.com> Message-ID: On 08/11/2013 10:12, Joel Goldstick wrote: > On Fri, Nov 8, 2013 at 4:36 AM, Mark Lawrence wrote: >> On 07/11/2013 22:25, donsuni wrote: >>> >>> Hi, I am new to python and i have to write a following code without using >>> any >>> inbuilt function or a for loop. Only while and if loops are allowed. > > This is confusing. What is an 'if loop'? Of course your instructor > didn't say that that. Well, if he did, you should get your money back > and drop the course. It will be better to help you if you actually > print the exact assignment. >>> >>> If i input a number, i should get a perfect cube nearest to it. >>> For eg: if >>> input=4, output=8 >>> input=8, output=27 >>> and so on.... >>> can some one help with the code? >>> >> >> Impossible as stated above, how do you get input without using an inbuilt >> function? I'd also like to see you write an if loop. >> >> -- >> Python is the second best programming language in the world. >> But the best has yet to be invented. Christian Tismer >> >> Mark Lawrence >> Joel, could you please sort out your email client or the way you use it. The above is confusing as you're replying to me, but your response is actually to the OP's words. If you need technical support I can recommend a really good Greek national that I'm aquainted with :) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From alan.gauld at btinternet.com Fri Nov 8 15:55:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 08 Nov 2013 14:55:53 +0000 Subject: [Tutor] Finding a nearest perfect cube In-Reply-To: References: <1383863129765-5038336.post@n6.nabble.com> Message-ID: On 08/11/13 10:12, Joel Goldstick wrote: >>> inbuilt function or a for loop. Only while and if loops are allowed. > > This is confusing. What is an 'if loop'? I'm not sure why but this is a common mistake by beginners. I get a lot of emails about my tutorial that refer to "if loops" even though I never use that term. I think beginners somehow confuse the terms block and loop. Maybe because they look similar visually. Whatever the reason they should still learn to use the correct terminology or we all get confused. But I wouldn't be too harsh on the OP, he/she is not alone. > ...It will be better to help you if you actually > print the exact assignment. And this is certainly true along with the usual advice to print the full text of any errors you get too.. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From donsuni at gmail.com Fri Nov 8 13:54:53 2013 From: donsuni at gmail.com (donsuni) Date: Fri, 8 Nov 2013 04:54:53 -0800 (PST) Subject: [Tutor] sequence of elements problem Message-ID: <1383915293058-5038402.post@n6.nabble.com> Hi, I have a problem in python which is kind of tricky. if i give a sequence of numbers, i should get another sequence of numbers such that the the elements exceeds previous element in the list. For eg seq_num([3,2,5,7])=[3,5,7] since 5 is >3, and 7>5 seq_num([1,2,3,4])=[1,2,3,4] since 2 is >1, and 3>2 and so on seq_num([5,5,5])=[5] seq_num([9,8,7])=[9] and so on without using any inbuilt functions. I tried the following code but it is not incrementing: def seq_num(numlist): n=len(numlist) for i in range(0,n - 1): if numlist[i]>numlist[i+1]: i+=1 return numlist[i] -- View this message in context: http://python.6.x6.nabble.com/sequence-of-elements-problem-tp5038402.html Sent from the Python - tutor mailing list archive at Nabble.com. From breamoreboy at yahoo.co.uk Fri Nov 8 19:24:30 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 08 Nov 2013 18:24:30 +0000 Subject: [Tutor] sequence of elements problem In-Reply-To: <1383915293058-5038402.post@n6.nabble.com> References: <1383915293058-5038402.post@n6.nabble.com> Message-ID: On 08/11/2013 12:54, donsuni wrote: > Hi, I have a problem in python which is kind of tricky. > > if i give a sequence of numbers, i should get another sequence of numbers > such that the the elements exceeds previous element in the list. For eg > > seq_num([3,2,5,7])=[3,5,7] since 5 is >3, and 7>5 > seq_num([1,2,3,4])=[1,2,3,4] since 2 is >1, and 3>2 and so on > seq_num([5,5,5])=[5] > seq_num([9,8,7])=[9] > > and so on without using any inbuilt functions. > > I tried the following code but it is not incrementing: > > def seq_num(numlist): > > n=len(numlist) > > for i in range(0,n - 1): > > if numlist[i]>numlist[i+1]: > i+=1 > return numlist[i] > You've failed to meet the stated requirement as len and range are built-in functions so whether or not the increment occurs is irrelevant. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From davea at davea.name Fri Nov 8 19:33:17 2013 From: davea at davea.name (Dave Angel) Date: Fri, 08 Nov 2013 12:33:17 -0600 Subject: [Tutor] sequence of elements problem In-Reply-To: <1383915293058-5038402.post@n6.nabble.com> References: <1383915293058-5038402.post@n6.nabble.com> <1383915293058-5038402.post@n6.nabble.com> Message-ID: On Fri, 8 Nov 2013 04:54:53 -0800 (PST), donsuni wrote: > Hi, I have a problem in python which is kind of tricky. Your wording is kind of tricky. > and so on without using any inbuilt functions. But you use len() and range(). Has your class taught about generators or list comprehensions? Currently your function returns an int, not a list. Changing it from a function to a generator might be easiest. -- DaveA From dyoo at hashcollision.org Fri Nov 8 20:17:07 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 8 Nov 2013 11:17:07 -0800 Subject: [Tutor] sequence of elements problem In-Reply-To: <1383915293058-5038402.post@n6.nabble.com> References: <1383915293058-5038402.post@n6.nabble.com> Message-ID: On Fri, Nov 8, 2013 at 4:54 AM, donsuni wrote: > Hi, I have a problem in python which is kind of tricky. > > if i give a sequence of numbers, i should get another sequence of numbers > such that the the elements exceeds previous element in the list. For eg > Have you written any other functions that takes lists and produce lists? If so, can you show them to us? The function you have so far is one that takes a list, but (at best) it's returning a single element in the list. That means you may not yet know how to write functions that produce lists. Do you know how to do so yet? -------------- next part -------------- An HTML attachment was scrubbed... URL: From abjadmailinglist at gmail.com Fri Nov 8 20:19:28 2013 From: abjadmailinglist at gmail.com (Peter O'Doherty) Date: Fri, 08 Nov 2013 20:19:28 +0100 Subject: [Tutor] Geometric sequence In-Reply-To: References: <52713CFB.10907@gmail.com> Message-ID: <527D3940.3020409@gmail.com> To the people who kindly replied to my question: many thanks! On 10/31/2013 06:29 PM, Danny Yoo wrote: > As an aside: It shouldn't be too bad to write a "generator" for the > geometric series, so that we can pick out the terms on-demand. > > ################################# > >>> def geometric(base): > ... x = 1 > ... while True: > ... yield x > ... x *= base > ... > >>> twos = geometric(2) > ################################# > > > 'twos' is a representation of the geometric series; we can then pick > out the elements one at a time: > > > ################################# > >>> twos.next() > 1 > >>> twos.next() > 2 > >>> twos.next() > 4 > >>> twos.next() > 8 > >>> twos.next() > 16 > >>> twos.next() > 32 > >>> twos.next() > 64 > ################################# > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From florinvlad.olariu at gmail.com Sat Nov 9 22:04:09 2013 From: florinvlad.olariu at gmail.com (Vlad Olariu) Date: Sat, 9 Nov 2013 22:04:09 +0100 Subject: [Tutor] Hi! Message-ID: Hello. I am new to python and mailing lists. Where should I post some code if I need to? -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Nov 12 18:53:13 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 12 Nov 2013 17:53:13 +0000 Subject: [Tutor] Hi! In-Reply-To: References: Message-ID: On 09/11/2013 21:04, Vlad Olariu wrote: > Hello. I am new to python and mailing lists. Where should I post some > code if I need to? > Here but only after you've read this http://sscce.org/ -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From joel.goldstick at gmail.com Tue Nov 12 18:54:07 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 12 Nov 2013 12:54:07 -0500 Subject: [Tutor] Hi! In-Reply-To: References: Message-ID: On Sat, Nov 9, 2013 at 4:04 PM, Vlad Olariu wrote: > Hello. I am new to python and mailing lists. Where should I post some code > if I need to? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Tell us your python version and OS version Try to create a small code example that shows the question you have. If you get an error in your code, copy and paste the complete traceback here Some people post to pastebin, but many others don't like that. So, best to keep example small and post here Finally, post in plaintext, not html -- Joel Goldstick http://joelgoldstick.com From amitsaha.in at gmail.com Tue Nov 12 23:48:28 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 13 Nov 2013 08:48:28 +1000 Subject: [Tutor] Hi! In-Reply-To: References: Message-ID: Hello, On Sun, Nov 10, 2013 at 7:04 AM, Vlad Olariu wrote: > Hello. I am new to python and mailing lists. Where should I post some code > if I need to? Welcome. Here is an example of a post with code. Assume that I am explaining to someone how they can exit out a while loop before the condition violated the first time: A while loop is an example of an "entry controlled" loop. This means that the condition is checked before entering the loop. Hence, this means if your loop condition was violated during the previous iteration, but not at the beginning, your loop will terminate after the first violation, not before it. Here is a simple example: >>> a = 1 >>> while a < 5: ... a = a+3 ... print a ... 4 7 .. and so on. Also switch to "Plain Text" in your Gmail window before you post. (if you do not know what this means, please search on the Web a bit). Good Luck. Best. Amit. -- http://echorand.me From jarod_v6 at libero.it Wed Nov 13 23:26:51 2013 From: jarod_v6 at libero.it (jarod_v6 at libero.it) Date: Wed, 13 Nov 2013 23:26:51 +0100 (CET) Subject: [Tutor] Help merge files using python Message-ID: <11040706.4729721384381611789.JavaMail.defaultUser@defaultHost> Hi I want to merge many files like this: #file1 A 10 B 20 C 30 #file2 B 45 Z 10 #file1 A 60 B 70 C 10 I want to obtain A 10 0 60 B 20 45 70 C 30 0 10 Z 0 10 0 I try to do like this: f = os.listdir(".") for i in f: T =open(i,"r") for r in t.readlines(): print r Could you please help me to understand how to use the right procedure in python?Thanks a lot! bw ----Messaggio originale---- >Da: tutor-request at python.org >Data: 23/10/2013 1.43 >A: >Ogg: Tutor Digest, Vol 116, Issue 58 > >Send Tutor mailing list submissions to > tutor at python.org > >To subscribe or unsubscribe via the World Wide Web, visit > https://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: Beginner Question (Andy McKenzie) > 2. Re: Beginner Question (Dave Angel) > 3. comma in an assignment (Key, Gregory E (E S SF RNA FSF 1 C)) > 4. Howto handle pictures with pyqt (Ulrich Goebel) > 5. Re: Beginner Question (Sven Hennig) > > >---------------------------------------------------------------------- > >Message: 1 >Date: Tue, 22 Oct 2013 13:26:08 -0400 >From: Andy McKenzie >To: "tutor at python.org" >Subject: Re: [Tutor] Beginner Question >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > >On Tue, Oct 22, 2013 at 10:25 AM, Sven Hennig wrote: > >> Hello, I would like to learn a programming language and have decided to >> use Python. I have some programming experience and doing well in Python. >> What really causes me problems is OOP. >> I'm just dont get it... I'm missing a really Practical example. In every >> book I've read are the examples of such Class Dog and the function is bark >> . Has anyone an OOP example for me as it is really used in real code, so >> I can better understand the concept? I do not know why this is so hard for >> me. >> >> Greetings >> Sven >> >> >The actual code I have is in PHP, so it's not exactly useful to post here, >but I can give you an outline of a class I used and found useful. The >class was created to help me manipulate network subnets in an interface to >handle DHCP and DNS on a server. > >class subnet: > > def __init__(cidr): > # Do some stuff with the CIDR notation of the subnet (1.2.3.0/24syntax) > > def netmask: > # Calculate the netmask and return it (ie, 255.255.255.0) > > def first_ip: > # Calculate and return the first IP in the range. > > def last_ip: > # Calculate and return the last IP in the range > > def number_of_addresses: > # Calculate the number of usable addresses in the range and return >that value > >The benefit to me was that I could create an instance of the subnet object >for a group (say, "lab_1"), and then pull out various information. Calling >"lab_1.first_ip()" returns the first possible IP address. That was a lot >more readable and a lot more concise than something like "first_ip( >1.2.3.0/24)". > > >I hope this helps! > >Andy >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 2 >Date: Tue, 22 Oct 2013 17:55:29 +0000 (UTC) >From: Dave Angel >To: tutor at python.org >Subject: Re: [Tutor] Beginner Question >Message-ID: >Content-Type: text/plain; charset=US-ASCII > >On 22/10/2013 10:25, Sven Hennig wrote: > >> Hello, I would like to learn a programming language and have decided to use >> Python. I have some programming experience and doing well in Python. What >> really causes me problems is OOP. >> I'm just dont get it... I'm missing a really Practical example. In every >> book I've read are the examples of such Class Dog and the function is bark. Has >> anyone an OOP example for me as it is really used in real code, so I can >> better understand the concept? I do not know why this is so hard for me. >> > >What you may not realize is you're already doing OOP, just by using the >standard library. When you open a file (or many other things that can >produce a stream of bytes), you get an instance of class file. When you >use that instance, you're calling methods of that instance. So when you >say: > >infile = open("myfile.txt,"r") >data = infile.readline() > >you're doing object oriented programming. You don't have to know what >kind of thing "infile" is, you just have to know it has methods read(), >readline(), close(), etc. > >When you want to write your own classes, or when you want to make a new >class that's related but different from one of the thousands that are >standard, that's when it gets interesting. As Alan says, GUI is one >place where you'll be wrting your own classes, usually by deriving from >one of the GUI library classes. > >At its most fundamental, a class is a description of how to create and >how to manipulate instances. An instance has methods (functions), and >attributes (data). When one class is derived from another, it can share >some or most of the attributes and behavior of the parent class, but >make changes. This helps avoid duplicating code when two things are >similar. > >You're familiar with list and tuple. Those are built-in >collection classes, supported explicitly by the language. But if you >want your own collection, you may want to make a class for it. The Dog >bark() example may seem silly, but a Dog has lots of other methods >besides that one, and has lots of attributes (color, breed, health >state, owner, etc.). In a sense those attributes are like a list within >the Dog, but you want them to have nice names, instead of remembering >that the 3rd one is owner. > > >-- >DaveA > > > > >------------------------------ > >Message: 3 >Date: Tue, 22 Oct 2013 19:20:25 +0000 >From: "Key, Gregory E (E S SF RNA FSF 1 C)" >To: "tutor at python.org" >Subject: [Tutor] comma in an assignment >Message-ID: > <5C28117E8FDB0E4F999E3CB30775EF5901F9A5 at USLZUA0EM21MSX.ww017.siemens.net> > >Content-Type: text/plain; charset="us-ascii" > >I understand that a comma in Python is a separator and not an operator. In some of the MatPlotLib examples I see code like this: > >line1, = ax1.plot(t, y1, lw=2, color='red', label='1 HZ') > >What does the comma do in an assignment statement? > >Greg Key > > >This message and any attachments are solely for the use of intended recipients. The information contained herein may include trade secrets, protected health or personal information, privileged or otherwise confidential information. Unauthorized review, forwarding, printing, copying, distributing, or using such information is strictly prohibited and may be unlawful. If you are not an intended recipient, you are hereby notified that you received this email in error, and that any review, dissemination, distribution or copying of this email and any attachment is strictly prohibited. If you have received this email in error, please contact the sender and delete the message and any attachment from your system. Thank you for your cooperation >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Message: 4 >Date: Tue, 22 Oct 2013 23:21:20 +0200 >From: Ulrich Goebel >To: tutor at python.org >Subject: [Tutor] Howto handle pictures with pyqt >Message-ID: <5266EC50.9070307 at fam-goebel.de> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >Hello, > >for my first python program I try to build a user interface for a litle >address database. Therefor I use pyqt to build the formular, and later I >will connect it to an existing SQLite DB, using APSW. > >Besides the "normal" things as name, address, email and others I want to >store an image. Normaly that will be given as a file (.jpg, .png, or >other type). I would let the user find the picture with a >QFileDialog.getOpenFileName() dialog. But what to do after that? Here >are my questions: > >Which widget is able to show the picture? > >How to show the picture? That means: howto put the picture from the file >into the widget? > >How to put the picture data into an blob(?) column in the database? > >How to get the data back from there and bring it in the widget? > >May be there is a tutorial which I didn't find yet? > >Thank's a lot for any help! > >Greetings >Ulrich > >-- >Ulrich Goebel >Paracelsusstr. 120, 53177 Bonn > > >------------------------------ > >Message: 5 >Date: Tue, 22 Oct 2013 20:18:28 +0200 >From: Sven Hennig >To: tutor at python.org >Subject: Re: [Tutor] Beginner Question >Message-ID: > >Content-Type: text/plain; charset="iso-8859-1" > >Thank you! You guys helped me out alot. > >@Alan your website is great! Really clearly written. Especially the "Things >to remember" part. > >If you have exercises for me or have a Website with exercises, bring it on. I >think this is the best way to learn. > > > >2013/10/22 Dave Angel > >> On 22/10/2013 10:25, Sven Hennig wrote: >> >> > Hello, I would like to learn a programming language and have decided to >> use >> > Python. I have some programming experience and doing well in Python. What >> > really causes me problems is OOP. >> > I'm just dont get it... I'm missing a really Practical example. In every >> > book I've read are the examples of such Class Dog and the function is >> bark. Has >> > anyone an OOP example for me as it is really used in real code, so I can >> > better understand the concept? I do not know why this is so hard for me. >> > >> >> What you may not realize is you're already doing OOP, just by using the >> standard library. When you open a file (or many other things that can >> produce a stream of bytes), you get an instance of class file. When you >> use that instance, you're calling methods of that instance. So when you >> say: >> >> infile = open("myfile.txt,"r") >> data = infile.readline() >> >> you're doing object oriented programming. You don't have to know what >> kind of thing "infile" is, you just have to know it has methods read(), >> readline(), close(), etc. >> >> When you want to write your own classes, or when you want to make a new >> class that's related but different from one of the thousands that are >> standard, that's when it gets interesting. As Alan says, GUI is one >> place where you'll be wrting your own classes, usually by deriving from >> one of the GUI library classes. >> >> At its most fundamental, a class is a description of how to create and >> how to manipulate instances. An instance has methods (functions), and >> attributes (data). When one class is derived from another, it can share >> some or most of the attributes and behavior of the parent class, but >> make changes. This helps avoid duplicating code when two things are >> similar. >> >> You're familiar with list and tuple. Those are built-in >> collection classes, supported explicitly by the language. But if you >> want your own collection, you may want to make a class for it. The Dog >> bark() example may seem silly, but a Dog has lots of other methods >> besides that one, and has lots of attributes (color, breed, health >> state, owner, etc.). In a sense those attributes are like a list within >> the Dog, but you want them to have nice names, instead of remembering >> that the 3rd one is owner. >> >> >> -- >> DaveA >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> >-------------- next part -------------- >An HTML attachment was scrubbed... >URL: > >------------------------------ > >Subject: Digest Footer > >_______________________________________________ >Tutor maillist - Tutor at python.org >https://mail.python.org/mailman/listinfo/tutor > > >------------------------------ > >End of Tutor Digest, Vol 116, Issue 58 >************************************** > From amitsaha.in at gmail.com Thu Nov 14 00:25:41 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Thu, 14 Nov 2013 09:25:41 +1000 Subject: [Tutor] Help merge files using python In-Reply-To: <11040706.4729721384381611789.JavaMail.defaultUser@defaultHost> References: <11040706.4729721384381611789.JavaMail.defaultUser@defaultHost> Message-ID: On Thu, Nov 14, 2013 at 8:26 AM, jarod_v6 at libero.it wrote: > Hi I want to merge many files like this: > #file1 > A 10 > B 20 > C 30 > #file2 > B 45 > Z 10 > #file1 > A 60 > B 70 > C 10 > > I want to obtain > > A 10 0 60 > B 20 45 70 > C 30 0 10 > Z 0 10 0 >From your example, it looks like you can have any number of unique letters and the final file should have each of those listed. Against each, you should have the numbers that appear against them in the files (0 if not). So here is what I think should be an approach you could follow: 1. For each file, record each letter and the number against it (A dictionary comes to mind) 2. Once you have the dictionary for each file, create a set (as in a Python data structure) of the keys. This set will give you all the unique letters. 3. Now for each member of this set, look if it appears it each of the above dictionaries. If it occurs, note it's value, else put it down as 0. Create a new dictionary (which will be your final dictionary). The key should be each letter and the value should be a list with one or more numbers. 4. Once you are done iterating over each element of the set, your dictionary in step 3 will have the unique letters against the numbers that occur against them in the files. Now, you can write this dictionary into a file. Since you want a plain text file you will have to iterate over the keys and values. So let's consider your example: > #file1 > A 10 > B 20 > C 30 > #file2 > B 45 > Z 10 > #file3 > A 60 > B 70 > C 10 After step 1 above, you have three dictionaries, say d1, d2 and d3: d1 = {'A':10, 'B': 20, 'C':30} d2 = {'B':45, 'Z':10} d3 = {'A':60, 'B':70, 'C':10} Now, step 2, will give you a set of the keys above: unique_letters = {'A', 'B', 'C', 'Z'} After step 3, you will have this global dictionary: d = {'A':[10, 0, 60], 'B':[20, 45, 70], 'C':[30, 0, 10], 'Z':[0, 10, 0]} Now you can write this dictionary to a file. Note that step 2 will require you to combine the three individual dictionaries, so you may have to learn how to do that first. > > I try to do like this: > f = os.listdir(".") > for i in f: > T =open(i,"r") > for r in t.readlines(): > print r > > Could you please help me to understand how to use the right procedure in > python?Thanks a lot! Does the above steps help? Best, Amit. -- http://echorand.me From alan.gauld at btinternet.com Thu Nov 14 02:27:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Nov 2013 01:27:20 +0000 Subject: [Tutor] Help merge files using python In-Reply-To: <11040706.4729721384381611789.JavaMail.defaultUser@defaultHost> References: <11040706.4729721384381611789.JavaMail.defaultUser@defaultHost> Message-ID: On 13/11/13 22:26, jarod_v6 at libero.it wrote: > I want to obtain > > A 10 0 60 > B 20 45 70 > C 30 0 10 > Z 0 10 0 Amit has given you a design to solve the problem, however based on your code you may not be able to translate that into code yet. > I try to do like this: > f = os.listdir(".") > for i in f: > T =open(i,"r") > for r in t.readlines(): > print r First, note that indentation counts in Python So your code opens each file and stores a reference in T. But each assignment loses the previous one so you wind up with just the final file reference stored in T. Second, note that Python is case sensitive so 't' and 'T' are not the same name. So your second loop tries to read lines from t but t does not exist. Your code should look more like this for f in os.listdir('.'): for r in open(f).readlines(): print r BTW it's better to use meaningful names rather than single letter names for variables. But that still won't really produce what you want, it will just print out every line in every file. Read Amit's mail and review the documentation on dictionaries and sets. Try again and if you get stuck ask for more help. And please don't post an entire digest next time, some people pay by the byte. Delete any messages that are not directly relevant. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From thabilerampa at gmail.com Thu Nov 14 16:54:29 2013 From: thabilerampa at gmail.com (Thabile Rampa) Date: Thu, 14 Nov 2013 17:54:29 +0200 Subject: [Tutor] TypeError: generatePersonID() takes exactly 1 argument (0 given) Message-ID: Hi, So I'm learning how to define my own functions, and in an exercise I was given, I get this error: Traceback (most recent call last): File "X:/X/xxx/Xxxxx/function_practice.py", line 36, in main () File "X:/X/xxx/Xxxxx/function_practice.py/function_practice.py", line 34, in main generatePersonID () TypeError: generatePersonID() takes exactly 1 argument (0 given) Here is the code: def getUserInput(): """ Get input from the user, i.e fullname, grossSalary, costs. Returns: fullName, grossSalary, costs """ grossSalary =None ; costs =None fullName="" while not fullName: fullName = raw_input ("First and Last Names: ") while not grossSalary: #TODO grossSalary = int (raw_input ("Annual Gross Salary: ")) while not costs: #TODO costs = int(raw_input ("Yearly costs: ")) return fullName, grossSalary, costs def generatePersonID (fullName): """generates unique ID""" global id id = (fullName) + 1 personID = str (id) + fullName return personID def main (): getUserInput () generatePersonID () main () raw_input ("Press the enter key to exit.") Regards, Tab -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Nov 14 18:21:11 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 14 Nov 2013 12:21:11 -0500 Subject: [Tutor] TypeError: generatePersonID() takes exactly 1 argument (0 given) In-Reply-To: References: Message-ID: On Thu, Nov 14, 2013 at 10:54 AM, Thabile Rampa wrote: > Hi, > > So I'm learning how to define my own functions, and in an exercise I was > given, I get this error: > > Traceback (most recent call last): > File "X:/X/xxx/Xxxxx/function_practice.py", line 36, in > main () > File "X:/X/xxx/Xxxxx/function_practice.py/function_practice.py", line 34, > in main > generatePersonID () > TypeError: generatePersonID() takes exactly 1 argument (0 given) > > Here is the code: > > def getUserInput(): > """ > Get input from the user, i.e fullname, grossSalary, costs. > Returns: fullName, grossSalary, costs > """ > > grossSalary =None ; > costs =None > fullName="" > > while not fullName: > > fullName = raw_input ("First and Last Names: ") > > while not grossSalary: > #TODO > grossSalary = int (raw_input ("Annual Gross Salary: ")) > > while not costs: > #TODO > costs = int(raw_input ("Yearly costs: ")) > > return fullName, grossSalary, costs > > def generatePersonID (fullName): > """generates unique ID""" > global id > id = (fullName) + 1 > personID = str (id) + fullName > return personID > > def main (): > getUserInput () > generatePersonID () > > main () > > raw_input ("Press the enter key to exit.") > > Regards, > Tab > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > You defined generatePersonID to take the parameter fullName, but when you call it, you don't pass a value. See what happens if you change the last line of main() to this: generatePersonID("PersonID") -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Thu Nov 14 18:32:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Nov 2013 17:32:13 +0000 Subject: [Tutor] TypeError: generatePersonID() takes exactly 1 argument (0 given) In-Reply-To: References: Message-ID: On 14/11/13 15:54, Thabile Rampa wrote: > Hi, > > So I'm learning how to define my own functions, and in an exercise I was > given, I get this error: > > Traceback (most recent call last): > ", line 34, in main > generatePersonID () > TypeError: generatePersonID() takes exactly 1 argument (0 given) OK, The error says you haven't passed an argum ent to your function. Lets take a look at the function... > def generatePersonID (fullName): > """generates unique ID""" > global id > id = (fullName) + 1 > personID = str (id) + fullName > return personID Yep, it needs an input argument. And it returns an ID. But it looks a bit odd so I'll walk through it and see if what I think its doing matches up with what you expect it to do. > def generatePersonID (fullName): This defines the function so that you can call it like myID = generatePersonID(someID) > """generates unique ID""" > global id This says it uses a global variable called id. I don't see any such variable in your code. It's usually a bad idea to rely on global variables like this. Either pass the variable in as an extra argument or avoid using it if possible. Only use globals as a last resort. > id = (fullName) + 1 This is where the wierdness happens. You add 1 to the argument passed in which is called fullName. Now either fullName is actually a number or you don't want to add 1 to it. If it is a number then change the name of the parameter. If it is really a string then maybe you want to append the character '1' to it? If so just use '1' instead of 1. Either way, you don't need the parens around fullName, they don't do anything. > personID = str (id) + fullName More wierdness. Here you take the new id value created above and convert it to a string then add the fullName again. But if fullName is a number this will fail. And if its a string and you meant to append'1' above then you get the odd result (if fullname is "alan gauld") of personID ending up like "alan gauld1alan gauld" Which is not what I think you want? > return personID And finally you return the result, no problems there. So I think you need to think through what types of data you are passing in and how you manipulate them. There is definitely something wrong as it stands. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Thu Nov 14 18:24:50 2013 From: akleider at sonic.net (Alex Kleider) Date: Thu, 14 Nov 2013 09:24:50 -0800 Subject: [Tutor] TypeError: generatePersonID() takes exactly 1 argument (0 given) In-Reply-To: References: Message-ID: <085bd7bb63dd7af59d35ffe5f5137da3@sonic.net> On 2013-11-14 07:54, Thabile Rampa wrote: > Hi, > > So I'm learning how to define my own functions, and in an exercise I > was given, I get this error: > > Traceback (most recent call last): > ? File "X:/X/xxx/Xxxxx/function_practice.py", line 36, in > ??? main () > ? File "X:/X/xxx/Xxxxx/function_practice.py/function_practice.py > [1]", line 34, in main > ??? generatePersonID () > TypeError: generatePersonID() takes exactly 1 argument (0 given) > > Here is the code: > > def getUserInput(): > ??? """ > ??? Get input from the user, i.e fullname, grossSalary, costs. > ??? Returns: fullName, grossSalary, costs > ??? """ > ??? > ??? grossSalary =None ; > ??? costs =None > ??? fullName="" > ??? > ??? while not fullName: > ??????? > ??????? fullName = raw_input ("First and Last Names: ") > > ??? while not grossSalary: > ??????? #TODO > ??????? grossSalary = int (raw_input ("Annual Gross Salary: ")) > > ??? while not costs: > ??????????????? #TODO > ??????? costs = int(raw_input ("Yearly costs: ")) > > ??? return fullName, grossSalary, costs > > def generatePersonID (fullName): > ??? """generates unique ID""" > ??? global id > ??? id = (fullName) + 1 > ??? personID = str (id) + fullName > ??? return personID > > def main (): > ??? getUserInput () > ??? generatePersonID () > ??? > main () > > raw_input ("Press the enter key to exit.") You define 'generatePersonID' as a function that requires one parameter but you do not give it a parameter when you call it with in your 'main' function. That's exactly what your error message is trying to tell you. From __peter__ at web.de Fri Nov 15 10:04:36 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Nov 2013 10:04:36 +0100 Subject: [Tutor] Help merge files using python References: <11040706.4729721384381611789.JavaMail.defaultUser@defaultHost> Message-ID: jarod_v6 at libero.it wrote: > Hi I want to merge many files like this: > #file1 > A 10 > B 20 > C 30 > #file2 > B 45 > Z 10 > #file1 > A 60 > B 70 > C 10 > > I want to obtain > > A 10 0 60 > B 20 45 70 > C 30 0 10 > Z 0 10 0 > > I try to do like this: > f = os.listdir(".") > for i in f: > T =open(i,"r") > for r in t.readlines(): > print r > > Could you please help me to understand how to use the right procedure in > python?Thanks a lot! If I were into spoon-feeding I would post import os folder = "." destfilename = "../pivot" filenames = sorted(os.listdir(folder)) filenames = [os.path.join(folder, name) for name in filenames] N = len(filenames) pivot = {} for index, filename in enumerate(filenames): with open(filename) as file: for line in file: key, value = line.split() pivot.setdefault(key, ["0"] * N)[index] = value with open(destfilename, "w") as dest: for key, value in sorted(pivot.items()): dest.write("\t".join([key] + value)) dest.write("\n") From sobisw at gmail.com Fri Nov 15 15:20:04 2013 From: sobisw at gmail.com (Sourav Biswas) Date: Fri, 15 Nov 2013 19:50:04 +0530 Subject: [Tutor] Need help on Python API programmig Message-ID: Hi All, This is my first post. I want to learn API programming with Python. I have basic knowledge of Python Programming. Could you please let me know the starting points for this programming. -- Thanks, Sourav Biswas Hyderabad -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Fri Nov 15 22:14:20 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sat, 16 Nov 2013 07:14:20 +1000 Subject: [Tutor] Need help on Python API programmig In-Reply-To: References: Message-ID: Hello Sourav, On 16/11/2013 6:53 AM, "Sourav Biswas" wrote: > > Hi All, > > This is my first post. I want to learn API programming with Python. I have basic knowledge of Python Programming. Could you please let me know the starting points for this programming. Since your question is fairly vague, could you please describe what you are trying to learn? An API is an interface. It can be an operating system interface, a vehicle web API or simply a web API. Some more details will be a lot of help. Best, Amit. > > -- > Thanks, > Sourav Biswas > Hyderabad > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From harveytrasmontero at hotmail.com Fri Nov 15 23:44:47 2013 From: harveytrasmontero at hotmail.com (harvey trasmontero) Date: Sat, 16 Nov 2013 11:44:47 +1300 Subject: [Tutor] Removing Unnecessary Indentation and other problems Message-ID: Good day, I have two problems. First one is, using and downloading tkinter. I have searched about it and it led me to a download page. But then, I didnt know which one to download so I chose the first one on the right. It led me to a zip file and its saying extract the'.tar.gz files for tcl and tk' but I couldn't find it in the zip file that I downloaded. What do I do? Secondly, I am having a hard time finding an answer to my question, which is how to remove indentation on dictionary when I run my program. I've searched google and all but I couldnt find anything. So the dictionary kind of looks like this:Dic = {"Sunnynook Rd":'50',"Carlisle Rd":'50',"East Coast Rd":'50',"Upper Harbour Drive":'50', "Lake Rd":'50',"Waipa St":'50',"Great North Rd":'50',"Richardson Rd":'50',"Atkinson Rd":'50'} My problem is when I run my program, there are unnecessary indentations in Upper Harbour Drive and Lake Rd. So when I run it it looks like this:Atkinson Rd 50Carlisle Rd 50Lake Rd 50Upper Harbour Drive 50Waipa St 50Sunnynook Rd 50Richardson Rd 50Great North Rd 50East Coast Rd 50 How do I align Lake Rd and Upper Harbour Drive so it wont look silly like the one above? Thank you and hope to hear from one of you tutors Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sat Nov 16 00:47:38 2013 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 15 Nov 2013 15:47:38 -0800 Subject: [Tutor] Removing Unnecessary Indentation and other problems In-Reply-To: References: Message-ID: <8ACF6EC6-AEAB-4A94-9171-48E4EF986871@alchemy.com> On your first question, make sure you have the right version of Tcl/Tk for your system (usually a tar.gz file is for Unix-like systems, although some programs like WinZip can read those files too). You may be able to get help from a Tcl/Tk forum on specifics of building that. However, doesn't your Python installation come with tkinter included? Most do. On your second question, the issue is that your program is inserting some kind of spaces or tabs when printing out that dictionary. How are you printing it? Include the actual code of your program please when asking questions about it so we know what's going on. Generally, though, you will want to use a formatted print statement such as the % operator with print, or the .format() method with print. It looks like you're printing a tab between the key and value, which is going to produce output like that if the keys don't fit within a single tab zone (8 characters usually). HTH HAND steve On 15-Nov-2013, at 14:44, harvey trasmontero wrote: > Good day, > > I have two problems. First one is, using and downloading tkinter. I have searched about it and it led me to a download page. But then, I didnt know which one to download so I chose the first one on the right. It led me to a zip file and its saying extract the'.tar.gz files for tcl and tk' but I couldn't find it in the zip file that I downloaded. What do I do? > > Secondly, I am having a hard time finding an answer to my question, which is how to remove indentation on dictionary when I run my program. I've searched google and all but I couldnt find anything. So the dictionary kind of looks like this: > Dic = {"Sunnynook Rd":'50',"Carlisle Rd":'50',"East Coast Rd":'50',"Upper Harbour Drive":'50', > "Lake Rd":'50',"Waipa St":'50',"Great North Rd":'50',"Richardson Rd":'50',"Atkinson Rd":'50'} > > My problem is when I run my program, there are unnecessary indentations in Upper Harbour Drive and Lake Rd. So when I run it it looks like this: > Atkinson Rd 50 > Carlisle Rd 50 > Lake Rd 50 > Upper Harbour Drive 50 > Waipa St 50 > Sunnynook Rd 50 > Richardson Rd 50 > Great North Rd 50 > East Coast Rd 50 > > How do I align Lake Rd and Upper Harbour Drive so it wont look silly like the one above? > > Thank you and hope to hear from one of you tutors > > Regards > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 16 01:27:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Nov 2013 00:27:07 +0000 Subject: [Tutor] Removing Unnecessary Indentation and other problems In-Reply-To: References: Message-ID: On 15/11/13 22:44, harvey trasmontero wrote: > I have two problems. First one is, using and downloading tkinter. I have > searched about it and it led me to a download page. But then, I didnt > know which one to download so I chose the first one on the right. It led > me to a zip file and its saying extract the'.tar.gz files for tcl and > tk' but I couldn't find it in the zip file that I downloaded. What do I do? Normally Tkinter comes with Python. You don't tell us which OS or Python version you are using? But before trying to install it separately have you checked for a binary Python installer for your OS? Activestate have versions for most common OS and they usually include Tkinter ready to run. > dictionary kind of looks like this: > Dic = {"Sunnynook Rd":'50',"Carlisle Rd":'50',"East Coast > Rd":'50',"Upper Harbour Drive":'50', > "Lake Rd":'50',"Waipa St":'50',"Great North Rd":'50',"Richardson > Rd":'50',"Atkinson Rd":'50'} How you create the dictionary has no bearing on how it will display. You need to show us the code that produces the printout. > My problem is when I run my program, there are unnecessary > indentations in Upper Harbour Drive and Lake Rd. What font are you using? If it is not monospace then formatting will be unpredictable. If layout is important its usually better to use a layout centered language like HTML or LaTeX to format the text before printing. for example you could create an HTML table. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From suhasbhairav at hotmail.com Sat Nov 16 04:28:54 2013 From: suhasbhairav at hotmail.com (Suhas Bhairav) Date: Sat, 16 Nov 2013 08:58:54 +0530 Subject: [Tutor] TypeError: generatePersonID() takes exactly 1 argument (0 given) In-Reply-To: <085bd7bb63dd7af59d35ffe5f5137da3@sonic.net> References: , <085bd7bb63dd7af59d35ffe5f5137da3@sonic.net> Message-ID: Hello, In your program, when you're calling generatePersonID(), you need to pass an argument to the function i.e. the value of fullName.This is because when you're defining the function generatePersonID(), it is generatePersonID(fullName) and not just generatePersonID(). So you have pass an arguments while you're calling it. Eg:def main(): getUserInput () generatePersonID ("Suhas") RegardsSuhas > Date: Thu, 14 Nov 2013 09:24:50 -0800 > From: akleider at sonic.net > To: tutor at python.org > Subject: Re: [Tutor] TypeError: generatePersonID() takes exactly 1 argument (0 given) > > On 2013-11-14 07:54, Thabile Rampa wrote: > > Hi, > > > > So I'm learning how to define my own functions, and in an exercise I > > was given, I get this error: > > > > Traceback (most recent call last): > > File "X:/X/xxx/Xxxxx/function_practice.py", line 36, in > > main () > > File "X:/X/xxx/Xxxxx/function_practice.py/function_practice.py > > [1]", line 34, in main > > generatePersonID () > > TypeError: generatePersonID() takes exactly 1 argument (0 given) > > > > Here is the code: > > > > def getUserInput(): > > """ > > Get input from the user, i.e fullname, grossSalary, costs. > > Returns: fullName, grossSalary, costs > > """ > > > > grossSalary =None ; > > costs =None > > fullName="" > > > > while not fullName: > > > > fullName = raw_input ("First and Last Names: ") > > > > while not grossSalary: > > #TODO > > grossSalary = int (raw_input ("Annual Gross Salary: ")) > > > > while not costs: > > #TODO > > costs = int(raw_input ("Yearly costs: ")) > > > > return fullName, grossSalary, costs > > > > def generatePersonID (fullName): > > """generates unique ID""" > > global id > > id = (fullName) + 1 > > personID = str (id) + fullName > > return personID > > > > def main (): > > getUserInput () > > generatePersonID () > > > > main () > > > > raw_input ("Press the enter key to exit.") > > You define 'generatePersonID' as a function that requires one parameter > but you do not give it a parameter when you call it with in your 'main' > function. That's exactly what your error message is trying to tell you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 16 12:22:55 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 16 Nov 2013 11:22:55 +0000 (GMT) Subject: [Tutor] Removing Unnecessary Indentation and other problems In-Reply-To: References: , Message-ID: <1384600975.88166.YahooMailNeo@web186003.mail.ir2.yahoo.com> Including tutor list.? Please use ReplyAll when responding to the list. ? Sorry about that. I am new to this so I didnt know I have to be very specific towards every detailIt depends on what you are asking, but in this case different downloads include different packages? so we need to know which OS, which version and which web site you got it from. In this case I'll? assume you got it from the python.org site? . I downloaded 'Python 3.3.2 Windows x86 MSI Installer?(Windows binary -- does not include source)'?Thats fine it does have Tkinter included. Personally, for Windows users I recommend? getting the Activestate.com version of Python instead. It includes some nice extra features? and it integrates Python more closely with the Windows environment. But thats not the? cause of your problem here. from Tkinter import * > > >This is the problem. In Python v3 they changed the name of the Tkinter module from? Tkinter to tkinter(no caps). I think it was just to make the name more consistent with? other modules... The result is you need to change your import to be from tkinter import * For the second part of the question.. I don't know which font I am using but I think its default font??OK, So in that case how are you running the program? Are you using IDLE or a CMD shell window?? Or something else? One of the problems of using tabs, and of printing directly in general, is that the? program may be displaying in many different environments and therefore with different fonts.? You therefore have limited control over the output. That's why generating an HTML page which? can have font information embedded into it and use tables etc to control layout is a more reliable? option if you need precise control of layout. If precise control is not so necessary and you think the font will be monospaced then you can? do some things in a print statement that will help, just be aware that it may not be 100% effective. while sMainContinue == "y"or sMainContinue =="yes" or sMainContinue =="YES"or sMainContinue =="Y": > >? ? userMainInput = (input("Please select one option from menu: ")) > >You are making this hard for yourself./ Its usually better to convert the input to lowercase? (or uppercase if you prefer!) and then compare. So your line above could be: while sMainContinue.lower() in ('y','yes'): Also in the input() line you don't need the outer set of parens. But see below... #Robust Options: if input is a letter > >? ? if userMainInput.isdigit(): >? ? ? ? userInput = int(userMainInput)Again its more common in Python to just do the conversion at the input stage and catch an? exception?if the data is bad., so that would look like ? ?try: ? ? ? userInput = int( input("Please select one option from menu: ") ) ? ?except ValueError: ? ? ? ?# deal with non numeric input here ? ?? #Options1 >? ? ? ? if userInput == 1: >? ? ? ? ? ? print("\n********Road Information**********") >? ? ? ? ? ? print("Road Name","Speed",sep = "\t\t") >? ? ? ? ? ? for key,value in Dic.items(): >? ? ? ? ? ? ? ? print(key,value,sep = "\t\t")And here is the display part and it relies on tabs. Tabs work on fixed column positions so to be? consistent you would need to check the length of the strings and insert the correct number of tabs? depending on whether the string was shorter or longer. In your case it could be anywhere from? 1 tab to 3 tabs... That's messy and using tabs for formatting like that is not recommended. Instead Python offers a formatting mechanism that you can apply to a string before it is? printed which gives you much more control over spacing and justification etc. You could read about it in the official docs but there is a more accessible tutorial here: http://infohost.nmt.edu/tcc/help/pubs/python/web/new-str-format.html The key is to use fixed length string fields to output your data. You may optionally choose to left justify the name and right justify the speeds,? or you could just left justify everything. The choice is yours. But remember format() still relies on the user having monospaced fonts for it to work properly. HTH, --? Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos? -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Sat Nov 16 15:01:46 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 17 Nov 2013 00:01:46 +1000 Subject: [Tutor] Need help on Python API programmig In-Reply-To: References: Message-ID: Hi Sourav, Please use "Reply all" when you reply an email so that everyone else also gets your messages and your chances of getting better help increases. On Sat, Nov 16, 2013 at 3:35 PM, Sourav Biswas wrote: > Hi Amit, > > Yes I know, the question is not quite good. Currently I am trying to learn > web API programming with Python. The ultimate goal is work with OpenStack > API. > > Can you please let me know, how to start on this. > > Thanks for the reply and thanks in advance. > Sorry, I certainly didn't mean that your question was "not good". Now that you have mentioned what specifically you are looking to learn, it becomes slightly easier to make some suggestions. I don't have any personal experience with OpenStack API. However, looking at [1], it seems like you will be mostly dealing with making HTTP requests and reading responses. There are couple of standard library modules such as urlllib2 and httplib that may be useful to you. However, in this case, you would certainly benefit from directly learning to use Requests [2]. Note that however, you will need to be familiar with Python data structures such as dictionaries and know how to work with JSON data ( please see the 'json' standard module). [1] http://docs.openstack.org/api/quick-start/content/ [2]http://www.python-requests.org/en/latest/ I am hoping those prove helpful. All the best, Amit. -- http://echorand.me From florinvlad.olariu at gmail.com Sat Nov 16 12:02:40 2013 From: florinvlad.olariu at gmail.com (Vlad Olariu) Date: Sat, 16 Nov 2013 12:02:40 +0100 Subject: [Tutor] Tutor Digest, Vol 117, Issue 25 In-Reply-To: References: Message-ID: is this active? 2013/11/16 > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://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: TypeError: generatePersonID() takes exactly 1 argument (0 > given) (Suhas Bhairav) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 16 Nov 2013 08:58:54 +0530 > From: Suhas Bhairav > To: Alex Kleider , "tutor at python.org" > > Subject: Re: [Tutor] TypeError: generatePersonID() takes exactly 1 > argument (0 given) > Message-ID: > Content-Type: text/plain; charset="iso-8859-1" > > Hello, > In your program, when you're calling generatePersonID(), you need to pass > an argument to the function i.e. the value of fullName.This is because when > you're defining the function generatePersonID(), it is > generatePersonID(fullName) and not just generatePersonID(). So you have > pass an arguments while you're calling it. > Eg:def main(): getUserInput () generatePersonID ("Suhas") > > RegardsSuhas > > > Date: Thu, 14 Nov 2013 09:24:50 -0800 > > From: akleider at sonic.net > > To: tutor at python.org > > Subject: Re: [Tutor] TypeError: generatePersonID() takes exactly 1 > argument (0 given) > > > > On 2013-11-14 07:54, Thabile Rampa wrote: > > > Hi, > > > > > > So I'm learning how to define my own functions, and in an exercise I > > > was given, I get this error: > > > > > > Traceback (most recent call last): > > > File "X:/X/xxx/Xxxxx/function_practice.py", line 36, in > > > main () > > > File "X:/X/xxx/Xxxxx/function_practice.py/function_practice.py > > > [1]", line 34, in main > > > generatePersonID () > > > TypeError: generatePersonID() takes exactly 1 argument (0 given) > > > > > > Here is the code: > > > > > > def getUserInput(): > > > """ > > > Get input from the user, i.e fullname, grossSalary, costs. > > > Returns: fullName, grossSalary, costs > > > """ > > > > > > grossSalary =None ; > > > costs =None > > > fullName="" > > > > > > while not fullName: > > > > > > fullName = raw_input ("First and Last Names: ") > > > > > > while not grossSalary: > > > #TODO > > > grossSalary = int (raw_input ("Annual Gross Salary: ")) > > > > > > while not costs: > > > #TODO > > > costs = int(raw_input ("Yearly costs: ")) > > > > > > return fullName, grossSalary, costs > > > > > > def generatePersonID (fullName): > > > """generates unique ID""" > > > global id > > > id = (fullName) + 1 > > > personID = str (id) + fullName > > > return personID > > > > > > def main (): > > > getUserInput () > > > generatePersonID () > > > > > > main () > > > > > > raw_input ("Press the enter key to exit.") > > > > You define 'generatePersonID' as a function that requires one parameter > > but you do not give it a parameter when you call it with in your 'main' > > function. That's exactly what your error message is trying to tell you. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131116/c172caf5/attachment-0001.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 117, Issue 25 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Sat Nov 16 16:10:22 2013 From: wprins at gmail.com (Walter Prins) Date: Sat, 16 Nov 2013 15:10:22 +0000 Subject: [Tutor] Is this list active? Message-ID: Hi, On 16 November 2013 11:02, Vlad Olariu wrote: > is this active? > > Yes. (Please don't reply to digest posts without at least trimming it and adjusting the subject as appropriate.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 16 21:04:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Nov 2013 20:04:38 +0000 Subject: [Tutor] Tutor Digest, Vol 117, Issue 25 In-Reply-To: References: Message-ID: On 16/11/13 11:02, Vlad Olariu wrote: > is this active? If you mean the mailing list then yes, but not massively busy and there is an archive of posts that you can search/review. If you mean did this mail get here then again yes but via the moderator queue so a little later than most. Otherwise you'll need to be more specific. Speaking of which we appreciate knowing, when you post, what OS and Python version you are using, what exactly the problem is (not just "its broke") and the full printout of any error messages not a summary. Shortish code listing illustrating the problem are welcome too. Finally, use a meaningful subject line and please do not send the entire digest contents (only one message in this case but can be much longer) since some people pay by the byte and others are earn a living by the minute so don't want to waste time looking for clues. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From byron.ruffin at g.austincc.edu Sat Nov 16 22:20:52 2013 From: byron.ruffin at g.austincc.edu (Byron Ruffin) Date: Sat, 16 Nov 2013 15:20:52 -0600 Subject: [Tutor] basic function concept Message-ID: def main(x, y, z): print (x, y, z) def funct(): x = 1 y = 2 z = 3 return x, y, z main() Can someone tell me why main is not being given any arguments? -------------- next part -------------- An HTML attachment was scrubbed... URL: From reuben.dlink at gmail.com Sat Nov 16 18:13:13 2013 From: reuben.dlink at gmail.com (reutest) Date: Sat, 16 Nov 2013 09:13:13 -0800 (PST) Subject: [Tutor] Class attribute error Message-ID: <1384621993288-5039199.post@n6.nabble.com> class myclass(): def test(self): print "print this line" if __name__ == '__main__': myclass.run() -- View this message in context: http://python.6.x6.nabble.com/Class-attribute-error-tp5039199.html Sent from the Python - tutor mailing list archive at Nabble.com. From nik at naturalnet.de Sun Nov 17 00:56:10 2013 From: nik at naturalnet.de (Dominik George) Date: Sun, 17 Nov 2013 00:56:10 +0100 Subject: [Tutor] basic function concept In-Reply-To: References: Message-ID: <20131116235610.GT5095@keks.naturalnet.de> > main() > > Can someone tell me why main is not being given any arguments? Because you didn't write any there. -nik -- Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From nik at naturalnet.de Sun Nov 17 00:55:11 2013 From: nik at naturalnet.de (Dominik George) Date: Sun, 17 Nov 2013 00:55:11 +0100 Subject: [Tutor] Class attribute error In-Reply-To: <1384621993288-5039199.post@n6.nabble.com> References: <1384621993288-5039199.post@n6.nabble.com> Message-ID: <20131116235510.GS5095@keks.naturalnet.de> On Sat, Nov 16, 2013 at 09:13:13AM -0800, reutest wrote: > class myclass(): > > def test(self): > print "print this line" > > > if __name__ == '__main__': > myclass.run() Is that a question? If I were to guess, I'd say you should have asked "Why does this say that myclass does not havea run method?". Then the simple answer is: Because, well, it doesn't! Why do you expect it to have one? -nik -- Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From alan.gauld at btinternet.com Sun Nov 17 01:51:47 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Nov 2013 00:51:47 +0000 Subject: [Tutor] basic function concept In-Reply-To: References: Message-ID: On 16/11/13 21:20, Byron Ruffin wrote: > def main(x, y, z): > > print (x, y, z) > > def funct(): > x = 1 > y = 2 > z = 3 > > return x, y, z > > > main() > > > Can someone tell me why main is not being given any arguments? Because somebody made a mistake. I don't know if this is your code or something you found in a book or web page but whichever it's an error and Python won't run it. Also funct() is a waste of space since its never used... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sun Nov 17 01:54:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Nov 2013 00:54:40 +0000 Subject: [Tutor] Class attribute error In-Reply-To: <1384621993288-5039199.post@n6.nabble.com> References: <1384621993288-5039199.post@n6.nabble.com> Message-ID: On 16/11/13 17:13, reutest wrote: > class myclass(): > > def test(self): > print "print this line" > > > if __name__ == '__main__': > myclass.run() If you have a question it helps if you ask it rather than have us guess. In this case I'm guessing you got an error and you are wondering why? It's because you are calling the run() class method of myclass. And there is no such method. If that's not your question please post again with a bit more of a clue about what you want to know. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From akleider at sonic.net Sun Nov 17 06:16:54 2013 From: akleider at sonic.net (Alex Kleider) Date: Sat, 16 Nov 2013 21:16:54 -0800 Subject: [Tutor] basic function concept In-Reply-To: References: Message-ID: On 2013-11-16 13:20, Byron Ruffin wrote: > def main(x, y, z): > > ??? print (x, y, z) > > def funct(): > ??? x = 1 > ??? y = 2 > ??? z = 3 > > ??? return x, y, z > > main() > > Can someone tell me why main is not being given any arguments? Because you didn't give it any. Try main(funct()) instead. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From amitsaha.in at gmail.com Sun Nov 17 08:36:27 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 17 Nov 2013 17:36:27 +1000 Subject: [Tutor] Fwd: Need help on Python API programmig In-Reply-To: References: Message-ID: Hi John, Perhaps your answer was directed towards Sourav. CCing tutor. ---------- Forwarded message ---------- From: John Steedman Date: Sun, Nov 17, 2013 at 6:26 AM Subject: Re: [Tutor] Need help on Python API programmig To: Amit Saha Hi Amit, I've been using Django Rest Framework for developing a database-driven API. If you choose to follow their tutorial, you may accomplish your goal quite quickly while learning a lot about web APIs and quite good engineering at the same time. Tastypie is a similar option. John On Fri, Nov 15, 2013 at 9:14 PM, Amit Saha wrote: > Hello Sourav, > > On 16/11/2013 6:53 AM, "Sourav Biswas" wrote: >> >> Hi All, >> >> This is my first post. I want to learn API programming with Python. I have >> basic knowledge of Python Programming. Could you please let me know the >> starting points for this programming. > > Since your question is fairly vague, could you please describe what you are > trying to learn? An API is an interface. It can be an operating system > interface, a vehicle web API or simply a web API. > > Some more details will be a lot of help. > > Best, Amit. > > -- http://echorand.me From byron.ruffin at g.austincc.edu Sun Nov 17 02:00:47 2013 From: byron.ruffin at g.austincc.edu (Byron Ruffin) Date: Sat, 16 Nov 2013 19:00:47 -0600 Subject: [Tutor] loop running twice? Message-ID: def main(): goal, apr, deposit = getSavingsDetails() determineMonthsTilSaved( goal, apr, deposit ) months = determineMonthsTilSaved(goal, apr, deposit) summarize( months ) def getSavingsDetails(): """ goal = float( input( "Principal sought? $" ) ) apr = float( input( "Interest rate? " ) ) deposit = float( input( "Deposit? $" ) ) """ goal = 1000.0 apr = .05 deposit = 100 return goal, apr, deposit def determineMonthsTilSaved( goal, apr, deposit ): months = 0 saved = 0 totalInterest = 0.0 while saved < goal: interest = saved * apr / 12 totalInterest += interest saved += (deposit + interest) months += 1 print( months, ("%.2f" % saved), ("%.2f" % totalInterest) ) return months def summarize( months ): print( "Saved! It took ", months // 12, "years and", months % 12, "months." ) main() When this is run it appears that determineMonthsTilSaved is running twice before the loop ends. It is supposed to run until saved > than goal, but look at the output. It runs again even after saved > goal. Help please? -------------- next part -------------- An HTML attachment was scrubbed... URL: From welcome.to.eye.o.rama at gmail.com Sun Nov 17 07:31:38 2013 From: welcome.to.eye.o.rama at gmail.com (John Aten) Date: Sun, 17 Nov 2013 00:31:38 -0600 Subject: [Tutor] basic function concept In-Reply-To: References: Message-ID: <478731FC-D3FA-4AC4-A328-838D7444442E@gmail.com> Too bad that doesn't work. On Nov 16, 2013, at 11:16 PM, Alex Kleider wrote: > On 2013-11-16 13:20, Byron Ruffin wrote: >> def main(x, y, z): >> print (x, y, z) >> def funct(): >> x = 1 >> y = 2 >> z = 3 >> return x, y, z >> main() >> Can someone tell me why main is not being given any arguments? > > Because you didn't give it any. > Try > main(funct()) > instead. > > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From sganeshhcu at gmail.com Sun Nov 17 09:46:43 2013 From: sganeshhcu at gmail.com (sree ganesh) Date: Sun, 17 Nov 2013 09:46:43 +0100 Subject: [Tutor] looking for python developper Message-ID: Hi I am looking for python developer who can work from home per day 2 hours. if any one has interest please let me know. Regards Ganesh On 17 November 2013 09:40, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://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. Class attribute error (reutest) > 2. Re: basic function concept (Dominik George) > 3. Re: Class attribute error (Dominik George) > 4. Re: basic function concept (Alan Gauld) > 5. Re: Class attribute error (Alan Gauld) > 6. Re: basic function concept (Alex Kleider) > 7. Fwd: Need help on Python API programmig (Amit Saha) > 8. loop running twice? (Byron Ruffin) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 16 Nov 2013 09:13:13 -0800 (PST) > From: reutest > To: tutor at python.org > Subject: [Tutor] Class attribute error > Message-ID: <1384621993288-5039199.post at n6.nabble.com> > Content-Type: text/plain; charset=us-ascii > > class myclass(): > > def test(self): > print "print this line" > > > if __name__ == '__main__': > myclass.run() > > > > -- > View this message in context: > http://python.6.x6.nabble.com/Class-attribute-error-tp5039199.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > > ------------------------------ > > Message: 2 > Date: Sun, 17 Nov 2013 00:56:10 +0100 > From: Dominik George > To: Byron Ruffin > Cc: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: <20131116235610.GT5095 at keks.naturalnet.de> > Content-Type: text/plain; charset="utf-8" > > > main() > > > > Can someone tell me why main is not being given any arguments? > > Because you didn't write any there. > > -nik > > -- > Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! > > PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: signature.asc > Type: application/pgp-signature > Size: 905 bytes > Desc: Digital signature > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131117/eef9967c/attachment-0001.sig > > > > ------------------------------ > > Message: 3 > Date: Sun, 17 Nov 2013 00:55:11 +0100 > From: Dominik George > To: reutest > Cc: tutor at python.org > Subject: Re: [Tutor] Class attribute error > Message-ID: <20131116235510.GS5095 at keks.naturalnet.de> > Content-Type: text/plain; charset="utf-8" > > On Sat, Nov 16, 2013 at 09:13:13AM -0800, reutest wrote: > > class myclass(): > > > > def test(self): > > print "print this line" > > > > > > if __name__ == '__main__': > > myclass.run() > > Is that a question? > > If I were to guess, I'd say you should have asked "Why does this say > that myclass does not havea run method?". Then the simple answer is: > Because, well, it doesn't! Why do you expect it to have one? > > -nik > > -- > Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! > > PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: signature.asc > Type: application/pgp-signature > Size: 905 bytes > Desc: Digital signature > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131117/5d249c0d/attachment-0001.sig > > > > ------------------------------ > > Message: 4 > Date: Sun, 17 Nov 2013 00:51:47 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 16/11/13 21:20, Byron Ruffin wrote: > > def main(x, y, z): > > > > print (x, y, z) > > > > def funct(): > > x = 1 > > y = 2 > > z = 3 > > > > return x, y, z > > > > > > main() > > > > > > Can someone tell me why main is not being given any arguments? > > Because somebody made a mistake. > I don't know if this is your code or something you found in a > book or web page but whichever it's an error and Python won't > run it. > > Also funct() is a waste of space since its never used... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 5 > Date: Sun, 17 Nov 2013 00:54:40 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Class attribute error > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 16/11/13 17:13, reutest wrote: > > class myclass(): > > > > def test(self): > > print "print this line" > > > > > > if __name__ == '__main__': > > myclass.run() > > > If you have a question it helps if you ask it rather than have us guess. > > In this case I'm guessing you got an error and you are wondering why? > > It's because you are calling the run() class method of myclass. And > there is no such method. > > If that's not your question please post again with a bit more of a clue > about what you want to know. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 6 > Date: Sat, 16 Nov 2013 21:16:54 -0800 > From: Alex Kleider > To: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 2013-11-16 13:20, Byron Ruffin wrote: > > def main(x, y, z): > > > > ??? print (x, y, z) > > > > def funct(): > > ??? x = 1 > > ??? y = 2 > > ??? z = 3 > > > > ??? return x, y, z > > > > main() > > > > Can someone tell me why main is not being given any arguments? > > Because you didn't give it any. > Try > main(funct()) > instead. > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > Message: 7 > Date: Sun, 17 Nov 2013 17:36:27 +1000 > From: Amit Saha > To: "tutor at python.org" > Subject: [Tutor] Fwd: Need help on Python API programmig > Message-ID: > < > CANODV3kXPNTYs093fkH4q+gEBG9ixpBrj9f-LYyGPaUh_8nORw at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hi John, > > Perhaps your answer was directed towards Sourav. > > CCing tutor. > > > > > ---------- Forwarded message ---------- > From: John Steedman > Date: Sun, Nov 17, 2013 at 6:26 AM > Subject: Re: [Tutor] Need help on Python API programmig > To: Amit Saha > > > Hi Amit, > > I've been using Django Rest Framework for developing a database-driven > API. If you choose to follow their tutorial, you may accomplish your > goal quite quickly while learning a lot about web APIs and quite good > engineering at the same time. Tastypie is a similar option. > > John > > On Fri, Nov 15, 2013 at 9:14 PM, Amit Saha wrote: > > Hello Sourav, > > > > On 16/11/2013 6:53 AM, "Sourav Biswas" wrote: > >> > >> Hi All, > >> > >> This is my first post. I want to learn API programming with Python. I > have > >> basic knowledge of Python Programming. Could you please let me know the > >> starting points for this programming. > > > > Since your question is fairly vague, could you please describe what you > are > > trying to learn? An API is an interface. It can be an operating system > > interface, a vehicle web API or simply a web API. > > > > Some more details will be a lot of help. > > > > Best, Amit. > > > > > > > > -- > http://echorand.me > > > ------------------------------ > > Message: 8 > Date: Sat, 16 Nov 2013 19:00:47 -0600 > From: Byron Ruffin > To: tutor at python.org > Subject: [Tutor] loop running twice? > Message-ID: > < > CAOsa8feQWPeKkYof9u69niUr8Dut-kj-2fKxdL0kYHTp2-H1yw at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > def main(): > > goal, apr, deposit = getSavingsDetails() > determineMonthsTilSaved( goal, apr, deposit ) > > months = determineMonthsTilSaved(goal, apr, deposit) > > summarize( months ) > > def getSavingsDetails(): > """ > goal = float( input( "Principal sought? $" ) ) > apr = float( input( "Interest rate? " ) ) > deposit = float( input( "Deposit? $" ) ) > """ > goal = 1000.0 > apr = .05 > deposit = 100 > return goal, apr, deposit > > def determineMonthsTilSaved( goal, apr, deposit ): > months = 0 > saved = 0 > totalInterest = 0.0 > > > > > while saved < goal: > interest = saved * apr / 12 > totalInterest += interest > saved += (deposit + interest) > months += 1 > print( months, ("%.2f" % saved), ("%.2f" % totalInterest) ) > > return months > > def summarize( months ): > print( "Saved! It took ", months // 12, "years and", months % 12, > "months." ) > > main() > > > When this is run it appears that determineMonthsTilSaved is running twice > before the loop ends. It is supposed to run until saved > than goal, but > look at the output. It runs again even after saved > goal. Help please? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131116/26f2f3b0/attachment.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 117, Issue 28 > ************************************** > -- Cheers, Sree Ganesh.T -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 17 09:47:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Nov 2013 08:47:01 +0000 Subject: [Tutor] basic function concept In-Reply-To: References: Message-ID: On 17/11/13 05:16, Alex Kleider wrote: > On 2013-11-16 13:20, Byron Ruffin wrote: >> def main(x, y, z): >> print (x, y, z) >> >> def funct(): >> x = 1 >> y = 2 >> z = 3 >> return x, y, z >> >> main() >> >> Can someone tell me why main is not being given any arguments? > > Because you didn't give it any. > Try > main(funct()) make that main(*funct()) funct returns a tuple so you need to unpack it in the main() argument list using the * notation. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sun Nov 17 09:50:31 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Nov 2013 08:50:31 +0000 Subject: [Tutor] loop running twice? In-Reply-To: References: Message-ID: On 17/11/13 01:00, Byron Ruffin wrote: > When this is run it appears that determineMonthsTilSaved is > running twice before the loop ends. It is supposed to run > until saved than goal, but look at the output. You haven't sent the output, just the code... > It runs again even after saved goal. > Help please? Look closely at main() > def main(): > > goal, apr, deposit = getSavingsDetails() > determineMonthsTilSaved( goal, apr, deposit ) > > months = determineMonthsTilSaved(goal, apr, deposit) You call the function twice, so it runs twice. > def determineMonthsTilSaved( goal, apr, deposit ): > months = 0 > saved = 0 > totalInterest = 0.0 > > while saved < goal: > interest = saved * apr / 12 > totalInterest += interest > saved += (deposit + interest) > months += 1 > print( months, ("%.2f" % saved), ("%.2f" % totalInterest) ) > > return months -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Sun Nov 17 13:19:44 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 17 Nov 2013 12:19:44 +0000 Subject: [Tutor] basic function concept In-Reply-To: <478731FC-D3FA-4AC4-A328-838D7444442E@gmail.com> References: <478731FC-D3FA-4AC4-A328-838D7444442E@gmail.com> Message-ID: On 17/11/2013 06:31, John Aten wrote: > Too bad that doesn't work. > > On Nov 16, 2013, at 11:16 PM, Alex Kleider wrote: > >> On 2013-11-16 13:20, Byron Ruffin wrote: >>> def main(x, y, z): >>> print (x, y, z) >>> def funct(): >>> x = 1 >>> y = 2 >>> z = 3 >>> return x, y, z >>> main() >>> Can someone tell me why main is not being given any arguments? >> >> Because you didn't give it any. >> Try >> main(funct()) >> instead. >> 1) Please don't top post. 2) Your statement isn't of much use on a tutor mailing list so why not explain why and show the corrected code? -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From reuben.dlink at gmail.com Sun Nov 17 09:57:44 2013 From: reuben.dlink at gmail.com (Reuben) Date: Sun, 17 Nov 2013 14:27:44 +0530 Subject: [Tutor] Class attribute error In-Reply-To: <20131116235510.GS5095@keks.naturalnet.de> References: <1384621993288-5039199.post@n6.nabble.com> <20131116235510.GS5095@keks.naturalnet.de> Message-ID: Hi, Thanks for correcting me. The solutions mentioned by Dominik and Alan have simplified the concept to me now. Regards, Reuben On Sun, Nov 17, 2013 at 5:25 AM, Dominik George wrote: > On Sat, Nov 16, 2013 at 09:13:13AM -0800, reutest wrote: > > class myclass(): > > > > def test(self): > > print "print this line" > > > > > > if __name__ == '__main__': > > myclass.run() > > Is that a question? > > If I were to guess, I'd say you should have asked "Why does this say > that myclass does not havea run method?". Then the simple answer is: > Because, well, it doesn't! Why do you expect it to have one? > > -nik > > -- > Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! > > PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From reuben.dlink at gmail.com Sun Nov 17 13:24:39 2013 From: reuben.dlink at gmail.com (Reuben) Date: Sun, 17 Nov 2013 17:54:39 +0530 Subject: [Tutor] Link required for difference between class and object Message-ID: Hi All, It would be nice if someone could forward a link which explains classes and object. I am still struggling to understand classes and objects better. Regards, Reuben -------------- next part -------------- An HTML attachment was scrubbed... URL: From satheesan.varier at gmail.com Sun Nov 17 13:19:50 2013 From: satheesan.varier at gmail.com (Satheesan Varier) Date: Sun, 17 Nov 2013 07:19:50 -0500 Subject: [Tutor] Tutor Digest, Vol 117, Issue 28 In-Reply-To: References: Message-ID: class myclass(): def test(self): print "print this line" if __name__ == '__main__': myclass.run() You can do the test run with an instance of that class, as follows: >>> class myclass(): def test(self): print "print this line" >>> k=myclass() >>> myclass.test(k) print this line On Sun, Nov 17, 2013 at 3:40 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://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. Class attribute error (reutest) > 2. Re: basic function concept (Dominik George) > 3. Re: Class attribute error (Dominik George) > 4. Re: basic function concept (Alan Gauld) > 5. Re: Class attribute error (Alan Gauld) > 6. Re: basic function concept (Alex Kleider) > 7. Fwd: Need help on Python API programmig (Amit Saha) > 8. loop running twice? (Byron Ruffin) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 16 Nov 2013 09:13:13 -0800 (PST) > From: reutest > To: tutor at python.org > Subject: [Tutor] Class attribute error > Message-ID: <1384621993288-5039199.post at n6.nabble.com> > Content-Type: text/plain; charset=us-ascii > > class myclass(): > > def test(self): > print "print this line" > > > if __name__ == '__main__': > myclass.run() > > > > -- > View this message in context: > http://python.6.x6.nabble.com/Class-attribute-error-tp5039199.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > > ------------------------------ > > Message: 2 > Date: Sun, 17 Nov 2013 00:56:10 +0100 > From: Dominik George > To: Byron Ruffin > Cc: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: <20131116235610.GT5095 at keks.naturalnet.de> > Content-Type: text/plain; charset="utf-8" > > > main() > > > > Can someone tell me why main is not being given any arguments? > > Because you didn't write any there. > > -nik > > -- > Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! > > PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: signature.asc > Type: application/pgp-signature > Size: 905 bytes > Desc: Digital signature > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131117/eef9967c/attachment-0001.sig > > > > ------------------------------ > > Message: 3 > Date: Sun, 17 Nov 2013 00:55:11 +0100 > From: Dominik George > To: reutest > Cc: tutor at python.org > Subject: Re: [Tutor] Class attribute error > Message-ID: <20131116235510.GS5095 at keks.naturalnet.de> > Content-Type: text/plain; charset="utf-8" > > On Sat, Nov 16, 2013 at 09:13:13AM -0800, reutest wrote: > > class myclass(): > > > > def test(self): > > print "print this line" > > > > > > if __name__ == '__main__': > > myclass.run() > > Is that a question? > > If I were to guess, I'd say you should have asked "Why does this say > that myclass does not havea run method?". Then the simple answer is: > Because, well, it doesn't! Why do you expect it to have one? > > -nik > > -- > Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! > > PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: signature.asc > Type: application/pgp-signature > Size: 905 bytes > Desc: Digital signature > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131117/5d249c0d/attachment-0001.sig > > > > ------------------------------ > > Message: 4 > Date: Sun, 17 Nov 2013 00:51:47 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 16/11/13 21:20, Byron Ruffin wrote: > > def main(x, y, z): > > > > print (x, y, z) > > > > def funct(): > > x = 1 > > y = 2 > > z = 3 > > > > return x, y, z > > > > > > main() > > > > > > Can someone tell me why main is not being given any arguments? > > Because somebody made a mistake. > I don't know if this is your code or something you found in a > book or web page but whichever it's an error and Python won't > run it. > > Also funct() is a waste of space since its never used... > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 5 > Date: Sun, 17 Nov 2013 00:54:40 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Class attribute error > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 16/11/13 17:13, reutest wrote: > > class myclass(): > > > > def test(self): > > print "print this line" > > > > > > if __name__ == '__main__': > > myclass.run() > > > If you have a question it helps if you ask it rather than have us guess. > > In this case I'm guessing you got an error and you are wondering why? > > It's because you are calling the run() class method of myclass. And > there is no such method. > > If that's not your question please post again with a bit more of a clue > about what you want to know. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 6 > Date: Sat, 16 Nov 2013 21:16:54 -0800 > From: Alex Kleider > To: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 2013-11-16 13:20, Byron Ruffin wrote: > > def main(x, y, z): > > > > ??? print (x, y, z) > > > > def funct(): > > ??? x = 1 > > ??? y = 2 > > ??? z = 3 > > > > ??? return x, y, z > > > > main() > > > > Can someone tell me why main is not being given any arguments? > > Because you didn't give it any. > Try > main(funct()) > instead. > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > Message: 7 > Date: Sun, 17 Nov 2013 17:36:27 +1000 > From: Amit Saha > To: "tutor at python.org" > Subject: [Tutor] Fwd: Need help on Python API programmig > Message-ID: > < > CANODV3kXPNTYs093fkH4q+gEBG9ixpBrj9f-LYyGPaUh_8nORw at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > Hi John, > > Perhaps your answer was directed towards Sourav. > > CCing tutor. > > > > > ---------- Forwarded message ---------- > From: John Steedman > Date: Sun, Nov 17, 2013 at 6:26 AM > Subject: Re: [Tutor] Need help on Python API programmig > To: Amit Saha > > > Hi Amit, > > I've been using Django Rest Framework for developing a database-driven > API. If you choose to follow their tutorial, you may accomplish your > goal quite quickly while learning a lot about web APIs and quite good > engineering at the same time. Tastypie is a similar option. > > John > > On Fri, Nov 15, 2013 at 9:14 PM, Amit Saha wrote: > > Hello Sourav, > > > > On 16/11/2013 6:53 AM, "Sourav Biswas" wrote: > >> > >> Hi All, > >> > >> This is my first post. I want to learn API programming with Python. I > have > >> basic knowledge of Python Programming. Could you please let me know the > >> starting points for this programming. > > > > Since your question is fairly vague, could you please describe what you > are > > trying to learn? An API is an interface. It can be an operating system > > interface, a vehicle web API or simply a web API. > > > > Some more details will be a lot of help. > > > > Best, Amit. > > > > > > > > -- > http://echorand.me > > > ------------------------------ > > Message: 8 > Date: Sat, 16 Nov 2013 19:00:47 -0600 > From: Byron Ruffin > To: tutor at python.org > Subject: [Tutor] loop running twice? > Message-ID: > < > CAOsa8feQWPeKkYof9u69niUr8Dut-kj-2fKxdL0kYHTp2-H1yw at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > def main(): > > goal, apr, deposit = getSavingsDetails() > determineMonthsTilSaved( goal, apr, deposit ) > > months = determineMonthsTilSaved(goal, apr, deposit) > > summarize( months ) > > def getSavingsDetails(): > """ > goal = float( input( "Principal sought? $" ) ) > apr = float( input( "Interest rate? " ) ) > deposit = float( input( "Deposit? $" ) ) > """ > goal = 1000.0 > apr = .05 > deposit = 100 > return goal, apr, deposit > > def determineMonthsTilSaved( goal, apr, deposit ): > months = 0 > saved = 0 > totalInterest = 0.0 > > > > > while saved < goal: > interest = saved * apr / 12 > totalInterest += interest > saved += (deposit + interest) > months += 1 > print( months, ("%.2f" % saved), ("%.2f" % totalInterest) ) > > return months > > def summarize( months ): > print( "Saved! It took ", months // 12, "years and", months % 12, > "months." ) > > main() > > > When this is run it appears that determineMonthsTilSaved is running twice > before the loop ends. It is supposed to run until saved > than goal, but > look at the output. It runs again even after saved > goal. Help please? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131116/26f2f3b0/attachment.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 117, Issue 28 > ************************************** > -- Warm regards. Satheesan Varier 860 (970) 2732 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 17 16:23:06 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Nov 2013 15:23:06 +0000 Subject: [Tutor] Call Attribute error - Was Re: Tutor Digest, Vol 117, Issue 28 In-Reply-To: References: Message-ID: On 17/11/13 12:19, Satheesan Varier wrote: > class myclass(): > def test(self): > print "print this line" > > if __name__ == '__main__': > myclass.run() > > You can do the test run with an instance of that class, as follows: > > >>> k=myclass() > > >>> myclass.test(k) > print this line Or more conventionally k.test() Please don't post the entire digest when replying, remove any irrelevant material. Some people pay by the byte and don't want to pay for stuff they've already seen. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From joel.goldstick at gmail.com Sun Nov 17 16:29:48 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 17 Nov 2013 10:29:48 -0500 Subject: [Tutor] Link required for difference between class and object In-Reply-To: References: Message-ID: On Sun, Nov 17, 2013 at 7:24 AM, Reuben wrote: > Hi All, > > It would be nice if someone could forward a link which explains classes and > object. > I am still struggling to understand classes and objects better. > > Regards, > Reuben > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > Have you looked here yet? http://docs.python.org/2/tutorial/classes.html -- Joel Goldstick http://joelgoldstick.com From breamoreboy at yahoo.co.uk Sun Nov 17 16:53:49 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 17 Nov 2013 15:53:49 +0000 Subject: [Tutor] Link required for difference between class and object In-Reply-To: References: Message-ID: On 17/11/2013 12:24, Reuben wrote: > Hi All, > > It would be nice if someone could forward a link which explains classes > and object. > I am still struggling to understand classes and objects better. > > Regards, > Reuben > An extremely simplistic answer to get you going, a class is the template that you have in your source code, an object is an instance of your class that you create in your source code. class Myclass(): #the class, the template pass myobject = Myclass() # the instance, the object -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From akleider at sonic.net Sun Nov 17 17:54:01 2013 From: akleider at sonic.net (Alex Kleider) Date: Sun, 17 Nov 2013 08:54:01 -0800 Subject: [Tutor] basic function concept In-Reply-To: References: Message-ID: <4d80fa567c0764c1441b8ea6dd9f2462@sonic.net> On 2013-11-17 00:47, Alan Gauld wrote: > On 17/11/13 05:16, Alex Kleider wrote: >> On 2013-11-16 13:20, Byron Ruffin wrote: >>> def main(x, y, z): >>> print (x, y, z) >>> >>> def funct(): >>> x = 1 >>> y = 2 >>> z = 3 >>> return x, y, z >>> >>> main() >>> >>> Can someone tell me why main is not being given any arguments? >> >> Because you didn't give it any. >> Try >> main(funct()) > > make that > > main(*funct()) > > funct returns a tuple so you need to unpack it in the main() > argument list using the * notation. Much more elegant than my 'corrected' version. Thanks for the suggestion. From akleider at sonic.net Sun Nov 17 17:51:48 2013 From: akleider at sonic.net (Alex Kleider) Date: Sun, 17 Nov 2013 08:51:48 -0800 Subject: [Tutor] basic function concept In-Reply-To: <478731FC-D3FA-4AC4-A328-838D7444442E@gmail.com> References: <478731FC-D3FA-4AC4-A328-838D7444442E@gmail.com> Message-ID: On 2013-11-16 22:31, John Aten wrote: > Too bad that doesn't work. No, it doesn't. Can you see why? Attached is a version that does work but you'd be better served looking at the two versions you already have and studying the error messages you get when you run them. > > On Nov 16, 2013, at 11:16 PM, Alex Kleider wrote: > >> On 2013-11-16 13:20, Byron Ruffin wrote: >>> def main(x, y, z): >>> print (x, y, z) >>> def funct(): >>> x = 1 >>> y = 2 >>> z = 3 >>> return x, y, z >>> main() >>> Can someone tell me why main is not being given any arguments? >> >> Because you didn't give it any. >> Try >> main(funct()) >> instead. >> >> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> https://mail.python.org/mailman/listinfo/tutor >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: func0args Type: text/x-python Size: 441 bytes Desc: not available URL: From alan.gauld at btinternet.com Sun Nov 17 18:20:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Nov 2013 17:20:56 +0000 Subject: [Tutor] Link required for difference between class and object In-Reply-To: References: Message-ID: On 17/11/13 12:24, Reuben wrote: > Hi All, > > It would be nice if someone could forward a link which explains classes > and object. > I am still struggling to understand classes and objects better. You can try the OOP topic in my tutorial if you like... In a nutshell: A class is a type, like string or integer are types. An instance is a 'value' of that type, like 'foo' or 42. Classes define methods (or operations) that you can apply to the instances, like 'foo'.upper(). You can create your own data types by writing classes. But nearly all you should ever do with a class itself is create instances of it (at least as a beginner). Most of the work is done by the instances, by calling their methods. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From ayodejirotibi at aol.com Mon Nov 18 07:57:20 2013 From: ayodejirotibi at aol.com (Ayo Rotibi) Date: Mon, 18 Nov 2013 06:57:20 -0000 Subject: [Tutor] Phython List values Message-ID: <002901cee42b$6e346fe0$4a9d4fa0$@com> Hi, I am a complete newbie to python. I read that an assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory. For instance, if a = [1, 2, 3] and b=a, then b = [1, 2, 3]. However, I discovered that if I change the value in 'a', 'b' does not take the new value. I thought since it is pointing to the same storage as 'a', 'b' should take the new value. Any explanation would be appreciated. Ayo _________________________________ Desire, Dedication, Determination and a little bit of Talent -------------- next part -------------- An HTML attachment was scrubbed... URL: From byron.ruffin at g.austincc.edu Mon Nov 18 04:27:56 2013 From: byron.ruffin at g.austincc.edu (Byron Ruffin) Date: Sun, 17 Nov 2013 21:27:56 -0600 Subject: [Tutor] ideas? Message-ID: Need a little help with finding a process for this: when a string of text is input, for example: abc def. I want to have each letter shift to the right one place in the alphabet. Thus.. abc def would be output as bcd efg. Any ideas on how to do this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From paradox at pobox.com Mon Nov 18 11:49:06 2013 From: paradox at pobox.com (Paradox) Date: Mon, 18 Nov 2013 05:49:06 -0500 Subject: [Tutor] Phython List values :p: In-Reply-To: <002901cee42b$6e346fe0$4a9d4fa0$@com> References: <002901cee42b$6e346fe0$4a9d4fa0$@com> Message-ID: <5289F0A2.3010306@pobox.com> Ayo, On 11/18/2013 01:57 AM, Ayo Rotibi wrote: > > > I read that an assignment with an = on lists does not make a copy. > Instead, assignment makes the two variables point to the one list in > memory. For instance, if a = [1, 2, 3] and b=a, then b = [1, 2, 3]. > > However, I discovered that if I change the value in ?a?, ?b? does not > take the new value. I thought since it is pointing to the same > storage as ?a?, ?b? should take the new value? > > It is not clear to me what code you are running, maybe you could give us the specifics? When I run an assignment like you seem to be talking about I get the expected result (using ipython for an interactive session to demonstrate): In [1]: a=[1,2,3] In [2]: b=a In [3]: b Out[3]: [1, 2, 3] In [4]: a[1]=0 In [5]: a Out[5]: [1, 0, 3] In [6]: b Out[6]: [1, 0, 3] Is that not what you are seeing? If not perhaps you could show us how you are doing the list assignment and changing the list a, what output you are expecting and what output you are getting. thomas From __peter__ at web.de Mon Nov 18 12:00:27 2013 From: __peter__ at web.de (Peter Otten) Date: Mon, 18 Nov 2013 12:00:27 +0100 Subject: [Tutor] ideas? References: Message-ID: Byron Ruffin wrote: > Need a little help with finding a process for this: > > when a string of text is input, for example: abc def. > I want to have each letter shift to the right one place in the alphabet. > Thus.. > abc def would be output as bcd efg. > > Any ideas on how to do this? Have a look at the str.maketrans() and str.translate() methods: >>> trans = str.maketrans("abc", "xyz") >>> "abba cdef".translate(trans) 'xyyx zdef' From alan.gauld at btinternet.com Mon Nov 18 12:01:08 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Nov 2013 11:01:08 +0000 Subject: [Tutor] ideas? In-Reply-To: References: Message-ID: On 18/11/13 03:27, Byron Ruffin wrote: > Need a little help with finding a process for this: > > when a string of text is input, for example: abc def. > I want to have each letter shift to the right one place in the alphabet. > Thus.. > abc def would be output as bcd efg. > > Any ideas on how to do this? Yes, use the ord() function to convert the letters to numbers. Add one and convert back using the chr() function. Check for the special case of 'z'. Consider how to handle upper case letters too. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From oscar.j.benjamin at gmail.com Mon Nov 18 12:03:53 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 18 Nov 2013 11:03:53 +0000 Subject: [Tutor] Phython List values In-Reply-To: <002901cee42b$6e346fe0$4a9d4fa0$@com> References: <002901cee42b$6e346fe0$4a9d4fa0$@com> Message-ID: On 18 November 2013 06:57, Ayo Rotibi wrote: > Hi, Hi, please don't post in HTML. > I am a complete newbie to python. > > I read that an assignment with an = on lists does not make a copy. Instead, > assignment makes the two variables point to the one list in memory. For > instance, if a = [1, 2, 3] and b=a, then b = [1, 2, 3]. This is correct. > However, I discovered that if I change the value in ?a?, ?b? does not take > the new value. I thought since it is pointing to the same storage as ?a?, > ?b? should take the new value? It does take the new value. Here is a demonstration: >>> a = [1, 2, 3] >>> a [1, 2, 3] >>> b = a >>> b [1, 2, 3] >>> a[0] = 'new value' >>> a ['new value', 2, 3] >>> b ['new value', 2, 3] This is because both names a and b are bound to the same list object. However if you assign a different list object to one of the names then they will no longer be bound to the same object. Continuing from above: >>> a = ['a', 'different', 'list', 'object'] >>> a ['a', 'different', 'list', 'object'] >>> b ['new value', 2, 3] The key thing is that "bare" assignment (i.e 'a = ...') rebinds the name a to a new object where as item assignment (i.e. 'a[index]= ...') changes values in the list that a is bound to. Oscar From satheesan.varier at gmail.com Mon Nov 18 12:08:32 2013 From: satheesan.varier at gmail.com (Satheesan Varier) Date: Mon, 18 Nov 2013 06:08:32 -0500 Subject: [Tutor] Tutor Digest, Vol 117, Issue 32 ( Subject: Phython List values ) Message-ID: Message: 7 Date: Mon, 18 Nov 2013 06:57:20 -0000 From: "Ayo Rotibi" To: Subject: [Tutor] Phython List values Message-ID: <002901cee42b$6e346fe0$4a9d4fa0$@com> Content-Type: text/plain; charset="us-ascii" Hi, I am a complete newbie to python. I read that an assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory. For instance, if a = [1, 2, 3] and b=a, then b = [1, 2, 3]. However, I discovered that if I change the value in 'a', 'b' does not take the new value. I thought since it is pointing to the same storage as 'a', 'b' should take the new value. Any explanation would be appreciated. Dear Ayo :: You should look at the order of execution: >>> a=['a','b','c'] >>> b=a >>> b.append('d') >>> a ['a', 'b', 'c', 'd'] In your third step you reassigned b=['a','b','c'] Best wishes ! _________________________________ Desire, Dedication, Determination and a little bit of Talent On Mon, Nov 18, 2013 at 5:35 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://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. Call Attribute error - Was Re: Tutor Digest, Vol 117, Issue > 28 (Alan Gauld) > 2. Re: Link required for difference between class and object > (Joel Goldstick) > 3. Re: Link required for difference between class and object > (Mark Lawrence) > 4. Re: basic function concept (Alex Kleider) > 5. Re: basic function concept (Alex Kleider) > 6. Re: Link required for difference between class and object > (Alan Gauld) > 7. Phython List values (Ayo Rotibi) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 17 Nov 2013 15:23:06 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: [Tutor] Call Attribute error - Was Re: Tutor Digest, Vol > 117, Issue 28 > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 17/11/13 12:19, Satheesan Varier wrote: > > class myclass(): > > def test(self): > > print "print this line" > > > > if __name__ == '__main__': > > myclass.run() > > > > You can do the test run with an instance of that class, as follows: > > > > >>> k=myclass() > > > > >>> myclass.test(k) > > print this line > > Or more conventionally > > k.test() > > Please don't post the entire digest when replying, remove any irrelevant > material. Some people pay by the byte and don't > want to pay for stuff they've already seen. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 2 > Date: Sun, 17 Nov 2013 10:29:48 -0500 > From: Joel Goldstick > To: Reuben > Cc: "tutor at python.org" > Subject: Re: [Tutor] Link required for difference between class and > object > Message-ID: > < > CAPM-O+xxzUiE_us8rj3TXN2vu-fZi__3ObsJCWgYbdsqetEuTQ at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Sun, Nov 17, 2013 at 7:24 AM, Reuben wrote: > > Hi All, > > > > It would be nice if someone could forward a link which explains classes > and > > object. > > I am still struggling to understand classes and objects better. > > > > Regards, > > Reuben > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > > > Have you looked here yet? http://docs.python.org/2/tutorial/classes.html > > -- > Joel Goldstick > http://joelgoldstick.com > > > ------------------------------ > > Message: 3 > Date: Sun, 17 Nov 2013 15:53:49 +0000 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] Link required for difference between class and > object > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 17/11/2013 12:24, Reuben wrote: > > Hi All, > > > > It would be nice if someone could forward a link which explains classes > > and object. > > I am still struggling to understand classes and objects better. > > > > Regards, > > Reuben > > > > An extremely simplistic answer to get you going, a class is the template > that you have in your source code, an object is an instance of your > class that you create in your source code. > > class Myclass(): #the class, the template > pass > > myobject = Myclass() # the instance, the object > > -- > Python is the second best programming language in the world. > But the best has yet to be invented. Christian Tismer > > Mark Lawrence > > > > ------------------------------ > > Message: 4 > Date: Sun, 17 Nov 2013 08:54:01 -0800 > From: Alex Kleider > To: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: <4d80fa567c0764c1441b8ea6dd9f2462 at sonic.net> > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 2013-11-17 00:47, Alan Gauld wrote: > > On 17/11/13 05:16, Alex Kleider wrote: > >> On 2013-11-16 13:20, Byron Ruffin wrote: > >>> def main(x, y, z): > >>> print (x, y, z) > >>> > >>> def funct(): > >>> x = 1 > >>> y = 2 > >>> z = 3 > >>> return x, y, z > >>> > >>> main() > >>> > >>> Can someone tell me why main is not being given any arguments? > >> > >> Because you didn't give it any. > >> Try > >> main(funct()) > > > > make that > > > > main(*funct()) > > > > funct returns a tuple so you need to unpack it in the main() > > argument list using the * notation. > > > Much more elegant than my 'corrected' version. > Thanks for the suggestion. > > > ------------------------------ > > Message: 5 > Date: Sun, 17 Nov 2013 08:51:48 -0800 > From: Alex Kleider > To: John Aten > Cc: tutor at python.org > Subject: Re: [Tutor] basic function concept > Message-ID: > Content-Type: text/plain; charset="utf-8"; Format="flowed" > > On 2013-11-16 22:31, John Aten wrote: > > Too bad that doesn't work. > > No, it doesn't. Can you see why? > Attached is a version that does work but you'd be better served looking > at the two versions you already have and studying the error messages you > get when you run them. > > > > > > On Nov 16, 2013, at 11:16 PM, Alex Kleider wrote: > > > >> On 2013-11-16 13:20, Byron Ruffin wrote: > >>> def main(x, y, z): > >>> print (x, y, z) > >>> def funct(): > >>> x = 1 > >>> y = 2 > >>> z = 3 > >>> return x, y, z > >>> main() > >>> Can someone tell me why main is not being given any arguments? > >> > >> Because you didn't give it any. > >> Try > >> main(funct()) > >> instead. > >> > >> > >>> _______________________________________________ > >>> Tutor maillist - Tutor at python.org > >>> To unsubscribe or change subscription options: > >>> https://mail.python.org/mailman/listinfo/tutor > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: func0args > Type: text/x-python > Size: 441 bytes > Desc: not available > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131117/5a05cb29/attachment-0001.py > > > > ------------------------------ > > Message: 6 > Date: Sun, 17 Nov 2013 17:20:56 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: Re: [Tutor] Link required for difference between class and > object > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 17/11/13 12:24, Reuben wrote: > > Hi All, > > > > It would be nice if someone could forward a link which explains classes > > and object. > > I am still struggling to understand classes and objects better. > > You can try the OOP topic in my tutorial if you like... > In a nutshell: > > A class is a type, like string or integer are types. > An instance is a 'value' of that type, like 'foo' or 42. > Classes define methods (or operations) that you can apply > to the instances, like 'foo'.upper(). > > You can create your own data types by writing classes. > But nearly all you should ever do with a class itself > is create instances of it (at least as a beginner). > Most of the work is done by the instances, by calling > their methods. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > > ------------------------------ > > Message: 7 > Date: Mon, 18 Nov 2013 06:57:20 -0000 > From: "Ayo Rotibi" > To: > Subject: [Tutor] Phython List values > Message-ID: <002901cee42b$6e346fe0$4a9d4fa0$@com> > Content-Type: text/plain; charset="us-ascii" > > Hi, > > I am a complete newbie to python. > > > > I read that an assignment with an = on lists does not make a copy. Instead, > assignment makes the two variables point to the one list in memory. For > instance, if a = [1, 2, 3] and b=a, then b = [1, 2, 3]. > > > > However, I discovered that if I change the value in 'a', 'b' does not take > the new value. I thought since it is pointing to the same storage as 'a', > 'b' should take the new value. > > > > Any explanation would be appreciated. > > > > Ayo > > > > _________________________________ > > Desire, Dedication, Determination > > and a little bit of Talent > > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131118/59d3b0c1/attachment.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 117, Issue 32 > ************************************** > -- Warm regards. Satheesan Varier 860 (970) 2732 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Mon Nov 18 18:59:39 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 18 Nov 2013 09:59:39 -0800 Subject: [Tutor] ideas? In-Reply-To: References: Message-ID: For reference, here are the documentation pages for ord() and chr(): http://docs.python.org/3/library/functions.html?highlight=chr#ord http://docs.python.org/3/library/functions.html?highlight=chr#chr On Mon, Nov 18, 2013 at 3:01 AM, Alan Gauld wrote: > On 18/11/13 03:27, Byron Ruffin wrote: > >> Need a little help with finding a process for this: >> >> when a string of text is input, for example: abc def. >> I want to have each letter shift to the right one place in the alphabet. >> Thus.. >> abc def would be output as bcd efg. >> >> Any ideas on how to do this? >> > > Yes, use the ord() function to convert the letters to numbers. Add one and > convert back using the chr() function. Check for the special case of 'z'. > > Consider how to handle upper case letters too. > > hth > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Mon Nov 18 22:21:03 2013 From: akleider at sonic.net (Alex Kleider) Date: Mon, 18 Nov 2013 13:21:03 -0800 Subject: [Tutor] =?utf-8?q?ideas=3F?= In-Reply-To: References: Message-ID: On 2013-11-17 19:27, Byron Ruffin wrote: > Need a little help with finding a process for this: > > when a string of text is input, for example: abc def. > I want to have each letter shift to the right one place in the > alphabet. Thus.. > abc def would be output as bcd efg. > > Any ideas on how to do this? "translate"? http://docs.python.org/2/library/stdtypes.html#str.translate > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From satheesan.varier at gmail.com Tue Nov 19 03:02:50 2013 From: satheesan.varier at gmail.com (Satheesan Varier) Date: Mon, 18 Nov 2013 21:02:50 -0500 Subject: [Tutor] Tutor Digest, Vol 117, Issue 33[ Re: Ideas ? ] Message-ID: Need a little help with finding a process for this: when a string of text is input, for example: abc def. I want to have each letter shift to the right one place in the alphabet. Thus.. abc def would be output as bcd efg. Any ideas on how to do this? ------------------------------------------------------------------------- if you do not want to use the translate: >>> s='abcdef ghijk lmn' >>> k='' >>> for char in s: if char!=' ': k+=str(chr(ord(char)+1)) else: k+=' ' >>> k 'bcdefg hijkl mno' -------------------------------------------------------------------------- If you want to use translate: >>> from string import maketrans >>> your_alphabets = 'abcdefghijklmnopurstuvwzyz' >>> my_alphabets='bcdefghijklmnopqystuvwxyza' >>> s='Let us Test Your language !' >>> s.translate(maketrans(your_alphabets, my_alphabets)) 'Lfu vt Tftu Ypvs mbohvbhf !' Note: my_alphabets to fine tune __________________________________________ On Mon, Nov 18, 2013 at 6:00 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://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. ideas? (Byron Ruffin) > 2. Re: Phython List values :p: (Paradox) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 17 Nov 2013 21:27:56 -0600 > From: Byron Ruffin > To: tutor at python.org > Subject: [Tutor] ideas? > Message-ID: > kOJUKEyG+chWw at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Need a little help with finding a process for this: > > when a string of text is input, for example: abc def. > I want to have each letter shift to the right one place in the alphabet. > Thus.. > abc def would be output as bcd efg. > > Any ideas on how to do this? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131117/56728ee8/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Mon, 18 Nov 2013 05:49:06 -0500 > From: Paradox > To: tutor at python.org > Subject: Re: [Tutor] Phython List values :p: > Message-ID: <5289F0A2.3010306 at pobox.com> > Content-Type: text/plain; charset=windows-1252; format=flowed > > Ayo, > > On 11/18/2013 01:57 AM, Ayo Rotibi wrote: > > > > > > I read that an assignment with an = on lists does not make a copy. > > Instead, assignment makes the two variables point to the one list in > > memory. For instance, if a = [1, 2, 3] and b=a, then b = [1, 2, 3]. > > > > However, I discovered that if I change the value in ?a?, ?b? does not > > take the new value. I thought since it is pointing to the same > > storage as ?a?, ?b? should take the new value? > > > > > It is not clear to me what code you are running, maybe you could give us > the specifics? When I run an assignment like you seem to be talking > about I get the expected result (using ipython for an interactive > session to demonstrate): > > In [1]: a=[1,2,3] > > In [2]: b=a > > In [3]: b > Out[3]: [1, 2, 3] > > In [4]: a[1]=0 > > In [5]: a > Out[5]: [1, 0, 3] > > In [6]: b > Out[6]: [1, 0, 3] > > Is that not what you are seeing? If not perhaps you could show us how > you are doing the list assignment and changing the list a, what output > you are expecting and what output you are getting. > > thomas > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 117, Issue 33 > ************************************** > -- Warm regards. Satheesan Varier 860 (970) 2732 -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Nov 19 15:02:13 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 19 Nov 2013 14:02:13 +0000 Subject: [Tutor] Tutor Digest, Vol 117, Issue 33[ Re: Ideas ? ] In-Reply-To: References: Message-ID: On 19/11/2013 02:02, Satheesan Varier wrote: If you want help would you please start a new thread and not send a reply to the entire tutor digest, albeit a small one in this instance. Or are you replying to someone else, it's very difficult to see from the mish mash that's arrived at my email client? -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From pscott_74 at yahoo.com Tue Nov 19 17:06:40 2013 From: pscott_74 at yahoo.com (Patti Scott) Date: Tue, 19 Nov 2013 08:06:40 -0800 (PST) Subject: [Tutor] Unit testing individual modules Message-ID: <1384877200.16553.YahooMailNeo@web161806.mail.bf1.yahoo.com> Python 2.4 self-study with Python Programming: An Introduction to Computer Science by Zelle ? I am trying to import a program that has a conditional execution statement at the end so I can troubleshoot individual modules in the main() program. ? Below is the textbook example program.? When I try to import the program from Idle, I get ? Traceback (most recent call last): ? File "", line 1, in -toplevel- ??? import rball ImportError: No module named rball ? (Also if I try to import with .py or .pyc) ? From the commandline interface, I can import the program, but __name__? is still? "__main__" and I haven't successfully unit tested any of the individual functions. ? ? ? # rball.py # textbook example of top-down design for Monte Carlo raquetball simulation from random import random def main(): ??? #printIntro() ??? #probA, probB, n = getInputs() ??? #winsA, winsB = simNGames(n,probA,probB) ??? #printSummary(winsA, winsB) ??? def printIntro(): ??????? print "This program simulates a game of racquetball between two" ??????? print 'players called "A" and "B."? The ability of each player is' ??????? print "indicated by a probability (a number between 0 and 1) that" ??????? print "the player wins the point when serving.? Player A always" ??????? print "has the first serve." ??? def getInputs(): ??????? #Returns the three simulation parameters ??????? n = input("How many games to simulate? ") ??????? a = input("What is the probability player A wins service? ") ??????? b = input("What is the probability player B wins service? ") ??????? return a, b, n ??? ??? def simNGames(n, probA, probB): ??????? #simulates n games of racquetball between players whose ??????? #?? abilities are represented by the prob. of winning serivce ??????? #Returns total number of wins for A and B ??????? winsA = winsB = 0 ??????? for i in range(n): ??????????? scoreA, scoreB = simOneGame(probA, probB) ??????????? if scoreA > scoreB: ??????????????? winsA = winsA + 1 ??????????? else: ??????????????? winsB = winsB + 1 ??????? return winsA, winsB ??? def simOneGame(probA, probB): ??????? #Simulates a single game between players whose ??????? #?? abilities are represented by the prob. of winning service. ??????? # Returns final scores for A and B, one game ??????? serving = 'A' ??????? scoreA = scoreB = 0 ??????? while not gameOver(scoreA, scoreB): ??????????? if serving == 'A': ??????????????? if random()< probA: ??????????????????? scoreA = scoreA + 1 ??????????????? else: ??????????????????? serving = 'B' ??????????? else: ??????????????? if random() < probB: ??????????????????? scoreB = scoreB + 1 ??????????????? else: ??????????????????? serving = 'A' ??????? return scoreA, scoreB ??? def gameOver(a,b): ??????? # a and b represent running scores for one racquetball game ??????? # Returns True if game over, False otherwise ??????? return a==15 or b==15 ??? def printSummary(winsA, winsB): ??????? # Prints a summary of wins for each player. ??????? n = winsA + winsB ??????? print ??????? print "Games simulated:", n ??????? print "Wins for A: %d (%0.1f%%)" % (winsA, float(winsA)/n*100) ??????? print "Wins for B: %d (%0.1f%%)" % (winsB, float(winsB)/n*100) ??? printIntro() ??? probA, probB, n = getInputs() ??? winsA, winsB = simNGames(n,probA,probB) ??? printSummary(winsA, winsB) if __name__ == "__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 19 23:58:11 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Nov 2013 22:58:11 +0000 Subject: [Tutor] Unit testing individual modules In-Reply-To: <1384877200.16553.YahooMailNeo@web161806.mail.bf1.yahoo.com> References: <1384877200.16553.YahooMailNeo@web161806.mail.bf1.yahoo.com> Message-ID: On 19/11/13 16:06, Patti Scott wrote: > Python 2.4 > self-study with Python Programming: An Introduction to Computer Science > by Zelle > I am trying to import a program that has a conditional execution > statement at the end so I can troubleshoot individual modules in the > main() program. I'm not quite sure what you are doing here. Can you give a bit more detail of how you are using this? How do you import it? > Traceback (most recent call last): > File "", line 1, in -toplevel- > import rball > ImportError: No module named rball Is rball in the import path? (sys.path) > (Also if I try to import with .py or .pyc) Never include the .py or .pyc in an import > From the commandline interface, I can import the program, but __name__ > is still "__main__" and I haven't successfully unit tested any of the > individual functions. This bit confuses me. Which command line do you mean? The OS or Python interpreter? Also the only way you can test the functions is if name is main. That's because the functions are all defined inside main(). That's a highly unusual pattern... > # rball.py > # textbook example of top-down design for Monte Carlo raquetball simulation > from random import random This import is the only thing that happens if name is not main... > def main(): > def printIntro():... > def getInputs():... > def simNGames(n, probA, probB):... > def simOneGame(probA, probB):... > def gameOver(a,b):... > def printSummary(winsA, winsB):... > ... > > if __name__ == "__main__": main() Are you really sure that's what you want? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From antongilb at gmail.com Wed Nov 20 01:22:32 2013 From: antongilb at gmail.com (Anton Gilb) Date: Tue, 19 Nov 2013 18:22:32 -0600 Subject: [Tutor] Not sure what I'm doing wrong with these 2 python scripts Message-ID: Not sure what I'm doing wrong, here are the problems and what I have for answers so far. 1.)Write the definition of a class Counter containing: An instance variable named counter of type int . A constructor that takes one int argument and assigns its value to counter A method named increment that adds one to counter . It does not take parameters or return a value. A method named decrement that subtracts one from counter . It also does not take parameters or return a value. A method named get_value that returns the value of the instance variable counter . class Counter(object): def __init__(self, ct): self.counter = ct def increment(self): self.counter += 1 def decrement(self): self.counter -= 1 def get_value(self): return self.counter 2.)Write the definition of a class WeatherForecast that provides the following behavior (methods): A method called set_skies that has one parameter, a String. A method called set_high that has one parameter, an int. A method called set_low that has one parameter, an int. A method called get_skies that has no parameters and that returns the value that was last used as an argument in set_skies . A method called get_high that has no parameters and that returns the value that was last used as an argument in set_high . A method called get_low that has no parameters and that returns the value that was last used as an argument in set_low . No constructor need be defined. Be sure to define instance variables as needed by your "get"/"set" methods. class WeatherForecast(object): def __init__ (self): self.skies = "" def get_skies(): return self.set_skies def set_skies(self, value) self.skies = value def get_high(): return self.set_high def set_high(self, value): self.high = value def get_low(): return self.set_low def set_low(self): self.low = value -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Wed Nov 20 10:51:31 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Wed, 20 Nov 2013 10:51:31 +0100 Subject: [Tutor] Not sure what I'm doing wrong with these 2 python scripts In-Reply-To: References: Message-ID: <20131120105131.022635de@Hof> Anton Gilb wrote: >Not sure what I'm doing wrong, here are the problems and what I have >for answers so far. You should tell us what's wrong with your solutions. Do you get an error? Then please show us the complete traceback (error message). Does your code something else than you expect? Then show us what you do, what you get and how/why it differs from the expected solution. Bye, Andreas From steve at pearwood.info Wed Nov 20 11:30:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 20 Nov 2013 21:30:17 +1100 Subject: [Tutor] Not sure what I'm doing wrong with these 2 python scripts In-Reply-To: References: Message-ID: <20131120103017.GC2085@ando> On Tue, Nov 19, 2013 at 06:22:32PM -0600, Anton Gilb wrote: > Not sure what I'm doing wrong, here are the problems and what I have for > answers so far. What makes you think you're doing anything wrong? See below for more comments. > 1.)Write the definition of a class Counter containing: > An instance variable named counter of type int . > A constructor that takes one int argument and assigns its value to counter > A method named increment that adds one to counter . It does not take > parameters or return a value. > A method named decrement that subtracts one from counter . It also does > not take parameters or return a value. > A method named get_value that returns the value of the instance variable > counter . > > class Counter(object): > def __init__(self, ct): > self.counter = ct > def increment(self): > self.counter += 1 > def decrement(self): > self.counter -= 1 > def get_value(self): > return self.counter This looks fine to me, except for a couple of little nit-picks about terminology. (If you care about them, feel free to ask, otherwise I'll just bite my tongue.) What errors are you getting? Nothing is obvious. > 2.)Write the definition of a class WeatherForecast that provides the > following behavior (methods): > A method called set_skies that has one parameter, a String. > A method called set_high that has one parameter, an int. > A method called set_low that has one parameter, an int. > A method called get_skies that has no parameters and that returns the > value that was last used as an argument in set_skies . > A method called get_high that has no parameters and that returns the value > that was last used as an argument in set_high . > A method called get_low that has no parameters and that returns the value > that was last used as an argument in set_low . > No constructor need be defined. Be sure to define instance variables as > needed by your "get"/"set" methods. Again, what errors are you getting? In this case, I can guess what some of the errors might be. See below. > class WeatherForecast(object): > def __init__ (self): > self.skies = "" The instructions say that you don't have to define a constructor, but they don't forbid it. In this case, I think I'd prefer not to include the constructor. (I know I said I wouldn't, but here's one of the nit-picks: __init__ isn't strictly speaking a constructor, it's an initialiser. Not that the difference really matters here.) > def get_skies(): > return self.set_skies Here, rather than return the skies value, you return the "set_skies" method itself. I suggest you look at the first class and consider how the get_value method works. You want to return the "skies" value instead. > def set_skies(self, value) > self.skies = value > def get_high(): > return self.set_high Likewise, here rather than return the high value, you return the "set_high" method. > def set_high(self, value): > self.high = value > def get_low(): > return self.set_low And likewise again. > def set_low(self): > self.low = value Hope this helps, -- Steven From alan.gauld at btinternet.com Wed Nov 20 19:37:04 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 20 Nov 2013 18:37:04 +0000 (GMT) Subject: [Tutor] Unit testing individual modules In-Reply-To: <1384969479.27645.YahooMailNeo@web161806.mail.bf1.yahoo.com> References: <1384877200.16553.YahooMailNeo@web161806.mail.bf1.yahoo.com> <1384969479.27645.YahooMailNeo@web161806.mail.bf1.yahoo.com> Message-ID: <1384972624.48373.YahooMailNeo@web186004.mail.ir2.yahoo.com> Forwarding to the python list for visibility/commebnt. Please always use ReplyAll to include the list. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos >________________________________ > From: Patti Scott >To: Alan Gauld >Sent: Wednesday, 20 November 2013, 17:44 >Subject: Re: [Tutor] Unit testing individual modules > > > >Thank you for your comments. >? >I am trying to import the program file named rball.py, then call/run one of the modules? >within rball.py? [printIntro() to start] ?without running the entire main() module of rball.py.?? We need to clarify the terminology. The "program file" is both a program file (aka script) and a module. In Python module refers to the file not the functions/classes within it. printIntro(), and indeed main() itself, are *functions* within the module. When you run a file directly from the OS prompt, eg: $ python rball.py then the interpreter will set the __name__ attribute to __main__. Thus the if statement at the end will only execute the main() function if you run the file from the OS prompt as above. When you import the file, as in import rball Then the interpreter sets the __name__ attribute to the name? of the module, rball in this case. Because the name is not? __main__ your main function is defined but not executed. Because main() is never executed the functions defined? within it are not defined. Hence you get an error when? you try to use them. It might work(I have't tried it) if you execute main()? manually and then try to execute the functions but I? suspect it won't since the functions are local to main(). >My understanding is that being able to call/run select?modules within the ? >main()?module?is a?useful troubleshooting technique.? No. It is much more helpful to define your functions outside of main. You can then access them as functions via the module, thus: import rball rball.printIntro() etc. What is useful is to define a test() or main() function that? will exercise all of the other functions when the file is executed? from the OS level as shown above. I suspect thats the bit that? has confused you. Thus when you run $ python rball.py You will see all your tests being executed. But when you do an import in another program(or at the? Python >>> prompt) you can access the functions in your? code via the module name. This dual purpose use of files? is a very handy feature indeed. >According to my text, adding the conditional execution statement >if __name__=='__main__': main()? should result in the program? > running when invoked directly [F5 from the Idle editor window],? > but not running when imported [import rball].?? That is correct.? > When imported, however, I should be able to individually test? > the functions within rball.py? such as >????>>import rball >????>>rball1.gameOver(0,0) >????False >? >This is not working as presented.?? Thats because you put the function definitions inside main() Move them outside main and it will work as you expect. HTH, Alan G. From rafael.knuth at gmail.com Thu Nov 21 12:00:31 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 21 Nov 2013 12:00:31 +0100 Subject: [Tutor] Issue w/ while loops Message-ID: Hej there, I want to use a while loop in a program (version used: Python 3.3.0), and I expect it to loop unless the user enters an integer or a floating-point number instead of a string. print("TIME TRACKING") hours_worked = input("How many hours did you work today? ") while hours_worked != str() or int(): hours_worked = input("Can't understand you. Please enter a number! ") print("you worked " + str(hours_worked) + " hours today.") When I run the program, it keeps looping even if the condition is met. How do I need to modify the program on the 3rd line so that it stops looping when the user enters a floating-point number or an integer? Thank you! Raf From __peter__ at web.de Thu Nov 21 12:31:56 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 21 Nov 2013 12:31:56 +0100 Subject: [Tutor] Issue w/ while loops References: Message-ID: Rafael Knuth wrote: > Hej there, > > I want to use a while loop in a program (version used: Python 3.3.0), > and I expect it to loop unless the user enters an integer or a > floating-point number instead of a string. > > print("TIME TRACKING") > hours_worked = input("How many hours did you work today? ") > while hours_worked != str() or int(): > hours_worked = input("Can't understand you. Please enter a number! ") > > print("you worked " + str(hours_worked) + " hours today.") > > When I run the program, it keeps looping even if the condition is met. > How do I need to modify the program on the 3rd line so that it stops > looping when the user enters a floating-point number or an integer? Let's have a look at what input() gives: >>> input("How many hours did you work today? ") How many hours did you work today? 1234 '1234' A human being would understand that I was either very busy or that I lied, but from Python's point of view this is just a str containing some digits, not an actual number. Now let's see str() actually is: >>> str() '' An empty string. Now int(): >>> int() 0 The integer 0. So your loop is while "1234" != "" or 0: ... and following Python's precedence rules it is evaluated as while ("1234" != "") or 0: ... With that information, can you work out with what input your script would terminate (or not enter) the while loop? Now how can we find out if the string can be converted to a valid (non- negative) float? You have to check the characters and verify that there are at most one ".", at least one digit and no other non-digits. While it would be a good exercise for you to try and implement the above check there is a simpler approach: just try the conversion and catch the potential error: valid = True # we are optimists try: hours_worked = float(hours_worked) except ValueError: valid = False # only executed when the string is not a valid float Try to integrate this into your script and come back here if you run into problems. From davea at davea.name Thu Nov 21 12:44:40 2013 From: davea at davea.name (Dave Angel) Date: Thu, 21 Nov 2013 06:44:40 -0500 Subject: [Tutor] Issue w/ while loops In-Reply-To: References: Message-ID: On Thu, 21 Nov 2013 12:00:31 +0100, Rafael Knuth wrote: > hours_worked = input("How many hours did you work today? ") > while hours_worked != str() or int(): > hours_worked = input("Can't understand you. Please enter a number! ") There are two problems with your conditional expression. First is your use of "or" Suppose you were trying to loop until the user entered "7" or "X". You couldn't use while value == "7" or "X": You would need while value == "7" or value == "X": The "or" operator is used to combine two boolean expressions, and since "X" is truthie, the entire expression would be true. The second problem is that str() and int() are used to convert values, not somehow analyze them. WIthout arguments to convert, they produce default values. Int() will produce a zero integer, and I assume str() will produce the empty string. Neither is what you want to compare. What you need instead is a technique that'll analyze a string to see whether it'll convert to an int or float. Best way to do that is to try to convert it, and see if an exception is thrown. while True: try: hw = float(hours_worked) except xxxxxxx as ex: hours_worked = input("try again....") -- DaveA From amitsaha.in at gmail.com Thu Nov 21 12:44:06 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Thu, 21 Nov 2013 21:44:06 +1000 Subject: [Tutor] Issue w/ while loops In-Reply-To: References: Message-ID: On Thu, Nov 21, 2013 at 9:00 PM, Rafael Knuth wrote: > Hej there, > > I want to use a while loop in a program (version used: Python 3.3.0), > and I expect it to loop unless the user enters an integer or a > floating-point number instead of a string. > > print("TIME TRACKING") > hours_worked = input("How many hours did you work today? ") > while hours_worked != str() or int(): > hours_worked = input("Can't understand you. Please enter a number! ") > > print("you worked " + str(hours_worked) + " hours today.") > > When I run the program, it keeps looping even if the condition is met. > How do I need to modify the program on the 3rd line so that it stops > looping when the user enters a floating-point number or an integer? There are two fundamental mistakes in your program: 1. The input() function always returns a string. So, there is no way to check directly whether the user has entered a number or a string. 2. hours_worked != str() or int() does not do what you want to do. In Python, str() creates a new string object and similarly int() creates an integer object, 0. So, to check whether the input is an integer or float, here is an idea: >>> def check_input(user_input): ... try: ... user_input = float(user_input) ... except ValueError: ... return 'Invalid input' ... else: ... return user_input ... >>> check_input('a') 'Invalid input' >>> check_input('1.5') 1.5 >>> check_input('1') 1.0 The idea above is basically, you convert the input (a string) to a float. If the input is a number, 1.5 or 1, the check_input() function will return the numeric equivalent. However, if the number is a string, it returns invalid input. You could make use of this in your program above. Hope that helps. Best, Amit. -- http://echorand.me From rafael.knuth at gmail.com Thu Nov 21 14:17:49 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 21 Nov 2013 14:17:49 +0100 Subject: [Tutor] Issue w/ while loops In-Reply-To: References: Message-ID: Hej there, @David @Peter @Amit: Thank you so much - you guys helped me understand my misconceptions and I learned a couple new things. On Thu, Nov 21, 2013 at 12:44 PM, Amit Saha wrote: > On Thu, Nov 21, 2013 at 9:00 PM, Rafael Knuth wrote: >> Hej there, >> >> I want to use a while loop in a program (version used: Python 3.3.0), >> and I expect it to loop unless the user enters an integer or a >> floating-point number instead of a string. >> >> print("TIME TRACKING") >> hours_worked = input("How many hours did you work today? ") >> while hours_worked != str() or int(): >> hours_worked = input("Can't understand you. Please enter a number! ") >> >> print("you worked " + str(hours_worked) + " hours today.") >> >> When I run the program, it keeps looping even if the condition is met. >> How do I need to modify the program on the 3rd line so that it stops >> looping when the user enters a floating-point number or an integer? > > There are two fundamental mistakes in your program: > > 1. The input() function always returns a string. So, there is no way > to check directly whether the user has entered a number or a string. > 2. hours_worked != str() or int() does not do what you want to do. In > Python, str() creates a new string object and similarly int() creates > an integer object, 0. Got you, thank you for the clarification. >>>> def check_input(user_input): > ... try: > ... user_input = float(user_input) > ... except ValueError: > ... return 'Invalid input' > ... else: > ... return user_input > ... >>>> check_input('a') > 'Invalid input' >>>> check_input('1.5') > 1.5 >>>> check_input('1') > 1.0 > > The idea above is basically, you convert the input (a string) to a > float. If the input is a number, 1.5 or 1, the check_input() function > will return the numeric equivalent. However, if the number is a > string, it returns invalid input. You could make use of this in your > program above. > > Hope that helps. It definitely does! I am completely new to programming, and I am taking a Python course at Codecademy. In addition to that, I write tiny, little throw-away programs along the way in order to get more practice. The concept of try/except/else was new to me and it's extremely valuable to know how make use of it. I'm only stuck at one point: How do I loop back to the beginning in case the user input is invalid? I want the program to loop until the user enters a value that is either a float or an int. None of my code modifications gave me the desired result. In case the user input is correct, I can move on and analyze it as I figured out, for example: print("TIME TRACKING") hours_worked = input("How many hours did you work today? ") try: hours_worked = float(hours_worked) except ValueError: print ("Invalid input") if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") All the best, Raf From alan.gauld at btinternet.com Thu Nov 21 16:24:26 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Nov 2013 15:24:26 +0000 Subject: [Tutor] Issue w/ while loops In-Reply-To: References: Message-ID: On 21/11/13 13:17, Rafael Knuth wrote: > I'm only stuck at one point: How do I loop back to the beginning in > case the user input is invalid? Look at Peter's example. He set a variable to false when the input was wrong. You can check that value in your while loop. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From fomcl at yahoo.com Thu Nov 21 21:04:19 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 21 Nov 2013 12:04:19 -0800 (PST) Subject: [Tutor] Is there a package to "un-mangle" characters? Message-ID: <1385064259.96702.YahooMailBasic@web163802.mail.gq1.yahoo.com> Hi, Today I had a csv file in utf-8 encoding, but part of the accented characters were mangled. The data were scraped from a website and it turned out that at least some of the data were mangled on the website already. Bits of the text were actually cp1252 (or cp850), I think, even though the webpage was in utf-8 Is there any package that helps to correct such issues? (I tried looking for one but it doesn't really help that there is such a thing as name mangling! ;-) This comes pretty close though: https://gist.github.com/litchfield/1282752 Thanks in advance! Regards, 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 breamoreboy at yahoo.co.uk Thu Nov 21 21:40:35 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 21 Nov 2013 20:40:35 +0000 Subject: [Tutor] Is there a package to "un-mangle" characters? In-Reply-To: <1385064259.96702.YahooMailBasic@web163802.mail.gq1.yahoo.com> References: <1385064259.96702.YahooMailBasic@web163802.mail.gq1.yahoo.com> Message-ID: On 21/11/2013 20:04, Albert-Jan Roskam wrote: > Hi, > > Today I had a csv file in utf-8 encoding, but part of the accented characters were mangled. The data were scraped from a website and it turned out that at least some of the data were mangled on the website already. Bits of the text were actually cp1252 (or cp850), I think, even though the webpage was in utf-8 Is there any package that helps to correct such issues? (I tried looking for one but it doesn't really help that there is such a thing as name mangling! ;-) This comes pretty close though: https://gist.github.com/litchfield/1282752 > 1) Would something like this help https://pypi.python.org/pypi/charset/1.0.1 ? 2) Surely this topic is too advanced for a tutor mailing list? -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From eryksun at gmail.com Fri Nov 22 03:29:35 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 21 Nov 2013 21:29:35 -0500 Subject: [Tutor] Is there a package to "un-mangle" characters? In-Reply-To: <1385064259.96702.YahooMailBasic@web163802.mail.gq1.yahoo.com> References: <1385064259.96702.YahooMailBasic@web163802.mail.gq1.yahoo.com> Message-ID: On Thu, Nov 21, 2013 at 3:04 PM, Albert-Jan Roskam wrote: > > Today I had a csv file in utf-8 encoding, but part of the accented > characters were mangled. The data were scraped from a website and it > turned out that at least some of the data were mangled on the website > already. Bits of the text were actually cp1252 (or cp850), I think, > even though the webpage was in utf-8 Is there any package that helps > to correct such issues? The links in the Wikipedia article may help: http://en.wikipedia.org/wiki/Charset_detection International Components for Unicode (ICU) does charset detection: http://userguide.icu-project.org/conversion/detection Python wrapper: http://pypi.python.org/pypi/PyICU http://packages.debian.org/wheezy/python-pyicu Example: import icu russian_text = u'????? ????? ????? ?? ??????? ?????.' encoded_text = russian_text.encode('windows-1251') cd = icu.CharsetDetector() cd.setText(encoded_text) match = cd.detect() matches = cd.detectAll() >>> match.getName() 'windows-1251' >>> match.getConfidence() 33 >>> match.getLanguage() 'ru' >>> [m.getName() for m in matches] ['windows-1251', 'ISO-8859-6', 'ISO-8859-8-I', 'ISO-8859-8'] >>> [m.getConfidence() for m in matches] [33, 13, 8, 8] From mckinnonryall at gmail.com Fri Nov 22 06:57:30 2013 From: mckinnonryall at gmail.com (G. McKinnon Ryall) Date: Thu, 21 Nov 2013 23:57:30 -0600 Subject: [Tutor] Reading number x and printing number x+1 Message-ID: I have a script that outputs results to a file (one file, reused.) I would like to have an output file in this format #-------------------- (blank line) (output from program (only one line)) name (T/F) (result iteration, shortened to x.) #--------------------- so like this #--------------------- 55 Joe false 1 96 Bob true 2 28 Mike true 3 #--------------------- I couldn't think of a way to read the last written number (it would be a multiple of 5). I know how to add 1 and print. Also, how would I arrange #-------- output.write("\n") output.write(x_string) output.write("\n") output.write(name) output.write("\n") output.write(exists_string) output.write("\n") #------- so that it didn't show up like this FIRST TIME 101 nope True 1 SECOND TIME 101 nope True 1 4554073 yup True Also, how would I make this program better in general? #BEGIN # Importing exists. Simple English. Nonsensical, but English nonetheless. from os.path import exists #Asking for your name name = raw_input("Hello!\nWhat is your name?\n\n") #Asking for the number and reacting to given response x = int(raw_input("\tFor the purposes of testing, please select a number between one and 100\n\n\t")) if x < 0: x = 4554073 print "\t\tNo negatives, asshole. Number changed to '4554073' for 'ASSHOLE', asshole." elif x == 0: print "\t\tMore than zero." elif x > 100: x = 101 print "\t\tDon't fuck with the computer." elif x == 42: print "\t\tThe meaning of life, the universe and everything." elif x == 7: print "\t\t7. How... creative. *cough* UNORIGINAL *cough*" elif x == 3: print "\t\t3! It's a magic numba\'. Yes it is! It's a magic numba\'." elif x == 37: print "\t\tThe two most common numbers." elif x == 99: print "\t\tI got 99 problems and a- wait, no, that's your IQ." elif x == 27: print "\t\tCONGRATULATATIONS! YOU'VE FOUND MY FOAVORITE NOMBER!" else: print "In all aspects your number appears to be normal." #Changing name to a string name_string = "%s" % name #Changing x to a string x_string = "%s" % x #Checking if file exists for archival purposes exists = exists("number_output.txt") exists_string = "%s" % exists #Opening output file number_output = 'number_output.txt' output = open(number_output, 'a') #Writing to file output.write("\n") output.write(x_string) output.write("\n") output.write(name) output.write("\n") output.write(exists_string) output.write("\n") #END -------------- next part -------------- An HTML attachment was scrubbed... URL: From rossaustech at gmail.com Thu Nov 21 18:35:51 2013 From: rossaustech at gmail.com (=?UTF-8?B?5LmF5aC05rW35Lq6?=) Date: Thu, 21 Nov 2013 09:35:51 -0800 Subject: [Tutor] (no subject) Message-ID: Hi. I began programming literally 2 days ago. This is a code to setup password and confirms to make sure they both match, and I need to know what coding I can use to loop back to specific line to start the code over if the user were to incorrectly typed in the password. 1. CreatePassword = raw_input ("Create New Password: ") 2. ConfirmationPass = raw_input (" Retype Password: ") 3. 4. 5. if CreatePassword == ConfirmationPass: 6. print ("Password Set!") 7. else: 8. print ("Password did not match!") -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Nov 22 09:57:46 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Nov 2013 09:57:46 +0100 Subject: [Tutor] (no subject) References: Message-ID: ???? wrote: > Hi. I began programming literally 2 days ago. > > This is a code to setup password and confirms to make sure they both > match, and I need to know what coding I can use to loop back to specific > line to start the code over if the user were to incorrectly typed in the > password. > > > 1. CreatePassword = raw_input ("Create New Password: ") > 2. ConfirmationPass = raw_input (" Retype Password: ") > 3. > 4. > 5. if CreatePassword == ConfirmationPass: > 6. print ("Password Set!") > 7. else: > 8. print ("Password did not match!") Use an infinite loop and break out of that when you get the correct data. Example: while True: # infinite loop guess = raw_input("Guess my number: ") if guess == "42": print "correct" break # break out of the infinite loop else: print "try again" From __peter__ at web.de Fri Nov 22 10:23:41 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Nov 2013 10:23:41 +0100 Subject: [Tutor] Reading number x and printing number x+1 References: Message-ID: G. McKinnon Ryall wrote: > I have a script that outputs results to a file (one file, reused.) I would > like to have an output file in this format > > #-------------------- > (blank line) > (output from program (only one line)) > name > (T/F) > (result iteration, shortened to x.) > #--------------------- > so like this > #--------------------- > > 55 > Joe > false > 1 > > 96 > Bob > true > 2 > > 28 > Mike > true > 3 > #--------------------- > > I couldn't think of a way to read the last written number (it would be a > multiple of 5). Just read the lines from the file, convert the last line to an int and add the new record. Example: with open("tmp.txt", "a+") as f: line = "0" # default when the file is empty or doesn't exist for line in f: pass n = int(line) + 1 f.write("{}\n".format(n)) > I know how to add 1 and print. Also, how would I arrange > #-------- > output.write("\n") > output.write(x_string) > output.write("\n") > output.write(name) > output.write("\n") > output.write(exists_string) > output.write("\n") > #------- > so that it didn't show up like this > FIRST TIME Now you have the n from my above sample you can run some of the code conditionally: if n == 1: ... else: ... > Also, how would I make this program better in general? Long if elif sequences can sometimes be simplified with a dict lookup: if a == 1: print "alpha" elif a == 2: print "beta" ... then becomes messages = {1: "alpha", 2: "beta"} try: print messages[a] except KeyError: # handle cases not covered by the value lookup approach Also, Python allows multiline strings: f.write("alpha\n") f.write("beta\n") becomes f.write("""\ alpha beta """) > #BEGIN > # Importing exists. Simple English. Nonsensical, but English nonetheless. > from os.path import exists > #Asking for your name > name = raw_input("Hello!\nWhat is your name?\n\n") > #Asking for the number and reacting to given response > x = int(raw_input("\tFor the purposes of testing, please select a number > between one and 100\n\n\t")) > > if x < 0: > x = 4554073 > print "\t\tNo negatives, asshole. Number changed to '4554073' for > 'ASSHOLE', asshole." > elif x == 0: > print "\t\tMore than zero." > elif x > 100: > x = 101 > print "\t\tDon't fuck with the computer." > elif x == 42: > print "\t\tThe meaning of life, the universe and everything." > elif x == 7: > print "\t\t7. How... creative. *cough* UNORIGINAL *cough*" > elif x == 3: > print "\t\t3! It's a magic numba\'. Yes it is! It's a magic numba\'." > elif x == 37: > print "\t\tThe two most common numbers." > elif x == 99: > print "\t\tI got 99 problems and a- wait, no, that's your IQ." > elif x == 27: > print "\t\tCONGRATULATATIONS! YOU'VE FOUND MY FOAVORITE NOMBER!" > else: > print "In all aspects your number appears to be normal." > #Changing name to a string > name_string = "%s" % name > #Changing x to a string > x_string = "%s" % x > #Checking if file exists for archival purposes > exists = exists("number_output.txt") > exists_string = "%s" % exists > #Opening output file > number_output = 'number_output.txt' > output = open(number_output, 'a') > #Writing to file > output.write("\n") > output.write(x_string) > output.write("\n") > output.write(name) > output.write("\n") > output.write(exists_string) > output.write("\n") > #END From rafael.knuth at gmail.com Fri Nov 22 11:11:45 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Fri, 22 Nov 2013 11:11:45 +0100 Subject: [Tutor] Issue w/ while loops In-Reply-To: References: Message-ID: >> I'm only stuck at one point: How do I loop back to the beginning in >> case the user input is invalid? > > > Look at Peter's example. He set a variable to false when the input was > wrong. You can check that value in your while loop. Ok, got you! print("TIME TRACKING") while True: hours_worked = input("How many hours did you work today? ") try: hours_worked = float(hours_worked) break except ValueError: print ("Invalid input") if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") Program works well now, a learned a lot along the way. Thank you & have a great weekend, Raf From nik at naturalnet.de Fri Nov 22 11:19:22 2013 From: nik at naturalnet.de (Dominik George) Date: Fri, 22 Nov 2013 11:19:22 +0100 Subject: [Tutor] Sending sensible e-mail (was: Re: (no subject)) In-Reply-To: References: Message-ID: <20131122101921.GB5646@keks.naturalnet.de> Hi, > Subject: [Tutor] (no subject) On a side note, please learn how to send e-mail. Thanks, Nik -- * mirabilos is handling my post-1990 smartphone * Aaah, it vibrates! Wherefore art thou, demonic device?? PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From __peter__ at web.de Fri Nov 22 11:33:26 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Nov 2013 11:33:26 +0100 Subject: [Tutor] Sending sensible e-mail (was: Re: (no subject)) References: <20131122101921.GB5646@keks.naturalnet.de> Message-ID: Dominik George wrote: >> Subject: [Tutor] (no subject) > > On a side note, please learn how to send e-mail. Nik, this is a beginners' list, so please be more constructive. ????, Nik may be unfriendly, but he is right; in future posts please take the time to pick a subject that gives the reader an idea of the problem you ran into. Thank you. From fomcl at yahoo.com Fri Nov 22 14:58:38 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 22 Nov 2013 05:58:38 -0800 (PST) Subject: [Tutor] Is there a package to "un-mangle" characters? In-Reply-To: Message-ID: <1385128718.69167.YahooMailBasic@web163802.mail.gq1.yahoo.com> > Today I had a csv file in utf-8 encoding, but part of the accented > characters were mangled. The data were scraped from a website and it > turned out that at least some of the data were mangled on the website > already. Bits of the text were actually cp1252 (or cp850), I think, > even though the webpage was in utf-8 Is there any package that helps > to correct such issues? The links in the Wikipedia article may help: ? ? http://en.wikipedia.org/wiki/Charset_detection International Components for Unicode (ICU) does charset detection: ? ? http://userguide.icu-project.org/conversion/detection Python wrapper: ? ? http://pypi.python.org/pypi/PyICU ? ? http://packages.debian.org/wheezy/python-pyicu Example: ? ? import icu ? ? russian_text = u'????? ????? ????? ?? ??????? ?????.' ? ? encoded_text = russian_text.encode('windows-1251') ? ? cd = icu.CharsetDetector() ? ? cd.setText(encoded_text) ? ? match = cd.detect() ? ? matches = cd.detectAll() ? ? >>> match.getName() ? ? 'windows-1251' ? ? >>> match.getConfidence() ? ? 33 ? ? >>> match.getLanguage() ? ? 'ru' ? ? >>> [m.getName() for m in matches] ? ? ['windows-1251', 'ISO-8859-6', 'ISO-8859-8-I', 'ISO-8859-8'] ? ? >>> [m.getConfidence() for m in matches] ? ? [33, 13, 8, 8] ====> Hi Mark, Eryksun, Thank you very much for your suggestions. Mark (sorry if I repeat myself but I think my earlier reply got lost), charset seems worth looking into. In hindsight I knew about chardet (with 'd'), I just forgot about it. Re: your other remark: I think encoding issues are such a common phenomenon that one can never be too inexperienced to start reading about it. The ICU module seems very cool too. I like the fact that you can even calculate a level of confidence. I wonder how it performs in my language (Dutch), where accented characters are not very common. Most is ascii (the printable chars in 0-128) and those are (I think) useless for trying to figure out the encoding. After all, utf-8, latin-1, cp1252, iso-8859-1 are all supersets of ascii. But in practice I treat those last three encodings as the same anyway (or was there some sneaky difference with fancyquotes?). I did a quick check and 0.2 % of the street names in my data (about 300K records) contain one or more accented characters (ordinals > 128). Since only part of the records are mangled, I may need to run getName() on every record that has accented characters in it. Regards, Albert-Jan From rafael.knuth at gmail.com Fri Nov 22 15:24:31 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Fri, 22 Nov 2013 15:24:31 +0100 Subject: [Tutor] Two subsequent for loops in one function Message-ID: Hej there, newbie question: I struggle to understand what exactly those two subsequent for loops in the program below do (Python 3.3.0): for x in range(2, 10): for y in range(2, x): if x % y == 0: print(x, "equals", y, "*", x//y) break else: print(x, "is a prime number") The result is: >>> 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 I have a very basic understanding of for loops, so for example: for everything in range(10): print(everything) ... the for loop grabs everything in that given range and prints it. But I feel confused by the double use of for loops as show above. Can anyone explain? Thanks Rafael From __peter__ at web.de Fri Nov 22 15:35:51 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 22 Nov 2013 15:35:51 +0100 Subject: [Tutor] Two subsequent for loops in one function References: Message-ID: Rafael Knuth wrote: > Hej there, > > newbie question: I struggle to understand what exactly those two > subsequent for loops in the program below do (Python 3.3.0): > > for x in range(2, 10): > for y in range(2, x): > if x % y == 0: > print(x, "equals", y, "*", x//y) > break > else: > print(x, "is a prime number") > > The result is: > >>>> > 2 is a prime number > 3 is a prime number > 4 equals 2 * 2 > 5 is a prime number > 6 equals 2 * 3 > 7 is a prime number > 8 equals 2 * 4 > 9 equals 3 * 3 > > I have a very basic understanding of for loops, so for example: > > for everything in range(10): > print(everything) > > ... the for loop grabs everything in that given range and prints it. > But I feel confused by the double use of for loops as show above. > > Can anyone explain? Try to understand the inner for loop first. Once you understand what it does treat it as a black box like so: def unknown(x): for y in range(2, x): if x % y == 0: print(x, "equals", y, "*", x//y) break else: print(x, "is a prime number") for x in range(2, 10): unknown(x) From steve at pearwood.info Fri Nov 22 15:52:53 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Nov 2013 01:52:53 +1100 Subject: [Tutor] Two subsequent for loops in one function In-Reply-To: References: Message-ID: <20131122145253.GK2085@ando> On Fri, Nov 22, 2013 at 03:24:31PM +0100, Rafael Knuth wrote: > Hej there, > > newbie question: I struggle to understand what exactly those two > subsequent for loops in the program below do (Python 3.3.0): > > for x in range(2, 10): > for y in range(2, x): > if x % y == 0: > print(x, "equals", y, "*", x//y) > break > else: > print(x, "is a prime number") The most tricky part here is, in my opinion, the "else" clause, because sadly it is badly named. It really should be called "then". A for-loop followed by an "else" means something like this: for something in something: run this block for each value else: then run this block (Notice that the "else" lines up with the "for".) What's the point of that? The point is that a "break" command jumps out of the *complete* for-else block. Try these examples: for i in range(5): if i == 400: break print(i) else: print("Finished loop!") for i in range(5): if i == 4: break print(i) else: print("Finished loop!") So the "else" clause only runs after the for block provided you never break out of the loop. Now, back to your nested loops. You have: for x in range(2, 10): for y in range(2, x): ... more code here ... The "for x" loop runs with x=2, x=3, x=4, ... x=9. For each of those values, the block inside the loop runs. Okay, so what's inside the block? It runs another for-loop, in this case a for-y loop. This ought to be more clear if you run a simpler (and shorter) example: for x in range(2, 7): print("outer loop, x =", x) for y in range(2, x): print("inner loop, x =", x, "y =", y) If you run that code, it should help you understand what the nested loops are doing. -- Steven From breamoreboy at yahoo.co.uk Fri Nov 22 16:04:21 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 22 Nov 2013 15:04:21 +0000 Subject: [Tutor] Sending sensible e-mail In-Reply-To: <20131122101921.GB5646@keks.naturalnet.de> References: <20131122101921.GB5646@keks.naturalnet.de> Message-ID: On 22/11/2013 10:19, Dominik George wrote: > Hi, > >> Subject: [Tutor] (no subject) > > On a side note, please learn how to send e-mail. > > Thanks, > Nik > At least Steven D'Aprano and myself love guessing games, let's have some occasionally please :) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From dfjennings at gmail.com Fri Nov 22 16:07:44 2013 From: dfjennings at gmail.com (Don Jennings) Date: Fri, 22 Nov 2013 10:07:44 -0500 Subject: [Tutor] Two subsequent for loops in one function In-Reply-To: References: Message-ID: On Nov 22, 2013, at 9:24 AM, Rafael Knuth wrote: > Hej there, > > newbie question: I struggle to understand what exactly those two > subsequent for loops in the program below do (Python 3.3.0): > > for x in range(2, 10): > for y in range(2, x): > if x % y == 0: > print(x, "equals", y, "*", x//y) > break > else: > print(x, "is a prime number") Let's step through the code. The outer for loop will iterate over the values of range(2, 10): >>> range(2, 10) [2, 3, 4, 5, 6, 7, 8, 9] So, each time the loop executes, x will be one of the values in that list. The inner loop then checks to see if any values up to but not including that value are evenly divisible by it. Let's choose 5 to see what will happen during that loop. The inner loop will then iterate over the values of range(2, 5): >>> range(2, 5) [2, 3, 4] So, here is what happens during the x % y: >>> 5 % 2 1 >>> 5 % 3 2 >>> 5 % 4 1 It is never equal to 0; the print(x, "is a prime number") will execute. Perhaps it's the "else" clause which is confusing? From the tutorial [1], I quote: When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement?s else clause runs when no exception occurs, and **a loop?s else clause runs when no break occurs**. (emphasis mine) Take care, Don [1] http://docs.python.org/3/tutorial/controlflow.html From steve at pearwood.info Fri Nov 22 16:30:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Nov 2013 02:30:34 +1100 Subject: [Tutor] Is there a package to "un-mangle" characters? In-Reply-To: <1385064259.96702.YahooMailBasic@web163802.mail.gq1.yahoo.com> References: <1385064259.96702.YahooMailBasic@web163802.mail.gq1.yahoo.com> Message-ID: <20131122153033.GL2085@ando> On Thu, Nov 21, 2013 at 12:04:19PM -0800, Albert-Jan Roskam wrote: > Hi, > > Today I had a csv file in utf-8 encoding, but part of the accented > characters were mangled. The data were scraped from a website and it > turned out that at least some of the data were mangled on the website > already. Bits of the text were actually cp1252 (or cp850), I think, > even though the webpage was in utf-8 Is there any package that helps > to correct such issues? Python has superpowers :-) http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/ -- Steven From dyoo at hashcollision.org Fri Nov 22 20:34:06 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 22 Nov 2013 11:34:06 -0800 Subject: [Tutor] Two subsequent for loops in one function In-Reply-To: References: Message-ID: I agree with Peter Otten. I want to try restating what he said to try to emphasize what I think is the key point. One basic skill that you learn as a programmer is how to handle nesting. One strategy is to give things names. This can have benefits: 1. The name itself might make the code easier to read. 2. The thing being named might be simpler to understand in isolation to the whole. So when we look at the original program here here: > for x in range(2, 10): > for y in range(2, x): > if x % y == 0: > print(x, "equals", y, "*", x//y) > break > else: > print(x, "is a prime number") we can start to tease it apart, by giving names to sections of the program. Imagine a box or contour being drawn around the inner loop: for x in range(2, 10): +------------------------------------------------------ | for y in range(2, x): | if x % y == 0: | print(x, "equals", y, "*", x//y) | break | else: | print(x, "is a prime number") ------------------------------------------------------ We can give that thing a name! We can do this naming with functions. Here's one approach: let's take that inner loop and make it into its own function. ################################# def InnerLoop(x): for y in range(2, x): if x % y == 0: print(x, "equals", y, "*", x//y) break else: print(x, "is a prime number") for x in range(2, 10): InnerLoop(x) ################################# This is fairly mechanical: see what variables are "free" in the body of the thing we're pulling out and make them arguments to the function. Here, the inner loop depends on the value of x, so that's why it becomes an argument in the function we've named "InnerLoop". We can do this extract-and-name process again and again: good taste tells us where we can take things too far and make the resulting code look silly. For example, we might do the same to the "x % y == 0" part of the inner loop's computation. This might look something like this: ################################# def IsDivisibleBy(x, y): """Returns true if y divides evenly into x.""" return x % y == 0 def InnerLoop(x): for y in range(2, x): if IsDivisibleBy(x, y): print(x, "equals", y, "*", x//y) break else: print(x, "is a prime number") for x in range(2, 10): InnerLoop(x) ################################# This might be taking naming too far. Some people can see "x % y == 0" and know that this is essentially a divisibility test. But hopefully the point is clear: if some piece of code is complex, you might be able to take a reductionist approach, pull it apart, and give names so you can look at the loops in isolation, rather than all together. Reductionism doesn't always work in all contexts: sometimes we can chop up the code so much that the result don't hold together. Figuring out where that balance is takes experience. I'm still trying to learn the right balance myself. :P Now, by the way, "InnerLoop" is an absolutely horrible name. Can you take a look at that function in isolation and describe what it is doing? If so, you can rename InnerLoop to something more appropriate. That's what I think Peter's point is in his naming of the inner loop to "unknown". Don't leave it named that way. Once you figure out what it's doing, give it a good name. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Fri Nov 22 20:54:25 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 22 Nov 2013 11:54:25 -0800 Subject: [Tutor] Issue w/ while loops In-Reply-To: References: Message-ID: > Ok, got you! > > print("TIME TRACKING") > > while True: > hours_worked = input("How many hours did you work today? ") > try: > hours_worked = float(hours_worked) > break > except ValueError: > print ("Invalid input") > if hours_worked < 24: > print("You must be a human.") > else: > print("You must be a cyborg.") > Here's an example where naming the while loop might be helpful in making the code easier to understand. Or not. :P Let's see what this might look like. First, let's take the while loop and make it a function: ######################################################### def GiveMeAGoodName(): while True: hours_worked = input("How many hours did you work today? ") try: hours_worked = float(hours_worked) break except ValueError: print ("Invalid input") return hours_worked print("TIME TRACKING") hours_worked = GiveMeAGoodName() if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") ######################################################### Here, the function-extracting is a little more complex, because there's an implicit passing of data from one part of the program to the other. The loop continues to run till hours_worked is a good float, after which the rest of the program uses that float. So that's why the "GiveMeAGoodName" returns something. We can look at GiveMeAGoodName(): it's tryingt to get the number of hours worked. Let's call it "AskForHoursWorked". ########################################################### def AskForHoursWorked(): while True: hours_worked = input("How many hours did you work today? ") try: hours_worked = float(hours_worked) break except ValueError: print ("Invalid input") return hours_worked print("TIME TRACKING") hours_worked = AskForHoursWorked() if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") ######################################################### If we have a better feeling for how control flow interacts with functions, we might simplify the lines in AskForHoursWorked() a little bit. Here's one restatement of that function that does the same thing: ######################################################### def AskForHoursWorked(): while True: hours_worked = input("How many hours did you work today? ") try: return float(hours_worked) except ValueError: print ("Invalid input") ######################################################### I'd argue that this is a little clearer because, in this variation, hours_worked is now definitely just a string throughout the program's run. It doesn't waffle between being a string and being a number. The function itself is a little shorter because we can do a "return" to get out of the function, rather than do the "assign the value, break, then return" that we had in the original code. Best of wishes! -------------- next part -------------- An HTML attachment was scrubbed... URL: From imrosebaga at gmail.com Fri Nov 22 22:02:13 2013 From: imrosebaga at gmail.com (Imrose Baga) Date: Fri, 22 Nov 2013 13:02:13 -0800 Subject: [Tutor] raw input program is still running. Message-ID: Hi I've just started using python. I tried to use raw input for name, city and state. But only my name shows up and then when i try to close the program, it is showed as still running and asks if I wish to kill the program. please any help -- Regards, Imrose Baga -------------- next part -------------- An HTML attachment was scrubbed... URL: From rudaguerman at gmail.com Fri Nov 22 17:25:06 2013 From: rudaguerman at gmail.com (Ruben Guerrero) Date: Fri, 22 Nov 2013 11:25:06 -0500 Subject: [Tutor] Extarcting data tables from a text file Message-ID: Dear tutor, I am a beginner in python and I need your guidance to write a python script to extract many nxn data tables of variable nunber of rows from a text file as in the following example Condensed to atoms (all electrons): 1 2 3 4 5 6 1 Cl 0.000000 0.304108 -0.101110 -0.108502 -0.108502 0.024111 2 C 0.304108 0.000000 0.515965 0.332621 0.332621 -0.004054 3 C -0.101110 0.515965 0.000000 -0.013334 -0.013334 0.352916 4 H -0.108502 0.332621 -0.013334 0.000000 -0.133436 -0.028924 5 H -0.108502 0.332621 -0.013334 -0.133436 0.000000 -0.028924 6 H 0.024111 -0.004054 0.352916 -0.028924 -0.028924 0.000000 7 H -0.030910 -0.074027 0.364085 -0.053300 0.048704 -0.123402 8 H -0.030910 -0.074027 0.364085 0.048704 -0.053300 -0.123402 7 8 1 Cl -0.030910 -0.030910 2 C -0.074027 -0.074027 3 C 0.364085 0.364085 4 H -0.053300 0.048704 5 H 0.048704 -0.053300 6 H -0.123402 -0.123402 7 H 0.000000 -0.118520 8 H -0.118520 0.000000 Mulliken atomic charges: to other text file with the numerical information in the table concatenated by columns. The phrases in red always delimite the tables in the original file. In the python generated file I need the following: a text flag (maybe a line with the "O" charanter) delimiting each table, a second line with the total number of rows (atoms) in the table followed by a line with the ordered string of chemical symbols separated by a silgle space. My aim is load the numerical data from this file to a c++ program to process this information. Thanks in advance. -Ruben. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Fri Nov 22 22:57:37 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sat, 23 Nov 2013 07:57:37 +1000 Subject: [Tutor] raw input program is still running. In-Reply-To: References: Message-ID: On Sat, Nov 23, 2013 at 7:02 AM, Imrose Baga wrote: > Hi I've just started using python. I tried to use raw input for name, city > and state. But only my name shows up and then when i try to close the > program, it is showed as still running and asks if I wish to kill the > program. please any help Please share your program. -- http://echorand.me From steve at pearwood.info Sat Nov 23 00:50:23 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Nov 2013 10:50:23 +1100 Subject: [Tutor] raw input program is still running. In-Reply-To: References: Message-ID: <20131122235022.GM2085@ando> On Fri, Nov 22, 2013 at 01:02:13PM -0800, Imrose Baga wrote: > Hi I've just started using python. I tried to use raw input for name, city > and state. But only my name shows up and then when i try to close the > program, it is showed as still running and asks if I wish to kill the > program. please any help Just a moment, let me get my crystal ball and see what you are doing... I see... nothing. Perhaps my crystal ball is out of order? Next time, please help us to help you by showing the code you are running, since crystal balls are often inaccurate, and while inspecting the entrails of animals is always correct, it does tend to me smelly and messy. You can interrupt whatever Python is doing this way: * click on the window that is running Python * hold down the Control key * press the C key. You may need to do that a couple of times. Or, you can just close the window and kill the program, that will be harmless. -- Steven From breamoreboy at yahoo.co.uk Sat Nov 23 02:08:28 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 23 Nov 2013 01:08:28 +0000 Subject: [Tutor] Extarcting data tables from a text file In-Reply-To: References: Message-ID: On 22/11/2013 16:25, Ruben Guerrero wrote: > Dear tutor, > > I am a beginner in python and I need your guidance to write a python > script to extract many nxn data tables of variable nunber of rows from > a text file as in the following example > > Condensed to atoms (all electrons): > 1 2 3 4 5 6 > 1 Cl 0.000000 0.304108 -0.101110 -0.108502 -0.108502 > 0.024111 > 2 C 0.304108 0.000000 0.515965 0.332621 0.332621 > -0.004054 > 3 C -0.101110 0.515965 0.000000 -0.013334 -0.013334 > 0.352916 > 4 H -0.108502 0.332621 -0.013334 0.000000 -0.133436 > -0.028924 > 5 H -0.108502 0.332621 -0.013334 -0.133436 0.000000 > -0.028924 > 6 H 0.024111 -0.004054 0.352916 -0.028924 -0.028924 > 0.000000 > 7 H -0.030910 -0.074027 0.364085 -0.053300 0.048704 > -0.123402 > 8 H -0.030910 -0.074027 0.364085 0.048704 -0.053300 > -0.123402 > 7 8 > 1 Cl -0.030910 -0.030910 > 2 C -0.074027 -0.074027 > 3 C 0.364085 0.364085 > 4 H -0.053300 0.048704 > 5 H 0.048704 -0.053300 > 6 H -0.123402 -0.123402 > 7 H 0.000000 -0.118520 > 8 H -0.118520 0.000000 > Mulliken atomic charges: > > to other text file with the numerical information in the table > concatenated by columns. The phrases in red always delimite the tables > in the original file. In the python generated file I need the following: > a text flag (maybe a line with the "O" charanter) delimiting each > table, a second line with the total number of rows (atoms) in the table > followed by a line with the ordered string of chemical symbols separated > by a silgle space. > > My aim is load the numerical data from this file to a c++ program to > process this information. > > Thanks in advance. > > -Ruben. > I'm sorry but we don't write code for you here. I suggest that you start out by reading the tutorial here http://docs.python.org/3/tutorial/index.html, try writing something and when and if you run into problems please feel free to get back to us. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From davnobezimeni at gmail.com Sat Nov 23 02:19:46 2013 From: davnobezimeni at gmail.com (Davnobezimeni Sasha Balagura) Date: Sat, 23 Nov 2013 03:19:46 +0200 Subject: [Tutor] Using tkinter::ttk::treeview to implement data view. Message-ID: Hello. I have to implement parcer for .txt file with special formating. There are a lot of data to display, modify, add. I decided to use tkinter::ttk:treeviev for this. And it really good one, very fast and good looking..but.. But I cant set borders between cells, like in Excel. Is it real at all for this widget? Or i've just overlooked something? Best regards, Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.steele1 at gmail.com Fri Nov 22 23:08:25 2013 From: paul.steele1 at gmail.com (Paul Steele) Date: Fri, 22 Nov 2013 16:08:25 -0600 Subject: [Tutor] numrows returning -1 Message-ID: Hey all... I am getting a numrows count of -1 when I print numrows (see line 23 of the code). What does "-1" mean? I think my connection is working and my table has data. Here's my code... #!/usr/bin/python # -*- coding: utf-8 -*- import mysql.connector from mysql.connector import errorcode try: con = mysql.connector.connect(user='root', password='pw848596', host='127.0.0.1', database='mydb') except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print("Database does not exists") else: print(err) else: cur=con.cursor() cur.execute("select Name from Rosters") numrows = cur.rowcount print numrows for x in xrange(0,numrows): row = cursor.fetchone() print "Name" con.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 23 03:27:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Nov 2013 02:27:27 +0000 Subject: [Tutor] Using tkinter::ttk::treeview to implement data view. In-Reply-To: References: Message-ID: On 23/11/13 01:19, Davnobezimeni Sasha Balagura wrote: > I have to implement parcer for .txt file with special formating. There > are a lot of data to display, modify, add. I decided to use > tkinter::ttk:treeviev for this. And it really good one, very fast and > good looking..but.. > But I cant set borders between cells, like in Excel. Is it real at all > for this widget? Or i've just overlooked something? There has been very little discussion of the ttk widgets on the tutor list so I'm not sure that many folks here use them (I know I've been meaning to play for a while). You might get a better response on the Tkinter mailing list (also available on gmane.org as gmane.comp.python.tkinter) HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sat Nov 23 03:33:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Nov 2013 02:33:58 +0000 Subject: [Tutor] numrows returning -1 In-Reply-To: References: Message-ID: On 22/11/13 22:08, Paul Steele wrote: > I am getting a numrows count of -1 when I print numrows (see line 23 of > the code). What does "-1" mean? I think my connection is working > and my table has data. I don't know about MySQL but the sqlite3 module documentation says: ------- As required by the Python DB API Spec, the rowcount attribute ?is -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface?. This includes SELECT statements because we cannot determine the number of rows a query produced until all rows were fetched. -------- That may help but you should check the docs for the mysql module for details of that implementation. Also I notice something odd in your code: cur.execute("select Name from Rosters") numrows = cur.rowcount print numrows for x in xrange(0,numrows): row = cursor.fetchone() #AG - You never use row? print "Name" #AG - just prints the literal string You do realize that this will not print the names retrieved? It will print the literal string "Name" once for each row found. I suspect that's not what you want? Check the examples on the sqlite3 module page for examples (in sqlite) of how to do what (I think) you want. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From fomcl at yahoo.com Sat Nov 23 13:12:35 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 23 Nov 2013 04:12:35 -0800 (PST) Subject: [Tutor] Is there a package to "un-mangle" characters? In-Reply-To: <20131122153033.GL2085@ando> Message-ID: <1385208755.86663.YahooMailBasic@web163804.mail.gq1.yahoo.com> -------------------------------------------- On Fri, 11/22/13, Steven D'Aprano wrote: Subject: Re: [Tutor] Is there a package to "un-mangle" characters? To: tutor at python.org Date: Friday, November 22, 2013, 4:30 PM On Thu, Nov 21, 2013 at 12:04:19PM -0800, Albert-Jan Roskam wrote: > Hi, > > Today I had a csv file in utf-8 encoding, but part of the accented > characters were mangled. The data were scraped from a website and it > turned out that at least some of the data were mangled on the website > already. Bits of the text were actually cp1252 (or cp850), I think, > even though the webpage was in utf-8 Is there any package that helps > to correct such issues? Python has superpowers :-) http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/ ====> Cool website! Love the corny terminology he uses. The function he created may be useful in situations where chardet, charset and icu may not be useful: a small amount of textual data that's a total mess. From satheesan.varier at gmail.com Sat Nov 23 04:04:13 2013 From: satheesan.varier at gmail.com (Satheesan Varier) Date: Fri, 22 Nov 2013 22:04:13 -0500 Subject: [Tutor] raw input program is still running. Message-ID: Re : raw input program is still running. No Code ? Mostly, you are in an infinite loop >>> for n in range(2): raw_input("name : ") raw_input("city : ") name : first name 'first name' city : first city 'first city' name : second name 'second name' city : second city 'second city' >>> >>> while True: raw_input("name : ") raw_input("city : ") print flag=raw_input("continue ..? ( Y ) : ") if flag != 'Y' : break name : a 'a' city : b 'b' continue ..? ( Y ) : Y name : c 'c' city : d 'd' continue ..? ( Y ) : y >>> On Fri, Nov 22, 2013 at 9:23 PM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > https://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. raw input program is still running. (Imrose Baga) > 2. Extarcting data tables from a text file (Ruben Guerrero) > 3. Re: raw input program is still running. (Amit Saha) > 4. Re: raw input program is still running. (Steven D'Aprano) > 5. Re: Extarcting data tables from a text file (Mark Lawrence) > 6. Using tkinter::ttk::treeview to implement data view. > (Davnobezimeni Sasha Balagura) > 7. numrows returning -1 (Paul Steele) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 22 Nov 2013 13:02:13 -0800 > From: Imrose Baga > To: tutor at python.org > Subject: [Tutor] raw input program is still running. > Message-ID: > < > CAPS79oiCwyQ6N3sYa5HSuRApCd3PzND0sVeYXUyyAKDmz9jeRQ at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi I've just started using python. I tried to use raw input for name, city > and state. But only my name shows up and then when i try to close the > program, it is showed as still running and asks if I wish to kill the > program. please any help > -- > Regards, > > Imrose Baga > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131122/937778c1/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Fri, 22 Nov 2013 11:25:06 -0500 > From: Ruben Guerrero > To: tutor at python.org > Subject: [Tutor] Extarcting data tables from a text file > Message-ID: > < > CAB44GdocQsHoPjrxb3a4YFziPhAD886Jv7YujdhAgZy1iSEXoQ at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Dear tutor, > > I am a beginner in python and I need your guidance to write a python > script to extract many nxn data tables of variable nunber of rows from a > text file as in the following example > > Condensed to atoms (all electrons): > 1 2 3 4 5 6 > 1 Cl 0.000000 0.304108 -0.101110 -0.108502 -0.108502 > 0.024111 > 2 C 0.304108 0.000000 0.515965 0.332621 0.332621 > -0.004054 > 3 C -0.101110 0.515965 0.000000 -0.013334 -0.013334 > 0.352916 > 4 H -0.108502 0.332621 -0.013334 0.000000 -0.133436 > -0.028924 > 5 H -0.108502 0.332621 -0.013334 -0.133436 0.000000 > -0.028924 > 6 H 0.024111 -0.004054 0.352916 -0.028924 -0.028924 > 0.000000 > 7 H -0.030910 -0.074027 0.364085 -0.053300 0.048704 > -0.123402 > 8 H -0.030910 -0.074027 0.364085 0.048704 -0.053300 > -0.123402 > 7 8 > 1 Cl -0.030910 -0.030910 > 2 C -0.074027 -0.074027 > 3 C 0.364085 0.364085 > 4 H -0.053300 0.048704 > 5 H 0.048704 -0.053300 > 6 H -0.123402 -0.123402 > 7 H 0.000000 -0.118520 > 8 H -0.118520 0.000000 > Mulliken atomic charges: > > to other text file with the numerical information in the table > concatenated by columns. The phrases in red always delimite the tables in > the original file. In the python generated file I need the following: a > text flag (maybe a line with the "O" charanter) delimiting each table, a > second line with the total number of rows (atoms) in the table followed by > a line with the ordered string of chemical symbols separated by a silgle > space. > > My aim is load the numerical data from this file to a c++ program to > process this information. > > Thanks in advance. > > -Ruben. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131122/b4aa577d/attachment-0001.html > > > > ------------------------------ > > Message: 3 > Date: Sat, 23 Nov 2013 07:57:37 +1000 > From: Amit Saha > To: Imrose Baga > Cc: "tutor at python.org" > Subject: Re: [Tutor] raw input program is still running. > Message-ID: > z-LqJqsW_+NaUeM3_NyE+yb3E-VUMg at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On Sat, Nov 23, 2013 at 7:02 AM, Imrose Baga wrote: > > Hi I've just started using python. I tried to use raw input for name, > city > > and state. But only my name shows up and then when i try to close the > > program, it is showed as still running and asks if I wish to kill the > > program. please any help > > Please share your program. > > > > -- > http://echorand.me > > > ------------------------------ > > Message: 4 > Date: Sat, 23 Nov 2013 10:50:23 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] raw input program is still running. > Message-ID: <20131122235022.GM2085 at ando> > Content-Type: text/plain; charset=us-ascii > > On Fri, Nov 22, 2013 at 01:02:13PM -0800, Imrose Baga wrote: > > Hi I've just started using python. I tried to use raw input for name, > city > > and state. But only my name shows up and then when i try to close the > > program, it is showed as still running and asks if I wish to kill the > > program. please any help > > Just a moment, let me get my crystal ball and see what you are doing... > > I see... nothing. Perhaps my crystal ball is out of order? Next time, > please help us to help you by showing the code you are running, since > crystal balls are often inaccurate, and while inspecting the entrails of > animals is always correct, it does tend to me smelly and messy. > > > You can interrupt whatever Python is doing this way: > > * click on the window that is running Python > > * hold down the Control key > > * press the C key. > > You may need to do that a couple of times. > > Or, you can just close the window and kill the program, that will be > harmless. > > > > -- > Steven > > > ------------------------------ > > Message: 5 > Date: Sat, 23 Nov 2013 01:08:28 +0000 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] Extarcting data tables from a text file > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 22/11/2013 16:25, Ruben Guerrero wrote: > > Dear tutor, > > > > I am a beginner in python and I need your guidance to write a python > > script to extract many nxn data tables of variable nunber of rows from > > a text file as in the following example > > > > Condensed to atoms (all electrons): > > 1 2 3 4 5 6 > > 1 Cl 0.000000 0.304108 -0.101110 -0.108502 -0.108502 > > 0.024111 > > 2 C 0.304108 0.000000 0.515965 0.332621 0.332621 > > -0.004054 > > 3 C -0.101110 0.515965 0.000000 -0.013334 -0.013334 > > 0.352916 > > 4 H -0.108502 0.332621 -0.013334 0.000000 -0.133436 > > -0.028924 > > 5 H -0.108502 0.332621 -0.013334 -0.133436 0.000000 > > -0.028924 > > 6 H 0.024111 -0.004054 0.352916 -0.028924 -0.028924 > > 0.000000 > > 7 H -0.030910 -0.074027 0.364085 -0.053300 0.048704 > > -0.123402 > > 8 H -0.030910 -0.074027 0.364085 0.048704 -0.053300 > > -0.123402 > > 7 8 > > 1 Cl -0.030910 -0.030910 > > 2 C -0.074027 -0.074027 > > 3 C 0.364085 0.364085 > > 4 H -0.053300 0.048704 > > 5 H 0.048704 -0.053300 > > 6 H -0.123402 -0.123402 > > 7 H 0.000000 -0.118520 > > 8 H -0.118520 0.000000 > > Mulliken atomic charges: > > > > to other text file with the numerical information in the table > > concatenated by columns. The phrases in red always delimite the tables > > in the original file. In the python generated file I need the following: > > a text flag (maybe a line with the "O" charanter) delimiting each > > table, a second line with the total number of rows (atoms) in the table > > followed by a line with the ordered string of chemical symbols separated > > by a silgle space. > > > > My aim is load the numerical data from this file to a c++ program to > > process this information. > > > > Thanks in advance. > > > > -Ruben. > > > > I'm sorry but we don't write code for you here. I suggest that you > start out by reading the tutorial here > http://docs.python.org/3/tutorial/index.html, try writing something and > when and if you run into problems please feel free to get back to us. > > -- > Python is the second best programming language in the world. > But the best has yet to be invented. Christian Tismer > > Mark Lawrence > > > > ------------------------------ > > Message: 6 > Date: Sat, 23 Nov 2013 03:19:46 +0200 > From: Davnobezimeni Sasha Balagura > To: tutor at python.org > Subject: [Tutor] Using tkinter::ttk::treeview to implement data view. > Message-ID: > < > CAA7iXku8_KD9wsn+8xFQRFU9YhDMobgq1kXAsN7fhxPt5iC_AQ at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hello. > I have to implement parcer for .txt file with special formating. There are > a lot of data to display, modify, add. I decided to use > tkinter::ttk:treeviev for this. And it really good one, very fast and good > looking..but.. > But I cant set borders between cells, like in Excel. Is it real at all for > this widget? Or i've just overlooked something? > > Best regards, > Alex > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131123/0599771c/attachment-0001.html > > > > ------------------------------ > > Message: 7 > Date: Fri, 22 Nov 2013 16:08:25 -0600 > From: Paul Steele > To: tutor at python.org > Subject: [Tutor] numrows returning -1 > Message-ID: > < > CALD6M00nU1usQD0OdeRb4SQTPWiDiNQRZWwxN15UUdptAx4iqg at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hey all... > > I am getting a numrows count of -1 when I print numrows (see line 23 of the > code). What does "-1" mean? I think my connection is working and my > table has data. > > Here's my code... > > #!/usr/bin/python > # -*- coding: utf-8 -*- > > import mysql.connector > from mysql.connector import errorcode > > try: > con = mysql.connector.connect(user='root', password='pw848596', > host='127.0.0.1', > database='mydb') > except mysql.connector.Error as err: > if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: > print("Something is wrong with your user name or password") > elif err.errno == errorcode.ER_BAD_DB_ERROR: > print("Database does not exists") > else: > print(err) > else: > cur=con.cursor() > > cur.execute("select Name from Rosters") > numrows = cur.rowcount > print numrows > for x in xrange(0,numrows): > row = cursor.fetchone() > print "Name" > > con.close() > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20131122/bf7c39de/attachment.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > https://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 117, Issue 44 > ************************************** > -- Warm regards. Satheesan Varier 860 (970) 2732 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafael.knuth at gmail.com Sat Nov 23 18:44:43 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sat, 23 Nov 2013 18:44:43 +0100 Subject: [Tutor] Strange issue w/ Python shell 3.0.0. Message-ID: Hej there, I noticed that sometimes when I do lots of modifications within a program, I get runtime errors even if the program is "clean". I realized that first time when I copy and pasted a program into a new window - it miraculously ran without any problems. Although it was exactly the same program that caused problems in the old window. Stupid rookie question: Does Python shell have a cache or so? And if that's the case - how do I empty it? Rafael From steve at pearwood.info Sat Nov 23 19:07:40 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Nov 2013 05:07:40 +1100 Subject: [Tutor] Strange issue w/ Python shell 3.0.0. In-Reply-To: References: Message-ID: <20131123180739.GS2085@ando> On Sat, Nov 23, 2013 at 06:44:43PM +0100, Rafael Knuth wrote: > Hej there, > > I noticed that sometimes when I do lots of modifications within a > program, I get runtime errors even if the program is "clean". I > realized that first time when I copy and pasted a program into a new > window - it miraculously ran without any problems. Although it was > exactly the same program that caused problems in the old window. > > Stupid rookie question: Does Python shell have a cache or so? And if > that's the case - how do I empty it? ??? Your question unfortunately doesn't make a lot of sense to me. A cache for what? I suspect you are operating under an assumption which seems to make sense to you, but isn't actually correct. I think, if I were to answer your literal question, I would say "No", the Python shell doesn't have a cache. But the Python compiler has all sorts of caches, regardless of whether it is running in the shell or not. It caches modules. It caches all sorts of objects. But this shouldn't be a problem under normal circumstances. My guess is that it isn't a cache that is causing problems, but a misinterpretation of what you are seeing. But I could be wrong. Can you explain in detail what you mean by "when I do lots of modifications within a program", "runtime errors", and especially what you mean by calling the program "clean"? How are you making modifications to the program? How then do you see the errors? ... let me think... are you using reload()? Because that doesn't work like you might be thinking. When you reload a module, it doesn't affect objects which are already in use. Likewise with importing. But since I don't know how you are making modifications, or what you are doing that generates runtime errors, I can't tell what you're doing wrong. Oh, wait, I see you are using Python 3.0. Don't. Python 3.0 is not supported because it is buggy. You should use 3.1, or better still, 3.3. Python 3.3 is much better than 3.1 or 3.2, and 3.0 is buggy and slow. -- Steven From rafael.knuth at gmail.com Sat Nov 23 19:51:59 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sat, 23 Nov 2013 19:51:59 +0100 Subject: [Tutor] Strange issue w/ Python shell 3.0.0. In-Reply-To: <20131123180739.GS2085@ando> References: <20131123180739.GS2085@ando> Message-ID: > Oh, wait, I see you are using Python 3.0. Don't. Python 3.0 is not > supported because it is buggy. You should use 3.1, or better still, 3.3. > Python 3.3 is much better than 3.1 or 3.2, and 3.0 is buggy and slow. What I was trying to say is that sometimes I get runtime errors even if nothing's wrong with my code. I had those issues with Python 3.3.0 ... I wrote a program and when I executed it, and a runtime error occured. I then copy and pasted that into a new window, I saved it and - surprise, surprise - it ran without any issues. Although I didn't modify my program in any ways. That's why I came up with that question that might sound odd to you whether Python shell somehow "caches" older, buggy versions of my program which I saved previously ... From rafael.knuth at gmail.com Sat Nov 23 20:57:54 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sat, 23 Nov 2013 20:57:54 +0100 Subject: [Tutor] Two subsequent for loops in one function - I got it! Message-ID: @Peter @Steven @Don @Danny thank you *so much" for explaining the concept of a nested for loop! Your simplified example Steven made it very clear to me: for x in range(2, 7): print("outer loop, x =", x) for y in range(2, x): print("inner loop, x =", x, "y =", y) I have only one question left. Here's my original program again: for x in range(2, 10): for y in range(2, x): if x % y == 0: print(x, "equals", y, "*", x//y) break else: print(x, "is a prime number") So the first output of the outer loop is: 2. It's then passed to the inner loop: for y in range(2,x): if x % y == 0: ... And I was wondering what is happening inside that loop. The output of for y in range (2,2): should be ... none - correct? What exactly happens on the next line of code? if x % y == 0 To me it looks like if 2 % "no value" == 0 is executed here which I assume causes the loop to break - correct? Just want to understand how Python deals with "no values" within a program. Thanks in advance! All the best, Raf From dfjennings at gmail.com Sat Nov 23 21:26:52 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 23 Nov 2013 15:26:52 -0500 Subject: [Tutor] Two subsequent for loops in one function - I got it! In-Reply-To: References: Message-ID: <85B3862A-F0EC-4E7F-A6D6-FD9091A443F2@gmail.com> On Nov 23, 2013, at 2:57 PM, Rafael Knuth wrote: > > The output of > > for y in range (2,2): > > should be ... none - correct? No, it's not none. It's an empty list; thus, python executes nothing inside the inner loop. >>> range(2,2) [] >>> for y in range(2,2): ... print 'yes, I made it to here' ... >>> See? It has no output. By the way, the python REPL is your friend! Use it often when you can't figure out what is happening. Take care, Don From rafael.knuth at gmail.com Sat Nov 23 21:54:38 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sat, 23 Nov 2013 21:54:38 +0100 Subject: [Tutor] Two subsequent for loops in one function - I got it! In-Reply-To: <85B3862A-F0EC-4E7F-A6D6-FD9091A443F2@gmail.com> References: <85B3862A-F0EC-4E7F-A6D6-FD9091A443F2@gmail.com> Message-ID: > See? It has no output. By the way, the python REPL is your friend! Use it often when you can't figure out what is happening. Oh, I didn't even know that such a thing exists :-) Cool! Unfortunately, I only found Python REPLs for version 2.7.2 or lower. Is there a REPL for 3.3.0 ..? Thanks, Raf From randolph.michael.sm at gmail.com Sat Nov 23 22:30:02 2013 From: randolph.michael.sm at gmail.com (Randolph Scott-McLaughlin II) Date: Sat, 23 Nov 2013 16:30:02 -0500 Subject: [Tutor] Depth First Search Listing all possible combinations Message-ID: [image: Inline image 2][image: Inline image 1]Hi Tutors, So I'm writing code for a depth first search where I have 1 start point and 1 end point. Between those points there are a series of 1-way roads that goes from one vertex to the next. Sometimes the vertex can have 4 or 5 one way road paths going into it or out of it. What I want to do is list each unique possible path someone can go from the start to end point, have the list written out and ideally labeled as "list'n'". Here's some code that I started off with but I keep getting errors and in general can't get it to do what I want it to do. If you could guide me in the right direction or tell me how I can alter the code I've been coming across to fit my needs that'd be great. I've also attached an image of the road map that I'm trying to develop, along with the decisional points that each vertex can take someone to and from. Thanks for help! #start=q9 q9 = (10, 33) q10 = (11, 28, 29, 30) q11 = (15) q16 = (17,19,24) q18 = (17, 19, 24) q24 = (25, 26) q27 = (34) q28 = (29, 30) q30 = (12, 31, 34) q32 = (34) q33 = (15, 30) q35 = (36, 37) q37 = (38, 39) q39 = (40, 41, 99) #end = 99 #trying new DFS code parent = {s:None} def DFS_VISIT(V, Adj,s): for v in Adj[s]: s.inprocess=True if v not in parent: s.inprocess=False parent[v]=s DFS_VISIT(V,Adj,s) #dfs visit code, controls checking notes around you def dfs(V,Adj): parent = {} for s in V: if s not in parent: parent[s] = None DFS_VISIT(V,Adj,s) #dfs has you start from any new vertex point possible This is about as far as I've gotten writing my own code. I have found some other DFS algorithms but I'm not sure how to adapt it to fit my needs. import sys def extractPaths(current_node,path,loops_seen): path.append(current_node) # if node has outgoing edges if nodes[current_node]!=None: for thatnode in nodes[current_node]: valid=True # if the node we are going to has been # visited before, we are completeing # a loop. if thatnode-1 in path: i=len(path)-1 # find the last time we visited # that node while path[i]!=thatnode-1: i-=1 # the last time, to this time is # a single loop. new_loop=path[i:len(path)] # if we haven't seen this loop go to # the node and node we have seen this # loop. else don't go to the node. if new_loop in loops_seen: valid=False else: loops_seen.append(new_loop) if valid: extractPaths(thatnode-1,path,loops_seen) # this is the end of the path else: newpath=list() # increment all the values for printing for i in path: newpath.append(i+1) found_paths.append(newpath) # backtrack path.pop() # graph defined by lists of outgoing edges nodes=[[2],[3],[4],[5,9],[6,7],[7],[4,8],None,None] # I tried this but it didn't work nodes=zip(['q9','q10','q11','q16','q18','q24','q27','q28','q30','q32','q33','q35','q37','q39'],[(10,33),(11, 28, 29, 30), (15),(17,19,24),(25, 26),(34),(29, 30),(34),(15, 30),(36, 37),(38, 39),(40, 41, None)]) #also tried this but it ididn't work nodes = {1: [2, 3],2: [1, 4, 5, 6],3: [1, 4],4: [2, 3, 5],5: [2, 4, 6],6: [2, 5]} found_paths=list() extractPaths(0,list(),list()) for i in found_paths: print(i) Best, Randy -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image (3).jpeg Type: image/jpeg Size: 1321086 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image (1).jpeg Type: image/jpeg Size: 1295221 bytes Desc: not available URL: From alan.gauld at btinternet.com Sat Nov 23 23:06:24 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Nov 2013 22:06:24 +0000 Subject: [Tutor] Two subsequent for loops in one function - I got it! In-Reply-To: References: <85B3862A-F0EC-4E7F-A6D6-FD9091A443F2@gmail.com> Message-ID: On 23/11/13 20:54, Rafael Knuth wrote: >> See? It has no output. By the way, the python REPL is your friend! > Unfortunately, I only found Python REPLs for version 2.7.2 or lower. > Is there a REPL for 3.3.0 ..? The REPL (read?eval?print loop) is the >>> prompt. You type stuff in and Python reads it(R), evaluates it(E), prints the result(P) and then asks for more input to read(L). It exists in every version of Python and is frequently underestimated in its power to unravel what python is doing. In other words, just play with the interpreter... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From marc.tompkins at gmail.com Sat Nov 23 23:46:56 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 23 Nov 2013 14:46:56 -0800 Subject: [Tutor] Issue w/ while loops In-Reply-To: References: Message-ID: On Sat, Nov 23, 2013 at 8:30 AM, Rafael Knuth wrote: > Marc, > > great feedback - thank you very much! > I will bear that in mind for the future. > > I modified my program as you suggested, but I received a runtime > error; I tried to fix that but unfortunately I didn't succeed. > The modified program executes well only when the user input has the > correct format (integer or float) and it breaks when the user enters a > string (at that point the program should print ("Invalid input") and > loop back to its beginning). > Can you please advise how I should change the program? > Thank you so much! > Raf > > Here's the original program: > > print("TIME TRACKING") > > while True: > hours_worked = input("How many hours did you work today? ") > try: > hours_worked = float(hours_worked) > break > except ValueError: > print ("Invalid input") > if hours_worked < 24: > print("You must be a human.") > else: > print("You must be a cyborg.") > > Here's the modified version: > > print("TIME TRACKING") > > hours_worked = "Invalid input" > while hours_worked == "Invalid input": > hours_worked = input("How many hours did you work today? ") > try: > hours_worked = float(hours_worked) > break > except ValueError: > print ("Invalid input") > if hours_worked < 24: > print("You must be a human.") > else: > print("You must be a cyborg.") > > And here's the error message I get: > > >>> > TIME TRACKING > How many hours did you work today? very long hours > Invalid input > Traceback (most recent call last): > File "C:\Users\Rafael_Knuth\Desktop\Rookies At > Work\Python\TimeReckord.py", line 12, in > if hours_worked < 24: > TypeError: unorderable types: str() < int() > >>> > The TypeError is basically just telling you that there's no meaningful way to compare the string "very long hours" with the integer 24. I should have recommended an exit condition more along the lines of checking whether hours_worked was still a string, like so: while isinstance(hours_worked, str) What I actually had in mind was to put the assignment to hours_worked inside the try/except - initialize it to a value that will keep you inside the loop, and only change its value to something that will escape the loop if the user enters a valid value. Like so: hours_worked = "Invalid input" while isinstance(hours_worked, str): try: hours_worked = float(raw_input("How many hours did you work today? ")) except ValueError: print ("Invalid input") if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") Note that I changed "input" to raw_input; I'm still using Python 2.7. If you're using Python 3, please disregard. In any case, the objective I was after was to make the "break" unnecessary. "Break"ing out of a loop should only happen in unusual cases; it shouldn't be the primary flow control. (Not because it's necessarily less efficient, or computationally wrong - but because a future maintainer will have to drill down into the loop to figure out what's happening.) If your IDE supports collapsing indented sections, it should be possible to understand the code flow without fully expanding it - or at least that's what I strive for. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 24 01:13:12 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Nov 2013 00:13:12 +0000 Subject: [Tutor] Depth First Search Listing all possible combinations In-Reply-To: References: Message-ID: On 23/11/13 21:30, Randolph Scott-McLaughlin II wrote: > Inline image 2Inline image 1Hi Tutors, > > So I'm writing code for a depth first search where I have 1 start point > and 1 end point. Between those points there are a series of 1-way roads > that goes from one vertex to the next. Sometimes the vertex can have 4 > or 5 one way road paths going into it or out of it. > > What I want to do is list each unique possible path someone can go from > the start to end point, have the list written out and ideally labeled as > "list'n'". > > Here's some code that I started off with but I keep getting errors What kind of errors? And if there are error messages please provide copies of the entire error message not just a summary. They are usually extremely informative. > in general can't get it to do what I want it to do. What do you expect? What do you get? Don't force us to try to run it, guess what it should do, then assess what it is doing. Tell us. > If you could guide me in the right direction or tell me how I can > alter the code I've been coming across to fit my needs that'd > be great. We can try but you need to tell us more detail too. > I've also attached an image of the road map that I'm trying to develop, > along with the decisional points that each vertex can take someone to > and from. Thanks for help! It may be helpful to somebody but not to me! :-( > #start=q9 > q9 = (10, 33) > q10 = (11, 28, 29, 30) > q11 = (15) > q16 = (17,19,24) > q18 = (17, 19, 24) > q24 = (25, 26) > q27 = (34) > q28 = (29, 30) > q30 = (12, 31, 34) > q32 = (34) > q33 = (15, 30) > q35 = (36, 37) > q37 = (38, 39) > q39 = (40, 41, 99) > #end = 99 Could you do a smaller example that exhibits the problem? > #trying new DFS code > parent = {s:None} > def DFS_VISIT(V, Adj,s): > for v in Adj[s]: > s.inprocess=True > if v not in parent: > s.inprocess=False > parent[v]=s > DFS_VISIT(V,Adj,s) You are using recursion but its not clear how you stop the recursion. Possibly when all elements of Adj[s] are not parents? But it looks lie you never use V and don't change Adj either. So I'm not sur4e how often this will recurse, but it may be more than the fixed limit compiled into Python. Is that one of the errors you get? > #dfs visit code, controls checking notes around you > def dfs(V,Adj): > parent = {} > for s in V: > if s not in parent: > parent[s] = None > DFS_VISIT(V,Adj,s) Note that you define a new 'parent' here. This is local to this function and hides the parent defined above DFS. But DFS will continue to use the one defined at the top. Is that what you expected? Its usually better to create unique names to avoid confusion. I have no idea what the stuff below does, it's way too much for me to try to wade through. I can't see any sign of you calling dfs() or DFS_VISIT() so I don't know what the connection is. I gave up at that point. Sorry. > import sys > > def extractPaths(current_node,path,loops_seen): > path.append(current_node) > # if node has outgoing edges > if nodes[current_node]!=None: > for thatnode in nodes[current_node]: > valid=True > # if the node we are going to has been > # visited before, we are completeing > # a loop. > if thatnode-1 in path: > i=len(path)-1 > # find the last time we visited > # that node > while path[i]!=thatnode-1: > i-=1 > # the last time, to this time is > # a single loop. > new_loop=path[i:len(path)] > # if we haven't seen this loop go to > # the node and node we have seen this > # loop. else don't go to the node. > if new_loop in loops_seen: > valid=False > else: > loops_seen.append(new_loop) > if valid: > extractPaths(thatnode-1,path,loops_seen) > # this is the end of the path > else: > newpath=list() > # increment all the values for printing > for i in path: > newpath.append(i+1) > found_paths.append(newpath) > # backtrack > path.pop() > > # graph defined by lists of outgoing edges > nodes=[[2],[3],[4],[5,9],[6,7],[7],[4,8],None,None] > # I tried this but it didn't work > nodes=zip(['q9','q10','q11','q16','q18','q24','q27','q28','q30','q32','q33','q35','q37','q39'],[(10,33),(11, > 28, 29, 30), (15),(17,19,24),(25, 26),(34),(29, 30),(34),(15, 30),(36, > 37),(38, 39),(40, 41, None)]) > #also tried this but it ididn't work nodes = {1: [2, 3],2: [1, 4, 5, > 6],3: [1, 4],4: [2, 3, 5],5: [2, 4, 6],6: [2, 5]} > found_paths=list() > extractPaths(0,list(),list()) > for i in found_paths: > print(i) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From steve at pearwood.info Sun Nov 24 01:35:29 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Nov 2013 11:35:29 +1100 Subject: [Tutor] Two subsequent for loops in one function - I got it! In-Reply-To: References: <85B3862A-F0EC-4E7F-A6D6-FD9091A443F2@gmail.com> Message-ID: <20131124003529.GT2085@ando> On Sat, Nov 23, 2013 at 09:54:38PM +0100, Rafael Knuth wrote: > > See? It has no output. By the way, the python REPL is your friend! > > Use it often when you can't figure out what is happening. > > Oh, I didn't even know that such a thing exists :-) Cool! > Unfortunately, I only found Python REPLs for version 2.7.2 or lower. > Is there a REPL for 3.3.0 ..? Every version of Python has a REPL, also known as the interactive shell or interactive interpreter. That includes Jython and IronPython, and I presume others such as PyPy (which I have not used). If you launch Python from your operating system's command line with no arguments, like this: python or give the version number: python3.3 it will launch the interactive interpreter. Depending on your operating system, you may need to provide the full path to the executable. You might also like to investigate IPython and bpython, which are enhanced REPLs. IPython adds shell-like features and a Mathematica-like interface, and is mostly aimed at the scientific community. bpython adds colour and other goodies. -- Steven From steve at pearwood.info Sun Nov 24 01:48:19 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Nov 2013 11:48:19 +1100 Subject: [Tutor] Two subsequent for loops in one function - I got it! In-Reply-To: References: Message-ID: <20131124004819.GW2085@ando> On Sat, Nov 23, 2013 at 08:57:54PM +0100, Rafael Knuth wrote: > I have only one question left. > Here's my original program again: > > for x in range(2, 10): > for y in range(2, x): > if x % y == 0: > print(x, "equals", y, "*", x//y) > break > else: > print(x, "is a prime number") > > So the first output of the outer loop is: 2. > It's then passed to the inner loop: > > for y in range(2,x): > if x % y == 0: > ... > > And I was wondering what is happening inside that loop. Absolutely nothing! The inner loop doesn't get executed. Python first generates the range object range(2, 2) which is empty (it starts at 2 and stops at 2). Since y iterates over an empty list, the loop immediately exits and the body gets executed zero times. > The output of > > for y in range (2,2): > > should be ... none - correct? Not quite "none", more like *nothing*. There's no output at all, because the body isn't executed even once. [...] > Just want to understand how Python deals with "no values" within a program. It doesn't. Things always have a value, if they are executed at all. But if they don't get executed, then they don't exist at all. if False: # This code never runs! print("This will never be printed") x = 23 print(x) At this point (unless x happened to have been defined even earlier in the code), trying to print x will cause a NameError -- the name 'x' doesn't exist. -- Steven From steve at pearwood.info Sun Nov 24 02:09:58 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Nov 2013 12:09:58 +1100 Subject: [Tutor] Strange issue w/ Python shell 3.0.0. In-Reply-To: References: <20131123180739.GS2085@ando> Message-ID: <20131124010958.GX2085@ando> On Sat, Nov 23, 2013 at 07:51:59PM +0100, Rafael Knuth wrote: > > Oh, wait, I see you are using Python 3.0. Don't. Python 3.0 is not > > supported because it is buggy. You should use 3.1, or better still, 3.3. > > Python 3.3 is much better than 3.1 or 3.2, and 3.0 is buggy and slow. > > What I was trying to say is that sometimes I get runtime errors even > if nothing's wrong with my code. > I had those issues with Python 3.3.0 ... I wrote a program and when I > executed it, and a runtime error occured. > I then copy and pasted that into a new window, I saved it and - > surprise, surprise - it ran without any issues. Although I didn't > modify my program in any ways. Are you perhaps using IDLE? Without seeing exactly what you mean, I'm not sure, but I *think* what is happening is something like this example. In Window #1, you have something like this: py> class Test: ... attr = 23 ... def test(): # oops a bug ... print(self.attr) ... py> x = Test() py> x.test() # failure! Traceback (most recent call last): File "", line 1, in TypeError: test() takes no arguments (1 given) py> py> # edit the Test class ... class Test: ... attr = 23 ... def test(self): # Fixed! ... print(self.attr) ... py> x.test() # but the error doesn't go away! Traceback (most recent call last): File "", line 1, in TypeError: test() takes no arguments (1 given) So then you copy and paste the Test class into Window #2, where it works perfectly: py> class Test: ... attr = 23 ... def test(self): # Fixed! ... print(self.attr) ... py> y = Test() py> y.test() 23 What's going on? It's not that Python has a cache, well, I suppose in a vague sense it does, but that *you* inadvertently have a cache. The problem is back in Window #1, where you have x = Test() with the buggy version of the method (missing the "self" argument). I must admit I kinda lied in the comment to this bit: py> # edit the Test class ... class Test: ... attr = 23 ... def test(self): # Fixed! ... print(self.attr) I didn't "edit the Test class" at all, although it looks like it. I actually created a NEW Test class, that looks the same except for the fixed bug. But x still belongs to the OLD Test class, so it still experiences the same bug, since as far as it is concerned, nothing has changed. What's going on here may be a little more clear if we avoid classes and just look at simple values: py> s = "Hello Wolrd!" # Oops a typo! py> motd = "The message of the day is: " + s py> print(motd) # oops, this is buggy The message of the day is: Hello Wolrd! py> s = "Hello World!" # Edit s to fix the typo. py> print(motd) # but motd has no way of knowing that The message of the day is: Hello Wolrd! Again, the same lie: I haven't actually edited s, and even if I had, it wouldn't effect motd. I've created a new s, which replaces the old one, but anything which was created from the old one will see no change. I can't tell if this is the problem you're experiencing, but from my experience as a beginner, it seems a reasonable chance. So, what to do about it? While the Python interactive interpreter is mighty powerful, it does have some limitations, and this is one of them. You just have to get used to the fact that it is not well-suited for editing large blocks of code. It is excellent for trying out small snippets, or for running blocks of code that don't have to change, but not for editing and running at the same time (at least not until you're experienced enough to deal with errors like this one). -- Steven From rafael.knuth at gmail.com Sun Nov 24 08:51:41 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sun, 24 Nov 2013 08:51:41 +0100 Subject: [Tutor] Strange issue w/ Python shell 3.0.0. In-Reply-To: <20131124010958.GX2085@ando> References: <20131123180739.GS2085@ando> <20131124010958.GX2085@ando> Message-ID: > So, what to do about it? While the Python interactive interpreter is > mighty powerful, it does have some limitations, and this is one of them. > You just have to get used to the fact that it is not well-suited for > editing large blocks of code. It is excellent for trying out small > snippets, or for running blocks of code that don't have to change, but > not for editing and running at the same time (at least not until you're > experienced enough to deal with errors like this one). Understood. Should I use a Python IDE like Pycharm or so? Would that help? If so, which ones would you recommend? From alan.gauld at btinternet.com Sun Nov 24 10:04:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Nov 2013 09:04:38 +0000 Subject: [Tutor] Strange issue w/ Python shell 3.0.0. In-Reply-To: References: <20131123180739.GS2085@ando> <20131124010958.GX2085@ando> Message-ID: On 24/11/13 07:51, Rafael Knuth wrote: >> So, what to do about it? While the Python interactive interpreter is >> mighty powerful, it does have some limitations, and this is one of them. >> You just have to get used to the fact that it is not well-suited for >> editing large blocks of code. ... > > Understood. Should I use a Python IDE like Pycharm or so? Would that help? > If so, which ones would you recommend? IDLE is fine (assuming Steven is right and you are using IDLE) but get used to opening an edit window and creating the script there and then running that rather than typing everything into the Python Shell window. You can still use the shell to try out small snippets of code but anything bigger goes in a separate file. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From rafael.knuth at gmail.com Sun Nov 24 11:24:43 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sun, 24 Nov 2013 11:24:43 +0100 Subject: [Tutor] Fibonacci Series Message-ID: Hej there, I am making a couple wrong assumptions about the program below, but I do not know where my thinking mistake is. I have some trouble understanding what exactly happens within this loop here: a, b = 0, 1 while b < 10: print(b) a, b = b, a +b What I would expect as an outcome of that while loop, is: >> 1 2 4 8 Here's my (wrong) assumption about that while loop: 1st loop: Pretty much straight forward, as b = 1 on the first line of code. >> 1 2nd loop (the output of the 1st loop is "reused" inside the 2nd loop which is: b = 1): a = b = 1 b = a + b = 1 + 1 = 2 >> 2 3rd loop: a = b = 2 b = a + b = 2 + 2 = 4 >> 4 3rd loop: a = b = 4 b = a + b = 4 + 4 = 8 break. Instead, that program's correct output is: >> 1 1 2 3 5 8 I understand what a Fibonacci Series is, but I struggle to understand what's happening inside that while loop above. Also, I would assume that an arbitrary integer can be assigned to "a" on the first line as what really matters (in my understanding) is the new value assigned to "a" within the loop. This assumption is wrong as well: a, b = 999, 1 while b < 10: print(b) a, b = b, a +b >>> 1 The while loop breaks after b = 1 is printed out. ... which makes me wonder, because I would expect a = 999 to be changed to a = b = 1 after the first loop and the program should execute the 2nd loop in my understanding ... Can anyone clarify please? Thank you! All the best, Raf From nik at naturalnet.de Sun Nov 24 11:40:06 2013 From: nik at naturalnet.de (Dominik George) Date: Sun, 24 Nov 2013 11:40:06 +0100 Subject: [Tutor] Fibonacci Series In-Reply-To: References: Message-ID: <20131124104005.GD5299@keks.naturalnet.de> Hi, > a, b = b, a +b > a = b = 1 > b = a + b = 1 + 1 = 2 Your issue is that you interpret the assignment wrong. You seem to think that it assigns b to a and THEN a+b to b, which is not the case. The right side of the assignment creates a tuple, and the left side unpacks it. It is the same as: t = (b, a+b) a = t[0] b = t[1] You see that a has not been assigned yet when the second part is calculated. Cheers, Nik -- * mirabilos is handling my post-1990 smartphone * Aaah, it vibrates! Wherefore art thou, demonic device?? PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From davea at davea.name Sun Nov 24 12:33:05 2013 From: davea at davea.name (Dave Angel) Date: Sun, 24 Nov 2013 06:33:05 -0500 Subject: [Tutor] Fibonacci Series In-Reply-To: References: Message-ID: On Sun, 24 Nov 2013 11:24:43 +0100, Rafael Knuth wrote: > a, b = b, a +b > a = b = 1 > b = a + b = 1 + 1 = 2 I suggest you play with the statement a bit. Print out both values each time through the loop. The expression b, a+b produces a tuple. The left side a, b *unpacks* that tuple into the two variables.a and b. Perhaps a simpler case might help. Try a, b = b, a What would you expect it to do and why? -- DaveA From rafael.knuth at gmail.com Sun Nov 24 14:05:43 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sun, 24 Nov 2013 14:05:43 +0100 Subject: [Tutor] Fibonacci Series In-Reply-To: References: Message-ID: Now I got it, thanks :-) a, b = b, b + a ... I was was wrongly assuming that "a" and "b" on the left side "talk" to each other and that "a" tells "b" something like: "Hey 'b' ... I just assigned another value to you, make sure you execute it." But "a" and "b" don't talk to each other. Each of them executes what it is supposed to and doesn't take notice of what its neighbor variable does. The more sophisticated explanation (from my view point as an absolute beginner who's not familiar with most programming concepts yet) is that "a" and "b" on the left side are unchangable tuples and they simply get unpacked on the right side. I wrote an even more primitive program which helped me understand what *exactly* happens with "a" and "b" with each run: # 1st run a, b = 1, 5 print(a) # 1 print(b) # 5 # 2nd run a, b = b, b + a print(a) # a = b = 5 print(b) # b + a = 5 + 1 = 6 # 3rd run a, b = b, b + a print(a) # a = b = 6 print(b) # b + a = 6 + 5 = 11 # 4th run a, b = b, b + a print(a) # a = b = 11 print(b) # b + a = 11 + 6 = 17 # 5th run a, b = b, b + a print(a) # a = b = 17 print(b) # b + a = 17 + 11 = 28 # 6th run a, b = b, b + a print(a) # a = b = 28 print(b) # b + a = 28 + 17 0 45 All the best, Raf On Sun, Nov 24, 2013 at 12:33 PM, Dave Angel wrote: > On Sun, 24 Nov 2013 11:24:43 +0100, Rafael Knuth > wrote: > >> a, b = b, a +b >> > > > a = b = 1 >> b = a + b = 1 + 1 = 2 >> > > I suggest you play with the statement a bit. Print out both values each > time through the loop. > > The expression b, a+b produces a tuple. The left side a, b *unpacks* that > tuple into the two variables.a and b. > > Perhaps a simpler case might help. Try a, b = b, a What would you expect > it to do and why? > > -- > DaveA > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Nov 24 15:58:48 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Nov 2013 01:58:48 +1100 Subject: [Tutor] Strange issue w/ Python shell 3.0.0. In-Reply-To: References: <20131123180739.GS2085@ando> <20131124010958.GX2085@ando> Message-ID: <20131124145847.GY2085@ando> On Sun, Nov 24, 2013 at 08:51:41AM +0100, Rafael Knuth wrote: > > So, what to do about it? While the Python interactive interpreter is > > mighty powerful, it does have some limitations, and this is one of them. > > You just have to get used to the fact that it is not well-suited for > > editing large blocks of code. It is excellent for trying out small > > snippets, or for running blocks of code that don't have to change, but > > not for editing and running at the same time (at least not until you're > > experienced enough to deal with errors like this one). > > Understood. Should I use a Python IDE like Pycharm or so? Would that help? > If so, which ones would you recommend? I have never found an IDE I really like. Actually, that's not quite true. Back in the late 1980s and early 1990s I had two IDEs I loved, although they weren't called IDEs back then because the TLA hadn't been invented. One was Apple's Hypercard, which was not just an IDE but a runtime GUI environment as well, and the other was Think's Pascal compiler. These days, my IDE of choice is called Linux. I have a web browser open for looking up code and help files on the internet, and a text editor open with at least two files (the program I'm working on, and a second program to test it). I prefer KDE 3's "kate" editor, like nearly everything about KDE version 4 is worse, but at a pinch Gnome's gedit will do. I also run a terminal that supports multiple tabs. I have at least three tabs open in the terminal: - one for running Linux commands and managing source control; - one for testing or running my program, which I normally do with a couple of commands: python myfile.py python myfile_tests.py - one open to a Python interactive interpreter, for testing code snippets. So that's three windows, and at least half a dozen tabs between them. I say at least, because the number of tabs in the terminal tends to rise and fall, or in the case of the browser, rise and rise and rise and rise. (Currently I have 110 browser tabs split over two browsers and four windows. Curse you Internet, why do you have so much interesting stuff?!) More here: http://blog.sanctum.geek.nz/series/unix-as-ide/ http://michaelochurch.wordpress.com/2013/01/09/ide-culture-vs-unix-philosophy/ And now I have 112 browser tabs open... -- Steven From alan.gauld at btinternet.com Sun Nov 24 16:48:03 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Nov 2013 15:48:03 +0000 Subject: [Tutor] Fibonacci Series In-Reply-To: References: Message-ID: On 24/11/13 13:05, Rafael Knuth wrote: > "a" and "b" on the left side are unchangable tuples and they simply get > unpacked on the right side. Be careful about terminology here. a,b is a single tuple with two values. But a and b are variables not tuples. Tuples are collections of (one or more) values. In python they are separated by commas. Thus a single valued tuple looks like (5,) A double valued tuple like (3,4) And so on. Note the parentheses are optional and only needed for disambiguating the tuple. 3,4 is also a double valued tuple. Variables are names that refer to values. A value can be any Python object (including a tuple!). So a = None a = 5 a = 's' a = (1,2) are all valid values for the variable 'a' And t = ( (1,2), (2,3) ) is a single tuple composed of two other tuples. So a,b = 3,4 is assigning the tuple on the right side to the tuple on the left. It *simultaneously* assigns 3 to a and 4 to b. It doesn't matter what a and b were storing previously it creates a new tuple on the right and assigns it to another newly created one on the left. Note that the right side could be an existing tuple but the one on the left is always a new tuple. Thus a,b = t # see above would only create one new tuple (on the left) and a would have the value t[0], or (1,2) and b would be t[1] or (2,3). The final thing that makes your case complicated is that a,b appear on both sides of the assignment. But if you remember that the assignments are effectively happening simultaneously it all follows the same rules. Tuple assignment/unpacking is a powerful technique in Python. Without it we would need to introduce extra variables so that a,b = b, a+b would become old_a = a a = b b = old_a + b HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From randolph.michael.sm at gmail.com Sun Nov 24 02:41:21 2013 From: randolph.michael.sm at gmail.com (Randolph Scott-McLaughlin II) Date: Sat, 23 Nov 2013 20:41:21 -0500 Subject: [Tutor] Depth First Search Listing all possible combinations In-Reply-To: References: Message-ID: So I cleaned up the code to make it readable. I'm not getting an error message now. What I'm getting is an empty bracket. I want to run find_all_paths with my graph and then list the start and end point (in this case that's q9 and q42) and then have it list a tuple of each path in a separate line. Each path being a unique way to get to the end point. Here's what I enter and I get back [] >>> find_all_paths(graph, 'q9', 'q42') [] What I want is >>> find_all_paths(graph, 'q9', 'q42') [q9, q10, q11 ,q15, q16, q17, q18, q20, q23, q34, q35, q36, q37, q38, q39, q41, q42, end] [then list another path.] [list another path] graph = {'q9': ['q10', 'q33'], 'q10': ['q11', 'q 28', 'q29', 'q30'], 'q11': ['q15'] , 'q16': ['q17', 'q19', 'q24'],' q18': ['q20'], 'q23': ['q34'], 'q24': ['q25', 'q26'], 'q27': ['q34'], 'q28': ['q30', 'q29'], 'q30': ['q34', 'q31', 'q12'], 'q32': ['q34'], 'q33': ['q15' , 'q30'], 'q35': ['q36', 'q37'], 'q37': ['q38', 'q39'], 'q39': ['q41', 'q40', 'q42'],'q42': ['end']} def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if not graph.has_key(start): return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths On Sat, Nov 23, 2013 at 7:13 PM, Alan Gauld wrote: > On 23/11/13 21:30, Randolph Scott-McLaughlin II wrote: > >> Inline image 2Inline image 1Hi Tutors, >> >> >> So I'm writing code for a depth first search where I have 1 start point >> and 1 end point. Between those points there are a series of 1-way roads >> that goes from one vertex to the next. Sometimes the vertex can have 4 >> or 5 one way road paths going into it or out of it. >> >> What I want to do is list each unique possible path someone can go from >> the start to end point, have the list written out and ideally labeled as >> "list'n'". >> >> Here's some code that I started off with but I keep getting errors >> > > What kind of errors? > And if there are error messages please provide copies of the entire error > message not just a summary. They are usually extremely > informative. > > > in general can't get it to do what I want it to do. >> > > What do you expect? What do you get? > Don't force us to try to run it, guess what it should do, > then assess what it is doing. > Tell us. > > > If you could guide me in the right direction or tell me how I can >> > > alter the code I've been coming across to fit my needs that'd > > be great. > > We can try but you need to tell us more detail too. > > > I've also attached an image of the road map that I'm trying to develop, >> along with the decisional points that each vertex can take someone to >> and from. Thanks for help! >> > > It may be helpful to somebody but not to me! :-( > > > #start=q9 >> q9 = (10, 33) >> q10 = (11, 28, 29, 30) >> q11 = (15) >> q16 = (17,19,24) >> q18 = (17, 19, 24) >> q24 = (25, 26) >> q27 = (34) >> q28 = (29, 30) >> q30 = (12, 31, 34) >> q32 = (34) >> q33 = (15, 30) >> q35 = (36, 37) >> q37 = (38, 39) >> q39 = (40, 41, 99) >> #end = 99 >> > > Could you do a smaller example that exhibits the problem? > > > #trying new DFS code >> parent = {s:None} >> def DFS_VISIT(V, Adj,s): >> for v in Adj[s]: >> s.inprocess=True >> if v not in parent: >> s.inprocess=False >> parent[v]=s >> DFS_VISIT(V,Adj,s) >> > > You are using recursion but its not clear how you stop > the recursion. Possibly when all elements of Adj[s] are > not parents? But it looks lie you never use V and > don't change Adj either. So I'm not sur4e how often > this will recurse, but it may be more than the fixed > limit compiled into Python. Is that one of the errors > you get? > > > #dfs visit code, controls checking notes around you >> def dfs(V,Adj): >> parent = {} >> for s in V: >> if s not in parent: >> parent[s] = None >> DFS_VISIT(V,Adj,s) >> > > Note that you define a new 'parent' here. This is local to this function > and hides the parent defined above DFS. But DFS will > continue to use the one defined at the top. Is that what you expected? > Its usually better to create unique names to avoid confusion. > > I have no idea what the stuff below does, it's way too much > for me to try to wade through. I can't see any sign of you > calling dfs() or DFS_VISIT() so I don't know what the > connection is. I gave up at that point. Sorry. > > > import sys >> >> def extractPaths(current_node,path,loops_seen): >> path.append(current_node) >> # if node has outgoing edges >> if nodes[current_node]!=None: >> for thatnode in nodes[current_node]: >> valid=True >> # if the node we are going to has been >> # visited before, we are completeing >> # a loop. >> if thatnode-1 in path: >> i=len(path)-1 >> # find the last time we visited >> # that node >> while path[i]!=thatnode-1: >> i-=1 >> # the last time, to this time is >> # a single loop. >> new_loop=path[i:len(path)] >> # if we haven't seen this loop go to >> # the node and node we have seen this >> # loop. else don't go to the node. >> if new_loop in loops_seen: >> valid=False >> else: >> loops_seen.append(new_loop) >> if valid: >> extractPaths(thatnode-1,path,loops_seen) >> # this is the end of the path >> else: >> newpath=list() >> # increment all the values for printing >> for i in path: >> newpath.append(i+1) >> found_paths.append(newpath) >> # backtrack >> path.pop() >> >> # graph defined by lists of outgoing edges >> nodes=[[2],[3],[4],[5,9],[6,7],[7],[4,8],None,None] >> # I tried this but it didn't work >> nodes=zip(['q9','q10','q11','q16','q18','q24','q27','q28',' >> q30','q32','q33','q35','q37','q39'],[(10,33),(11, >> 28, 29, 30), (15),(17,19,24),(25, 26),(34),(29, 30),(34),(15, 30),(36, >> 37),(38, 39),(40, 41, None)]) >> #also tried this but it ididn't work nodes = {1: [2, 3],2: [1, 4, 5, >> 6],3: [1, 4],4: [2, 3, 5],5: [2, 4, 6],6: [2, 5]} >> found_paths=list() >> extractPaths(0,list(),list()) >> for i in found_paths: >> print(i) >> > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From reuben.dlink at gmail.com Sun Nov 24 17:03:11 2013 From: reuben.dlink at gmail.com (Reuben) Date: Sun, 24 Nov 2013 21:33:11 +0530 Subject: [Tutor] minor display issue with python dictionaries Message-ID: Hi, ########################################## >>> >>> new_dict = {'a':10, 'b' :20, 'c': 30,'d' : 40} >>> >>> >>> print new_dict {'a': 10, 'c': 30, 'b': 20, 'd': 40} >>> ######################################### >From the above output, I see key 'c' is at third position during input, but while displaying the output it is displayed at second position Although, I dont see any impact of it since we mainly refer to dictionary values only using "keys" -- but just for curiosity why is this position change? Regards, Reuben -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Nov 24 17:55:29 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 24 Nov 2013 11:55:29 -0500 Subject: [Tutor] minor display issue with python dictionaries In-Reply-To: References: Message-ID: On Sun, Nov 24, 2013 at 11:03 AM, Reuben wrote: > Hi, > > ########################################## >>>> >>>> new_dict = {'a':10, 'b' :20, 'c': 30,'d' : 40} >>>> >>>> >>>> print new_dict > {'a': 10, 'c': 30, 'b': 20, 'd': 40} >>>> > > > ######################################### > > > From the above output, I see key 'c' is at third position during input, but > while displaying the output it is displayed at second position > > Although, I dont see any impact of it since we mainly refer to dictionary > values only using "keys" -- but just for curiosity why is this position > change? > > Regards, > Reuben > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > The key is the way to the value. Depending on the implementation, python might find the value by different algorithms. Sometimes people call dictionaries 'hashes', which I believe refers to a method of indexing that does some algorithm on the key to get the value location. This is for speed and for space savings in memory. So, sometimes you might see a dictionary displayed in the order you entered it, but sometimes not. -- Joel Goldstick http://joelgoldstick.com From rafael.knuth at gmail.com Sun Nov 24 22:32:20 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Sun, 24 Nov 2013 22:32:20 +0100 Subject: [Tutor] Else vs. Continue Message-ID: Hej there, I stumbled upon the "continue" statement and to me it looks like it does exactly the same as else. I tested both else and continue in a little program and I don't see any differences between both. Is my assumption correct or wrong? If the latter is the case: Can you give me examples of continue usage that couldn't be done with else? Here's my code sample I mentioned above: for num in range(2,10): if num % 2 == 0: print("Found an even number", num) continue print("Found a number", num) Same program with else: for num in range(2,10): if num % 2 == 0: print("Found an even number", num) else: print("Found a number", num) Thanks in advance! All the best, Raf From amitsaha.in at gmail.com Sun Nov 24 22:34:58 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Mon, 25 Nov 2013 07:34:58 +1000 Subject: [Tutor] minor display issue with python dictionaries In-Reply-To: References: Message-ID: On Mon, Nov 25, 2013 at 2:55 AM, Joel Goldstick wrote: > On Sun, Nov 24, 2013 at 11:03 AM, Reuben wrote: >> Hi, >> >> ########################################## >>>>> >>>>> new_dict = {'a':10, 'b' :20, 'c': 30,'d' : 40} >>>>> >>>>> >>>>> print new_dict >> {'a': 10, 'c': 30, 'b': 20, 'd': 40} >>>>> >> >> >> ######################################### >> >> >> From the above output, I see key 'c' is at third position during input, but >> while displaying the output it is displayed at second position >> >> Although, I dont see any impact of it since we mainly refer to dictionary >> values only using "keys" -- but just for curiosity why is this position >> change? >> >> Regards, >> Reuben >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > The key is the way to the value. Depending on the implementation, > python might find the value by different algorithms. Sometimes people > call dictionaries 'hashes', which I believe refers to a method of > indexing that does some algorithm on the key to get the value > location. This is for speed and for space savings in memory. > > So, sometimes you might see a dictionary displayed in the order you > entered it, but sometimes not. And if order is important, you should look at using OrderedDict [1]. See here [2] for examples. [1] http://docs.python.org/2/library/collections.html#collections.OrderedDict [2] http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes Best, Amit. -- http://echorand.me From nik at naturalnet.de Sun Nov 24 22:41:13 2013 From: nik at naturalnet.de (Dominik George) Date: Sun, 24 Nov 2013 22:41:13 +0100 Subject: [Tutor] Else vs. Continue In-Reply-To: References: Message-ID: <20131124214112.GF5299@keks.naturalnet.de> Hi, > I stumbled upon the "continue" statement and to me it looks like it > does exactly the same as else. I tested both else and continue in a > little program and I don't see any differences between both. Is my > assumption correct or wrong? If the latter is the case: Can you give > me examples of continue usage that couldn't be done with else? In general, you can translate quite many code samples into different ones. The difference is that else is used in an if control block, and continue is used only in loops and does exactly one thing: Skip the rest of the loop body, and begin the next iteration. Of course, you could do a lot of tests in the loop and use a lot of else: pass blocks that, after hitting a point where you want to escape the loop, skip the rest of the effective code, but that's cumbersome. If you want to exit a loop at a certain point, just use continue (or break to skip all remaining operations). To add to your confusion: while loops do have an else part in Python: while CONDITION: ... do something ... else: ... do something else ... The else part is executed exactly in the case that CONDITION is no longer True - but *not* when you break from the loop before that. -nik -- * concerning Mozilla code leaking assertion failures to tty without D-BUS * That means, D-BUS is a tool that makes software look better than it actually is. PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From joel.goldstick at gmail.com Sun Nov 24 23:02:59 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 24 Nov 2013 17:02:59 -0500 Subject: [Tutor] Else vs. Continue In-Reply-To: <20131124214112.GF5299@keks.naturalnet.de> References: <20131124214112.GF5299@keks.naturalnet.de> Message-ID: On Sun, Nov 24, 2013 at 4:41 PM, Dominik George wrote: > Hi, > >> I stumbled upon the "continue" statement and to me it looks like it >> does exactly the same as else. I tested both else and continue in a >> little program and I don't see any differences between both. Is my >> assumption correct or wrong? If the latter is the case: Can you give >> me examples of continue usage that couldn't be done with else? I applaud your industrious exploration lately. Don't forget the Python website. I googled 'python continue' and got this: http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops Google is your friend! https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com From alan.gauld at btinternet.com Sun Nov 24 23:38:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Nov 2013 22:38:44 +0000 Subject: [Tutor] Else vs. Continue In-Reply-To: References: Message-ID: On 24/11/13 21:32, Rafael Knuth wrote: > I stumbled upon the "continue" statement and to me it looks like it > does exactly the same as else. I tested both else and continue in a > little program and I don't see any differences between both. > for num in range(2,10): > if num % 2 == 0: > print("Found an even number", num) > continue > print("Found a number", num) > > Same program with else: > > for num in range(2,10): > if num % 2 == 0: > print("Found an even number", num) > else: > print("Found a number", num) It's certainly possible to use an if/else to mimic the behaviour of a continue, and in languages without continue that's exactly what you'd do. But consider this example which puts the continue inside the else clause: for num in range(7): if num%2 == 0: print 'its even' else: print 'its odd' continue evens.append(num) It's easy enough to do that without using continue but its not as simple as saying its the same as the else clause. The other difference is the amount of processing done. Let's assume we have a complex function that takes a long time to execute that we need to use in a secondary if test. Using continue can avoid that overhead. Lets say we have one that checks if a number is prime because we only want to collect prime numbers: primes = [] for n in range(1000) if n%2 == 0: even numbers aren't prime continue else: if isPrime(n): primes.append(n) Now the continue means the isPrime test never gets executed, saving a lot of processing. Without continue you would need to execute the test and the only way to save the time would be to move the n%2 test inside the isPrime() function - which you may not always be able to do easily - or wrap the isPrime like so: def myPrime(n): if n%2 == 0: return False else: return isPrime(n) and make the loop do this: primes = [] for n in range(1000): if myPrime(n): primes.append(n) But that still incurs a little bit extra cost in calling myPrime(). So in general, yes, you can always replace continue with an if/else but it often results in less efficient code, or code that's less readable (more indentation levels etc). HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Sun Nov 24 23:53:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Nov 2013 22:53:29 +0000 Subject: [Tutor] Else vs. Continue In-Reply-To: References: Message-ID: On 24/11/13 22:38, Alan Gauld wrote: Responding to my own post, never a good sign :-( > primes = [] > for n in range(1000) > if n%2 == 0: even numbers aren't prime > continue > else: > if isPrime(n): > primes.append(n) > > Now the continue means the isPrime test never gets executed, > saving a lot of processing. Without continue you would need > to execute the test and the only way to save the time would > be to move the n%2 test inside the isPrime() function As soon as I posted it I realized that wasn't true, you could do this instead... for n in range(1000): if n%2 == 1: if isPrime(n): primes.append(n) So a bad example, sorry. DeMorgan wins again. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Mon Nov 25 00:28:06 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 24 Nov 2013 23:28:06 +0000 Subject: [Tutor] Else vs. Continue In-Reply-To: <20131124214112.GF5299@keks.naturalnet.de> References: <20131124214112.GF5299@keks.naturalnet.de> Message-ID: On 24/11/2013 21:41, Dominik George wrote: > Hi, > >> I stumbled upon the "continue" statement and to me it looks like it >> does exactly the same as else. I tested both else and continue in a >> little program and I don't see any differences between both. Is my >> assumption correct or wrong? If the latter is the case: Can you give >> me examples of continue usage that couldn't be done with else? > > In general, you can translate quite many code samples into different > ones. > > The difference is that else is used in an if control block, and continue > is used only in loops and does exactly one thing: Skip the rest of the > loop body, and begin the next iteration. > > Of course, you could do a lot of tests in the loop and use a lot of > else: pass blocks that, after hitting a point where you want to escape > the loop, skip the rest of the effective code, but that's cumbersome. > > If you want to exit a loop at a certain point, just use continue (or > break to skip all remaining operations). > > To add to your confusion: while loops do have an else part in Python: > > while CONDITION: > ... do something ... > else: > ... do something else ... > > The else part is executed exactly in the case that CONDITION is no > longer True - but *not* when you break from the loop before that. > > -nik > To add to your confusion: for loops can also have an else part in Python: http://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From steve at pearwood.info Mon Nov 25 02:12:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Nov 2013 12:12:24 +1100 Subject: [Tutor] minor display issue with python dictionaries In-Reply-To: References: Message-ID: <20131125011224.GZ2085@ando> On Sun, Nov 24, 2013 at 09:33:11PM +0530, Reuben wrote: [...] > From the above output, I see key 'c' is at third position during input, but > while displaying the output it is displayed at second position Dictionaries are deliberately made unordered. That means the order that items will be displayed is free to vary, not only from how you entered them, but in principle they might even vary each time you inspect the dict. (They probably won't, but they could.) Python dicts are actually "hash tables", which is a standard computer science data structure that you can look up, but in a nutshell, a hash table is an array indexed by the key's hash value. Why do we care about hash tables? Because they make a really fast and efficient way to look up keys, and from the key get access to a value. Let's start with the simplest way to store a key and value pair, an unsorted table of pairs with a marker indicating "blank", so you know when you've reached the end. Here's an example of a half-filled table: { ("Hello", value), # key first, then some value ("World", value), ("Spam", value), ("Eggs", value), ("Cheese", value), , , , , , } In order to find a key in the table, you have to inspect every position until you reach either the key you are looking for, or , in which case you know that the key is not there. So to find "Eggs", you have to inspect "Hello", "World", "Spam" and finally "Eggs". On average, a successful search takes half as many inspections as there are keys, e.g. if you have 10 keys in the table, you need to inspect 5 positions; if there are 100 keys, you need to inspect 50 positions on average. If there are 1000 keys, you need to inspect 500 positions. This is pretty slow. Imagine looking up a word in a dictionary (a real paper dictionary), but with a twist: the words are in whatever order the dictionary writer first thought of them, not alphabetical order, so for any word you have to start at the beginning and read every single world until you find it. Obviously we can do better, by keeping the words sorted. Our table will look like this: { ("Cheese", value), ("Eggs", value), ("Hello", value), ("Spam", value), ("World", value), , , , , , } In this case, we can use a technique called "binary search" to narrow down the possible places the key might be. This is very much like what you probably do when looking up words in a paper dictionary: flip the dictionary open to the middle, then decide whether you've gone too far or not far enough. Each time, you split the remaining half in half again, until you've narrowed down to the page containing the word you want. In a sorted table with binary search, the savings over an unsorted table can be very high. With 10 keys, on average you will end up inspecting 3 or 4 items, which isn't much improvement over 5 for the unsorted case, but with 100 keys, you will inspect 6 or 7, and with 1000 keys, 9 or 10. With a million keys, you only need to inspect about 20 items to either find the key you are looking for, or determine it isn't there. Can we do better than binary search? Yes we can, and we do so with a hash table, which is what Python dicts are. The secret to the hash table is that instead of putting all the keys at the beginning of the table, we want the entries to be scattered at random all over the place. Only not quite at random, since we need a way to jump straight to the key when asked. That's the *hash function*, which converts a key to an arbitrary, and distinct, index: { , ("World", value), # hash of "World" is 1 ("Cheese", value), # hash of "Cheese" is 2 , , ("Eggs", value), # hash of "Eggs" is 5 , ("Spam", value), # hash of "Spam" is 7 , ("Hello", value), # hash of "Hello" is 9 } So the positions of the keys in the table depend on the keys, not the order you write them down. The advantage of this is that looking for a key requires (near enough to) constant time. If you want to see whether "Eggs" is in the table, it doesn't matter whether there are ten keys or ten billion, it will take exactly the same amount of time: hash the key "Eggs" to give you index 5, look at index 5, it is either there or it isn't. Now, in reality we can't actually guarantee that every hash value is distinct. In real life, a hash table has to deal with "collisions", which is when two different keys have the same hash value, and that will spoil the nice simple constant time performance. But collisions are usually rare, and so when discussing hash tables in broad terms we normally ignore them. In Python, you can calculate the hash value of a key with the hash() function. The exact values you get may depend on the specific version of Python you are using, but to give you an example: py> hash("cat") 405875055 py> hash("hat") 1255409212 py> hash("fat") -750391218 So you can see, by changing just one letter of the key, we get a completely different hash value. A good hash function -- and Python's hash function is good -- will will mix up the positions of keys in a very unpredictable way. The end result of this is that when displaying a dict, keys are shown in whatever order they happen to be inside the hash table. That's unpredicable, depending on the details of the hash function, the actual keys, and whether there have been any collisions or not. If you care about this, it is easy enough to sort the keys before printing them: # instead of this print mydict.keys() # do this print sorted(mydict.keys()) If you care about keeping the insertion order, rather than alphabetical order, you can use an OrderedDict: from collections import OrderedDict but OrderedDicts are slower and use more memory than regular dicts, since they have to track the order that the keys were inserted. -- Steven From joel.goldstick at gmail.com Mon Nov 25 02:22:41 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 24 Nov 2013 20:22:41 -0500 Subject: [Tutor] minor display issue with python dictionaries In-Reply-To: <20131125011224.GZ2085@ando> References: <20131125011224.GZ2085@ando> Message-ID: On Sun, Nov 24, 2013 at 8:12 PM, Steven D'Aprano wrote: > On Sun, Nov 24, 2013 at 09:33:11PM +0530, Reuben wrote: > [...] >> From the above output, I see key 'c' is at third position during input, but >> while displaying the output it is displayed at second position > > Dictionaries are deliberately made unordered. That means the order that > items will be displayed is free to vary, not only from how you entered > them, but in principle they might even vary each time you inspect the > dict. (They probably won't, but they could.) > > Python dicts are actually "hash tables", which is a standard computer > science data structure that you can look up, but in a nutshell, a hash > table is an array indexed by the key's hash value. Why do we care about > hash tables? Because they make a really fast and efficient way to look > up keys, and from the key get access to a value. > > Let's start with the simplest way to store a key and value pair, an > unsorted table of pairs with a marker indicating "blank", so you know > when you've reached the end. Here's an example of a half-filled table: > > { ("Hello", value), # key first, then some value > ("World", value), > ("Spam", value), > ("Eggs", value), > ("Cheese", value), > , > , > , > , > , > } > > In order to find a key in the table, you have to inspect every position > until you reach either the key you are looking for, or , in which > case you know that the key is not there. So to find "Eggs", you have to > inspect "Hello", "World", "Spam" and finally "Eggs". On average, a > successful search takes half as many inspections as there are keys, e.g. > if you have 10 keys in the table, you need to inspect 5 positions; if > there are 100 keys, you need to inspect 50 positions on average. If > there are 1000 keys, you need to inspect 500 positions. > > This is pretty slow. Imagine looking up a word in a dictionary (a real > paper dictionary), but with a twist: the words are in whatever order the > dictionary writer first thought of them, not alphabetical order, so for > any word you have to start at the beginning and read every single world > until you find it. > > Obviously we can do better, by keeping the words sorted. Our table will > look like this: > > { ("Cheese", value), > ("Eggs", value), > ("Hello", value), > ("Spam", value), > ("World", value), > , > , > , > , > , > } > > In this case, we can use a technique called "binary search" to narrow > down the possible places the key might be. This is very much like what > you probably do when looking up words in a paper dictionary: flip the > dictionary open to the middle, then decide whether you've gone too far > or not far enough. Each time, you split the remaining half in half > again, until you've narrowed down to the page containing the word you > want. > > In a sorted table with binary search, the savings over an unsorted table > can be very high. With 10 keys, on average you will end up inspecting 3 > or 4 items, which isn't much improvement over 5 for the unsorted case, > but with 100 keys, you will inspect 6 or 7, and with 1000 keys, 9 or 10. > With a million keys, you only need to inspect about 20 items to either > find the key you are looking for, or determine it isn't there. > > Can we do better than binary search? Yes we can, and we do so with a > hash table, which is what Python dicts are. > > The secret to the hash table is that instead of putting all the keys at > the beginning of the table, we want the entries to be scattered at > random all over the place. Only not quite at random, since we need a way > to jump straight to the key when asked. That's the *hash function*, > which converts a key to an arbitrary, and distinct, index: > > { , > ("World", value), # hash of "World" is 1 > ("Cheese", value), # hash of "Cheese" is 2 > , > , > ("Eggs", value), # hash of "Eggs" is 5 > , > ("Spam", value), # hash of "Spam" is 7 > , > ("Hello", value), # hash of "Hello" is 9 > } > > So the positions of the keys in the table depend on the keys, not the > order you write them down. The advantage of this is that looking for a > key requires (near enough to) constant time. If you want to see whether > "Eggs" is in the table, it doesn't matter whether there are ten keys or > ten billion, it will take exactly the same amount of time: hash the key > "Eggs" to give you index 5, look at index 5, it is either there or it > isn't. > > Now, in reality we can't actually guarantee that every hash value is > distinct. In real life, a hash table has to deal with "collisions", > which is when two different keys have the same hash value, and that will > spoil the nice simple constant time performance. But collisions are > usually rare, and so when discussing hash tables in broad terms we > normally ignore them. > > In Python, you can calculate the hash value of a key with the hash() > function. The exact values you get may depend on the specific version of > Python you are using, but to give you an example: > > py> hash("cat") > 405875055 > py> hash("hat") > 1255409212 > py> hash("fat") > -750391218 > > > So you can see, by changing just one letter of the key, we get a > completely different hash value. A good hash function -- and Python's > hash function is good -- will will mix up the positions of keys in a > very unpredictable way. > > The end result of this is that when displaying a dict, keys are shown in > whatever order they happen to be inside the hash table. That's > unpredicable, depending on the details of the hash function, the actual > keys, and whether there have been any collisions or not. > > If you care about this, it is easy enough to sort the keys before > printing them: > > # instead of this > print mydict.keys() > > # do this > print sorted(mydict.keys()) > > > If you care about keeping the insertion order, rather than alphabetical > order, you can use an OrderedDict: > > from collections import OrderedDict > > > but OrderedDicts are slower and use more memory than regular dicts, > since they have to track the order that the keys were inserted. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor Well explained Stephen -- Joel Goldstick http://joelgoldstick.com From joel.goldstick at gmail.com Mon Nov 25 02:23:26 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 24 Nov 2013 20:23:26 -0500 Subject: [Tutor] minor display issue with python dictionaries In-Reply-To: References: <20131125011224.GZ2085@ando> Message-ID: On Sun, Nov 24, 2013 at 8:22 PM, Joel Goldstick wrote: > On Sun, Nov 24, 2013 at 8:12 PM, Steven D'Aprano wrote: >> On Sun, Nov 24, 2013 at 09:33:11PM +0530, Reuben wrote: >> [...] >>> From the above output, I see key 'c' is at third position during input, but >>> while displaying the output it is displayed at second position >> >> Dictionaries are deliberately made unordered. That means the order that >> items will be displayed is free to vary, not only from how you entered >> them, but in principle they might even vary each time you inspect the >> dict. (They probably won't, but they could.) >> >> Python dicts are actually "hash tables", which is a standard computer >> science data structure that you can look up, but in a nutshell, a hash >> table is an array indexed by the key's hash value. Why do we care about >> hash tables? Because they make a really fast and efficient way to look >> up keys, and from the key get access to a value. >> >> Let's start with the simplest way to store a key and value pair, an >> unsorted table of pairs with a marker indicating "blank", so you know >> when you've reached the end. Here's an example of a half-filled table: >> >> { ("Hello", value), # key first, then some value >> ("World", value), >> ("Spam", value), >> ("Eggs", value), >> ("Cheese", value), >> , >> , >> , >> , >> , >> } >> >> In order to find a key in the table, you have to inspect every position >> until you reach either the key you are looking for, or , in which >> case you know that the key is not there. So to find "Eggs", you have to >> inspect "Hello", "World", "Spam" and finally "Eggs". On average, a >> successful search takes half as many inspections as there are keys, e.g. >> if you have 10 keys in the table, you need to inspect 5 positions; if >> there are 100 keys, you need to inspect 50 positions on average. If >> there are 1000 keys, you need to inspect 500 positions. >> >> This is pretty slow. Imagine looking up a word in a dictionary (a real >> paper dictionary), but with a twist: the words are in whatever order the >> dictionary writer first thought of them, not alphabetical order, so for >> any word you have to start at the beginning and read every single world >> until you find it. >> >> Obviously we can do better, by keeping the words sorted. Our table will >> look like this: >> >> { ("Cheese", value), >> ("Eggs", value), >> ("Hello", value), >> ("Spam", value), >> ("World", value), >> , >> , >> , >> , >> , >> } >> >> In this case, we can use a technique called "binary search" to narrow >> down the possible places the key might be. This is very much like what >> you probably do when looking up words in a paper dictionary: flip the >> dictionary open to the middle, then decide whether you've gone too far >> or not far enough. Each time, you split the remaining half in half >> again, until you've narrowed down to the page containing the word you >> want. >> >> In a sorted table with binary search, the savings over an unsorted table >> can be very high. With 10 keys, on average you will end up inspecting 3 >> or 4 items, which isn't much improvement over 5 for the unsorted case, >> but with 100 keys, you will inspect 6 or 7, and with 1000 keys, 9 or 10. >> With a million keys, you only need to inspect about 20 items to either >> find the key you are looking for, or determine it isn't there. >> >> Can we do better than binary search? Yes we can, and we do so with a >> hash table, which is what Python dicts are. >> >> The secret to the hash table is that instead of putting all the keys at >> the beginning of the table, we want the entries to be scattered at >> random all over the place. Only not quite at random, since we need a way >> to jump straight to the key when asked. That's the *hash function*, >> which converts a key to an arbitrary, and distinct, index: >> >> { , >> ("World", value), # hash of "World" is 1 >> ("Cheese", value), # hash of "Cheese" is 2 >> , >> , >> ("Eggs", value), # hash of "Eggs" is 5 >> , >> ("Spam", value), # hash of "Spam" is 7 >> , >> ("Hello", value), # hash of "Hello" is 9 >> } >> >> So the positions of the keys in the table depend on the keys, not the >> order you write them down. The advantage of this is that looking for a >> key requires (near enough to) constant time. If you want to see whether >> "Eggs" is in the table, it doesn't matter whether there are ten keys or >> ten billion, it will take exactly the same amount of time: hash the key >> "Eggs" to give you index 5, look at index 5, it is either there or it >> isn't. >> >> Now, in reality we can't actually guarantee that every hash value is >> distinct. In real life, a hash table has to deal with "collisions", >> which is when two different keys have the same hash value, and that will >> spoil the nice simple constant time performance. But collisions are >> usually rare, and so when discussing hash tables in broad terms we >> normally ignore them. >> >> In Python, you can calculate the hash value of a key with the hash() >> function. The exact values you get may depend on the specific version of >> Python you are using, but to give you an example: >> >> py> hash("cat") >> 405875055 >> py> hash("hat") >> 1255409212 >> py> hash("fat") >> -750391218 >> >> >> So you can see, by changing just one letter of the key, we get a >> completely different hash value. A good hash function -- and Python's >> hash function is good -- will will mix up the positions of keys in a >> very unpredictable way. >> >> The end result of this is that when displaying a dict, keys are shown in >> whatever order they happen to be inside the hash table. That's >> unpredicable, depending on the details of the hash function, the actual >> keys, and whether there have been any collisions or not. >> >> If you care about this, it is easy enough to sort the keys before >> printing them: >> >> # instead of this >> print mydict.keys() >> >> # do this >> print sorted(mydict.keys()) >> >> >> If you care about keeping the insertion order, rather than alphabetical >> order, you can use an OrderedDict: >> >> from collections import OrderedDict >> >> >> but OrderedDicts are slower and use more memory than regular dicts, >> since they have to track the order that the keys were inserted. >> >> >> >> -- >> Steven >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor > > Well explained Stephen Oops... I mean Steven!... > > -- > Joel Goldstick > http://joelgoldstick.com -- Joel Goldstick http://joelgoldstick.com From steve at pearwood.info Mon Nov 25 02:40:16 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 25 Nov 2013 12:40:16 +1100 Subject: [Tutor] Else vs. Continue In-Reply-To: References: Message-ID: <20131125014016.GA2085@ando> On Sun, Nov 24, 2013 at 10:32:20PM +0100, Rafael Knuth wrote: > Hej there, > > I stumbled upon the "continue" statement and to me it looks like it > does exactly the same as else. I tested both else and continue in a > little program and I don't see any differences between both. "continue" and "else" are completely unrelated. "continue" can only be inside a for-loop or a while-loop, and it immediately jumps back to the beginning of the next loop. If I write this: for i in range(10): print(i) continue print("This will never be printed") it will print the numbers 0 through 9 but never reach the second print. Obviously, unconditionally using "continue" in this way is silly. If you don't ever want the second print line, why not just leave it out? But it is useful to conditionally continue or not, which means you will nearly always see "continue" somewhere inside an if...elif...else block. For example: for i in range(20): if i%2 == 0: print("Skipping an even number") continue print("Odd number {}".format(i)) print("Remainder when divided by three is: {}".format(i%3)) The continue need not be inside the "if" block. It could be inside an "elif" or "else" block instead. -- Steven From dyoo at hashcollision.org Mon Nov 25 05:28:23 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 24 Nov 2013 20:28:23 -0800 Subject: [Tutor] Depth First Search Listing all possible combinations In-Reply-To: References: Message-ID: You have at least one error in your graph. Specifically, if you are using: ########################################################### graph = {'q9': ['q10', 'q33'], 'q10': ['q11', 'q 28', 'q29', 'q30'], 'q11': ['q15'] , 'q16': ['q17', 'q19', 'q24'],' q18': ['q20'], 'q23': ['q34'], 'q24': ['q25', 'q26'], 'q27': ['q34'], 'q28': ['q30', 'q29'], 'q30': ['q34', 'q31', 'q12'], 'q32': ['q34'], 'q33': ['q15' , 'q30'], 'q35': ['q36', 'q37'], 'q37': ['q38', 'q39'], 'q39': ['q41', 'q40', 'q42'],'q42': ['end']} ########################################################### to represent the graph structure you've presented, then 'q15' is missing. Other nodes in your network may also be missing, so check your data again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafael.knuth at gmail.com Mon Nov 25 09:24:27 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Mon, 25 Nov 2013 09:24:27 +0100 Subject: [Tutor] Fibonacci Series In-Reply-To: References: Message-ID: @Alan @Dave @Dominik thank you all so much for the elaborate explanations! It's really simple and crystal clear now, the most difficult part was actually to detect and overcome my own misconceptions. Once I did that, the rest was really easy. Kind of a valuable learning for the future ;-) Instead of asking: "What's wrong with this code?" I should ask myself: "What's wrong with my assumption about this code?" whenever I hit the wall. Again, thank you so much & have a great week! Raf On Sun, Nov 24, 2013 at 4:48 PM, Alan Gauld wrote: > On 24/11/13 13:05, Rafael Knuth wrote: > >> "a" and "b" on the left side are unchangable tuples and they simply get >> unpacked on the right side. > > > Be careful about terminology here. a,b is a single tuple with two values. > But a and b are variables not tuples. > > Tuples are collections of (one or more) values. In python they are separated > by commas. Thus a single valued tuple looks like > > (5,) > > A double valued tuple like > > (3,4) > > And so on. > Note the parentheses are optional and only needed for > disambiguating the tuple. 3,4 is also a double valued > tuple. > > Variables are names that refer to values. A value can > be any Python object (including a tuple!). So > > a = None > a = 5 > a = 's' > a = (1,2) > > are all valid values for the variable 'a' > > And > > t = ( (1,2), (2,3) ) > > is a single tuple composed of two other tuples. > > So > > a,b = 3,4 > > is assigning the tuple on the right side to > the tuple on the left. It *simultaneously* > assigns 3 to a and 4 to b. > > It doesn't matter what a and b were storing previously > it creates a new tuple on the right and assigns it to > another newly created one on the left. Note that the > right side could be an existing tuple but the one > on the left is always a new tuple. Thus > > a,b = t # see above > > would only create one new tuple (on the left) and a > would have the value t[0], or (1,2) and b would be > t[1] or (2,3). > > The final thing that makes your case complicated is > that a,b appear on both sides of the assignment. But > if you remember that the assignments are effectively > happening simultaneously it all follows the same rules. > > Tuple assignment/unpacking is a powerful technique in Python. > Without it we would need to introduce extra variables so that > > a,b = b, a+b > > would become > > old_a = a > a = b > b = old_a + b > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From sunil.techspk at gmail.com Mon Nov 25 09:31:44 2013 From: sunil.techspk at gmail.com (Sunil Tech) Date: Mon, 25 Nov 2013 14:01:44 +0530 Subject: [Tutor] Date time Message-ID: I want to know, what difference is in between *mxDateTime & datetime of python?* looking for your comments... Thank you in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Nov 25 09:53:19 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 25 Nov 2013 08:53:19 +0000 Subject: [Tutor] Date time In-Reply-To: References: Message-ID: On 25/11/2013 08:31, Sunil Tech wrote: > I want to know, what difference is in between*mxDateTime & datetime of > python?* > looking for your comments... > > Thank you in advance. > What do you need to know that the documentation doesn't tell you? While you're rereading the docs you might also like to look up dateutil. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From dyoo at hashcollision.org Mon Nov 25 10:06:38 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 25 Nov 2013 01:06:38 -0800 Subject: [Tutor] Date time In-Reply-To: References: Message-ID: On Mon, Nov 25, 2013 at 12:31 AM, Sunil Tech wrote: > I want to know, what difference is in between *mxDateTime & datetime of > python?* > looking for your comments... > According to the mxDateTime web site, it provides a compatible interface to the standard library's version. http://www.egenix.com/products/python/mxBase/mxDateTime/ I'm trying to remember the history of things, but unfortunately my memory can't be trusted. But I believe mxDateTime was developed first, and influenced the design of the standard library's version. I'm trying to see if I can find supporting evidence for this guess... ok, the one in the standard library came in July 2003, according to: http://docs.python.org/release/2.3/whatsnew/node18.html#SECTION0001810000000000000000 We can do a few more searches to see that references to mxDateTime did exist before then. For example, here's a reference from back in April 1999: http://code.activestate.com/lists/python-list/208/ We can also see that the developer, M.-A. Lemburg, worked to get things compatible between the two implementations: https://mail.python.org/pipermail/python-dev/2003-January/032100.html So that should help explain why there are two libraries out there with the same interface. -------------- next part -------------- An HTML attachment was scrubbed... URL: From randolph.michael.sm at gmail.com Mon Nov 25 03:45:02 2013 From: randolph.michael.sm at gmail.com (Randolph Scott-McLaughlin II) Date: Sun, 24 Nov 2013 21:45:02 -0500 Subject: [Tutor] Depth First Search Listing all possible combinations In-Reply-To: References: Message-ID: I solved the question thanks to Alan's suggestions. Attached is the .py file I ran to solve my question. Thanks guys. On Sat, Nov 23, 2013 at 8:41 PM, Randolph Scott-McLaughlin II < randolph.michael.sm at gmail.com> wrote: > So I cleaned up the code to make it readable. I'm not getting an error > message now. What I'm getting is an empty bracket. I want to run > find_all_paths with my graph and then list the start and end point (in this > case that's q9 and q42) and then have it list a tuple of each path in a > separate line. Each path being a unique way to get to the end point. > > Here's what I enter and I get back [] > > >>> find_all_paths(graph, 'q9', 'q42') > > [] > > What I want is > > >>> find_all_paths(graph, 'q9', 'q42') > [q9, q10, q11 ,q15, q16, q17, q18, q20, q23, q34, q35, q36, q37, q38, q39, > q41, q42, end] > [then list another path.] > [list another path] > > graph = {'q9': ['q10', 'q33'], 'q10': ['q11', 'q 28', 'q29', 'q30'], > 'q11': ['q15'] , 'q16': ['q17', 'q19', 'q24'],' q18': ['q20'], 'q23': > ['q34'], 'q24': ['q25', 'q26'], 'q27': ['q34'], 'q28': ['q30', 'q29'], > 'q30': ['q34', 'q31', 'q12'], 'q32': ['q34'], 'q33': ['q15' , 'q30'], > 'q35': ['q36', 'q37'], 'q37': ['q38', 'q39'], 'q39': ['q41', 'q40', > 'q42'],'q42': ['end']} > > def find_path(graph, start, end, path=[]): > path = path + [start] > if start == end: > return path > if not graph.has_key(start): > return None > for node in graph[start]: > if node not in path: > newpath = find_path(graph, node, end, path) > if newpath: return newpath > return None > > > def find_all_paths(graph, start, end, path=[]): > path = path + [start] > if start == end: > return [path] > if not graph.has_key(start): > return [] > paths = [] > for node in graph[start]: > if node not in path: > newpaths = find_all_paths(graph, node, end, path) > for newpath in newpaths: > paths.append(newpath) > return paths > > > > > On Sat, Nov 23, 2013 at 7:13 PM, Alan Gauld wrote: > >> On 23/11/13 21:30, Randolph Scott-McLaughlin II wrote: >> >>> Inline image 2Inline image 1Hi Tutors, >>> >>> >>> So I'm writing code for a depth first search where I have 1 start point >>> and 1 end point. Between those points there are a series of 1-way roads >>> that goes from one vertex to the next. Sometimes the vertex can have 4 >>> or 5 one way road paths going into it or out of it. >>> >>> What I want to do is list each unique possible path someone can go from >>> the start to end point, have the list written out and ideally labeled as >>> "list'n'". >>> >>> Here's some code that I started off with but I keep getting errors >>> >> >> What kind of errors? >> And if there are error messages please provide copies of the entire error >> message not just a summary. They are usually extremely >> informative. >> >> >> in general can't get it to do what I want it to do. >>> >> >> What do you expect? What do you get? >> Don't force us to try to run it, guess what it should do, >> then assess what it is doing. >> Tell us. >> >> >> If you could guide me in the right direction or tell me how I can >>> >> > alter the code I've been coming across to fit my needs that'd >> > be great. >> >> We can try but you need to tell us more detail too. >> >> >> I've also attached an image of the road map that I'm trying to develop, >>> along with the decisional points that each vertex can take someone to >>> and from. Thanks for help! >>> >> >> It may be helpful to somebody but not to me! :-( >> >> >> #start=q9 >>> q9 = (10, 33) >>> q10 = (11, 28, 29, 30) >>> q11 = (15) >>> q16 = (17,19,24) >>> q18 = (17, 19, 24) >>> q24 = (25, 26) >>> q27 = (34) >>> q28 = (29, 30) >>> q30 = (12, 31, 34) >>> q32 = (34) >>> q33 = (15, 30) >>> q35 = (36, 37) >>> q37 = (38, 39) >>> q39 = (40, 41, 99) >>> #end = 99 >>> >> >> Could you do a smaller example that exhibits the problem? >> >> >> #trying new DFS code >>> parent = {s:None} >>> def DFS_VISIT(V, Adj,s): >>> for v in Adj[s]: >>> s.inprocess=True >>> if v not in parent: >>> s.inprocess=False >>> parent[v]=s >>> DFS_VISIT(V,Adj,s) >>> >> >> You are using recursion but its not clear how you stop >> the recursion. Possibly when all elements of Adj[s] are >> not parents? But it looks lie you never use V and >> don't change Adj either. So I'm not sur4e how often >> this will recurse, but it may be more than the fixed >> limit compiled into Python. Is that one of the errors >> you get? >> >> >> #dfs visit code, controls checking notes around you >>> def dfs(V,Adj): >>> parent = {} >>> for s in V: >>> if s not in parent: >>> parent[s] = None >>> DFS_VISIT(V,Adj,s) >>> >> >> Note that you define a new 'parent' here. This is local to this function >> and hides the parent defined above DFS. But DFS will >> continue to use the one defined at the top. Is that what you expected? >> Its usually better to create unique names to avoid confusion. >> >> I have no idea what the stuff below does, it's way too much >> for me to try to wade through. I can't see any sign of you >> calling dfs() or DFS_VISIT() so I don't know what the >> connection is. I gave up at that point. Sorry. >> >> >> import sys >>> >>> def extractPaths(current_node,path,loops_seen): >>> path.append(current_node) >>> # if node has outgoing edges >>> if nodes[current_node]!=None: >>> for thatnode in nodes[current_node]: >>> valid=True >>> # if the node we are going to has been >>> # visited before, we are completeing >>> # a loop. >>> if thatnode-1 in path: >>> i=len(path)-1 >>> # find the last time we visited >>> # that node >>> while path[i]!=thatnode-1: >>> i-=1 >>> # the last time, to this time is >>> # a single loop. >>> new_loop=path[i:len(path)] >>> # if we haven't seen this loop go to >>> # the node and node we have seen this >>> # loop. else don't go to the node. >>> if new_loop in loops_seen: >>> valid=False >>> else: >>> loops_seen.append(new_loop) >>> if valid: >>> extractPaths(thatnode-1,path,loops_seen) >>> # this is the end of the path >>> else: >>> newpath=list() >>> # increment all the values for printing >>> for i in path: >>> newpath.append(i+1) >>> found_paths.append(newpath) >>> # backtrack >>> path.pop() >>> >>> # graph defined by lists of outgoing edges >>> nodes=[[2],[3],[4],[5,9],[6,7],[7],[4,8],None,None] >>> # I tried this but it didn't work >>> nodes=zip(['q9','q10','q11','q16','q18','q24','q27','q28',' >>> q30','q32','q33','q35','q37','q39'],[(10,33),(11, >>> 28, 29, 30), (15),(17,19,24),(25, 26),(34),(29, 30),(34),(15, 30),(36, >>> 37),(38, 39),(40, 41, None)]) >>> #also tried this but it ididn't work nodes = {1: [2, 3],2: [1, 4, 5, >>> 6],3: [1, 4],4: [2, 3, 5],5: [2, 4, 6],6: [2, 5]} >>> found_paths=list() >>> extractPaths(0,list(),list()) >>> for i in found_paths: >>> print(i) >>> >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.flickr.com/photos/alangauldphotos >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> https://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: coding_ROUTES.py Type: text/x-python-script Size: 2228 bytes Desc: not available URL: From sunil.techspk at gmail.com Mon Nov 25 11:23:40 2013 From: sunil.techspk at gmail.com (Sunil Tech) Date: Mon, 25 Nov 2013 15:53:40 +0530 Subject: [Tutor] Date time In-Reply-To: References: Message-ID: Thank you Danny On Mon, Nov 25, 2013 at 2:36 PM, Danny Yoo wrote: > On Mon, Nov 25, 2013 at 12:31 AM, Sunil Tech > wrote: > > I want to know, what difference is in between *mxDateTime & datetime of >> python?* >> looking for your comments... >> > > > According to the mxDateTime web site, it provides a compatible interface > to the standard library's version. > > http://www.egenix.com/products/python/mxBase/mxDateTime/ > > > I'm trying to remember the history of things, but unfortunately my memory > can't be trusted. But I believe mxDateTime was developed first, and > influenced the design of the standard library's version. > > > I'm trying to see if I can find supporting evidence for this guess... ok, > the one in the standard library came in July 2003, according to: > > > http://docs.python.org/release/2.3/whatsnew/node18.html#SECTION0001810000000000000000 > > We can do a few more searches to see that references to mxDateTime did > exist before then. > > For example, here's a reference from back in April 1999: > > http://code.activestate.com/lists/python-list/208/ > > > We can also see that the developer, M.-A. Lemburg, worked to get things > compatible between the two implementations: > > https://mail.python.org/pipermail/python-dev/2003-January/032100.html > > > So that should help explain why there are two libraries out there with the > same interface. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From reuben.dlink at gmail.com Mon Nov 25 07:37:47 2013 From: reuben.dlink at gmail.com (Reuben) Date: Mon, 25 Nov 2013 12:07:47 +0530 Subject: [Tutor] Usefulness of classes and necessity of inheriting classes Message-ID: Hi, Question no 1: ---------------------- I would like to know why do we actually inherit classes? What would be the benefit of inheriting? If possible, a practical example would be of great help Question no 2: ---------------------- Why would I ever use a class? I understand this is strange question May be an example to make me understand would be useful. Or may be answering the question should be rephrased as "Why not use modules instead of classes?" Regards, Reuben -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 25 12:11:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Nov 2013 11:11:44 +0000 Subject: [Tutor] Usefulness of classes and necessity of inheriting classes In-Reply-To: References: Message-ID: On 25/11/13 06:37, Reuben wrote: > Question no 1: > ---------------------- > I would like to know why do we actually inherit classes? What would be > the benefit of inheriting? Inheritance is the key to providing polymorphism. It also saves a lot of duplication in that a new class only has to implement those methods that differ from the ones in the inherited class. See the BankAccount examples in my OOP tutorial topic for examples of this. > If possible, a practical example would be of great help Real world examples include widgets in a GUI. You can have a Button widget which does all the standard button type things. You might then want a special button that flashes while an operation is in progress. You therefore define a new button class inheriting from the regular button. You only need to implement the display code, the code that responds to mouse clicks etc is all inherited from the standard. Another case in in Network management. Network management systems use what is called a MIB. A Management Information Base. The MIB is usually defined in terms of Managed Objects(MO). There is a standard protocol (a set of methods or API) that all MOs must adhere to. Specific types of network elements (routers, switches, printers etc) all have their own specialist methods/features on top of the standard MO protocol. Specific models of router or printer will then have their own proprietary features on top of that again. So a MIB will typically have a deep inheritance stricture starting with MO, then a layer of generic devices(router, switch, printer etc) then a third layer of manufacturers models (eg. Cisco5300, HP Deskjet 4550, etc) When we come to add a new model of printer, say, to the MIB we want to minimize the coding so we inherit the generic printer object which will give us the generic MO protocol methods plus the generic printer features (out of paper/ink alarms etc) for free. We then implement the special features of that model (blue-tooth connection opened, banner printing mode selected etc). By only having to code the differences it is much easier to add new objects. > Question no 2: > ---------------------- > > Why would I ever use a class? I understand this is strange question > > May be an example to make me understand would be useful. > > Or may be answering the question should be rephrased as "Why not use > modules instead of classes?" Modules only allow for one instance. All the data fields in a module are shared between users. A class is like a new data type. You can have as many instances as you like and each one will have its own attributes. Think of the GUI Button class. A typical GUI screen with have several Buttons ('Save', "Don't Save", "Cancel" for example) Each of those buttons has a different piece of code linked to it and a different label, but they are all Buttons. If we just had a Button module we would need to hold all the data about each button locally in our code and then pass all of it into each function every time we used it. (And that includes things like screen location, size, font, colors, borders, state, etc etc) It's perfectly possible to do that (it's what we did before OOP became popular) but it's very tedious, and error prone. And of course you can't inherit from Modules! However, it is important to say that you don't need to use classes. They are powerful tools, especially where you need to reuse code across projects and in organizing larger projects. But Python modules do a lot of the same things and in smaller projects are often sufficient. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From nik at naturalnet.de Mon Nov 25 12:12:17 2013 From: nik at naturalnet.de (Dominik George) Date: Mon, 25 Nov 2013 12:12:17 +0100 Subject: [Tutor] Usefulness of classes and necessity of inheriting classes In-Reply-To: References: Message-ID: <20131125111215.GG5299@keks.naturalnet.de> Hi Reuben, > Question no 1: > ---------------------- > I would like to know why do we actually inherit classes? What would be the > benefit of inheriting? I think this is not the classical explanation of this, but when teaching programming to my students, I make a very great deal of the following: All things programming (even all things to do with computers) are about agreements (dt. Abmachungen) and promises (dt. Versprechen). Protocols are agreements about the communication between programs (or devices), and a programming language is an agreement about communication between a programmer and the machine. A program, or an interface, then, is an agreement between the user and the programmer and his machine. The important thing is that, as is to be expected from the kids I teach towards their teachers, friends and family, if the agreement is fulfilled by both sides, everything will work out well. The machine gives us a promies: if we feed it with certain binary operations, it will do a certain thing, and exactly this one thing (unless it has a bug). The Python interpreter, or its developers, gives us a promise: if we feed it with certain lines/blocks of code, it will do exactly as asked. If it doesn't, most likely we broke the agreement in some way or another (unless the interpreter or the machine udner it has a bug). Now, you could see a class as a promies to both the interpreter and users of your class (if you use it in a library): A certain class has certain attributes and methods, and this is a promise. It follows, that if a class inherits from another class, then this class will keep the promise made by the base class as well - it will (at least) have the interface the base class is known to have. Obviously, a developer could break this promise by manipulating stuff in the inheriting class in an unexpected way, but that's not our fault then nor is it Python's or the machine's fault ;). Now, normally, you extend a class (inherit from it) when you want your own class to basically behave the same way the base class does, and expose more or less the same interface. Maybe you even do not want to change the internal behaviour, but only add a tiny thing. My experience in classroom teaching has shown that thinking of programming and CS as making keeping promises helps a lot. > If possible, a practical example would be of great help A practical example, as in code - an example that has a practical use is hard to give. But I'll try anyway: class Display(): """" This class can put pixels on a monochrome display """ def __init__(self): """ Do setup stuff for the display """ pass def put(self, pos): """ Puts a pixel at an (x, y) pos pass def clear(self, pos): """ Clears a pixel at an (x, y) pos """ pass class ColorDisplay(Display): """ This class behaves just like the Display class, but can control colour. """ # The setup stuff is copied/inherited from the base def put(self, pos, colour=None): """ This method overrides the base method, but calls it in case the user does not use colour, so our interface is universal """ if not colour: return Display.put(self, pos) # do colourful magic stuff here You see that both classes can be used in exactly the same manner, but the second one has been extended by an optional colour attribute in the put method. From this example, you can conclude that the inheritance was chosen to avoid code duplication, and to sign the promise that the interfaces are somewhat compatible. > Question no 2: > ---------------------- > > Why would I ever use a class? I understand this is strange question > > May be an example to make me understand would be useful. > > Or may be answering the question should be rephrased as "Why not use > modules instead of classes?" Because you cannot (well you can, but not without turning right into a zombie) make a copy of a module. When you instantiate a class, you get a copy of its attributes in something like a dictionary (exposed in a different way) and it is independent of the other copies. The only reasonable thing you do with a module is importing it. With that, you get a copy of its *name* - mind you, modules and importing are all about names and namespaces, no more no less. So imagine a module named spam, with these contents: bacon = 5 eggs = 7 Now, do something like this: import spam as spam1 import spam as spam2 This is completely valid, but you only get two names pointing to the exact same thing: spam1.bacon = 10 print(spam2.bacon) This will give 10. You most likely did not want that ;). What you *can* do is write simple functions in a module that expect a certain (promised) data structure as input and manipulates it in a (promised) way, like so: def grow_a_human(human): human['length'] += 10 my_human = {'length': 120, 'weight': 25} You can iamgine how to put that in classes. And as a matter of fact, classes in Python aren't so much different from that. The attributes in a class are in a very dict-like thing, and the class methods are called on it. Maybe you wondered about the self argument in every class method: def dosomething(self): pass Now having this in a class called Spam, and having that instantiated as mySpam, Python's magic more or less does nothing more than Spam.dosomething(mySpam) when you call mySpam.dosomething() So, classes and object orientation are mostly just another way to look at things. It allows for tighter contracts (agreements, promises) and for a more natural model. Class methods do something with the object they belong to, so the object is "self-managed". In the example above: a human is not grown by something outside it, but it grows by its own body chemics and power. So, modelling things is a bit clearer with classes. There are a lot more traditional explanations, but I hope this is enough for the tutors list ;). HTH, Nik -- * concerning Mozilla code leaking assertion failures to tty without D-BUS * That means, D-BUS is a tool that makes software look better than it actually is. PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From fomcl at yahoo.com Mon Nov 25 14:29:57 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 25 Nov 2013 05:29:57 -0800 (PST) Subject: [Tutor] Usefulness of classes and necessity of inheriting classes In-Reply-To: Message-ID: <1385386197.97329.YahooMailBasic@web163805.mail.gq1.yahoo.com> Another case in in Network management. Network management systems use what is called a MIB. A Management Information Base. The MIB is usually defined in terms of Managed Objects(MO). There is a standard protocol (a set of methods or API) that all MOs must adhere to. Specific types of network? elements (routers, switches, printers etc) all have their own specialist methods/features on top of the standard MO protocol. Specific models of router or printer will then have their own proprietary features on top of that again. So a MIB will typically have a deep inheritance stricture starting with MO, then a layer of generic devices(router, switch, printer etc) then a third layer of manufacturers models (eg. Cisco5300, HP Deskjet 4550, etc) When we come to add a new model of printer, say, to the MIB we want to minimize the coding so we inherit the generic printer object which will give us the generic MO protocol methods plus the generic printer features (out of paper/ink alarms etc) for free. We then implement the special features of that model (blue-tooth connection opened, banner printing mode selected etc). By only having to code the differences it is much easier to add new objects. ===> interesting. Is this (a) the same as or (b) similar to Abstract Base Classes (ABC) in Python? From alan.gauld at btinternet.com Mon Nov 25 15:30:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Nov 2013 14:30:45 +0000 Subject: [Tutor] Usefulness of classes and necessity of inheriting classes In-Reply-To: <1385386197.97329.YahooMailBasic@web163805.mail.gq1.yahoo.com> References: <1385386197.97329.YahooMailBasic@web163805.mail.gq1.yahoo.com> Message-ID: On 25/11/13 13:29, Albert-Jan Roskam wrote: > > ===> interesting. Is this (a) the same as or (b) > similar to Abstract Base Classes (ABC) in Python? > MIB...is usually defined in terms of Managed Objects(MO). There is > a standard protocol (a set of methods or API) that all MOs > must adhere to. A MO is an abstract base class. I don't know what/how Python supports for ABC but the concept of abstract base classes is at the root of almost all OO designs. In fact OO design is largely about extracting out the common elements from a group of classes and creating an abstract superclass (or set of them) from that. The main framework of the application is then created around manipulating the abstract classes. The amount of bespoke, class specific code is thus minimized. The bespoke elements are hidden inside the class implementations of the abstract behaviour. In an ideal solution this allows you to add new classes to the system without making any changes to the application itself. It is rarely that simple in practice! > switches, printers etc) all have their own specialist > methods/features on top of the standard MO protocol. These are non-abstract base classes. That is to say it's perfectly possible, and quite common, to actually create instances of a generic printer or switch (possibly because a class doesn't exist yet for that make/model or because it has no unique features). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From reuben.dlink at gmail.com Mon Nov 25 12:32:21 2013 From: reuben.dlink at gmail.com (Reuben) Date: Mon, 25 Nov 2013 17:02:21 +0530 Subject: [Tutor] Usefulness of classes and necessity of inheriting classes In-Reply-To: References: Message-ID: Thanks to Alan and Dominik for their explanation and valuable time to provide their inputs. On Mon, Nov 25, 2013 at 4:41 PM, Alan Gauld wrote: > On 25/11/13 06:37, Reuben wrote: > > Question no 1: >> ---------------------- >> I would like to know why do we actually inherit classes? What would be >> the benefit of inheriting? >> > > Inheritance is the key to providing polymorphism. It also saves a lot of > duplication in that a new class only has to implement those methods that > differ from the ones in the inherited class. > > See the BankAccount examples in my OOP tutorial topic for examples of this. > > > If possible, a practical example would be of great help >> > > Real world examples include widgets in a GUI. > You can have a Button widget which does all the standard button type > things. > You might then want a special button that flashes while an operation is in > progress. You therefore define a new button class inheriting from the > regular button. You only need to implement the display code, the code that > responds to mouse clicks etc is all inherited from the standard. > > Another case in in Network management. Network management systems > use what is called a MIB. A Management Information Base. The MIB > is usually defined in terms of Managed Objects(MO). There is a > standard protocol (a set of methods or API) that all MOs must > adhere to. Specific types of network elements (routers, > switches, printers etc) all have their own specialist > methods/features on top of the standard MO protocol. Specific > models of router or printer will then have their own > proprietary features on top of that again. So a MIB will > typically have a deep inheritance stricture starting with MO, > then a layer of generic devices(router, switch, printer etc) > then a third layer of manufacturers models (eg. Cisco5300, > HP Deskjet 4550, etc) > > When we come to add a new model of printer, say, to the MIB > we want to minimize the coding so we inherit the generic printer > object which will give us the generic MO protocol methods > plus the generic printer features (out of paper/ink alarms etc) > for free. We then implement the special features of that model (blue-tooth > connection opened, banner printing mode selected > etc). By only having to code the differences it is much easier > to add new objects. > > > Question no 2: >> ---------------------- >> >> Why would I ever use a class? I understand this is strange question >> >> May be an example to make me understand would be useful. >> >> Or may be answering the question should be rephrased as "Why not use >> modules instead of classes?" >> > > Modules only allow for one instance. All the data fields in a module are > shared between users. A class is like a new data type. You can have as many > instances as you like and each one will have its own attributes. > > Think of the GUI Button class. A typical GUI screen with have several > Buttons ('Save', "Don't Save", "Cancel" for example) Each of those buttons > has a different piece of code linked to it and a different label, but they > are all Buttons. If we just had a Button module we would need to hold all > the data about each button locally in our code and then pass all of it into > each function every time we used it. (And that includes things like screen > location, size, font, colors, borders, state, etc etc) It's perfectly > possible to do that (it's what we did before OOP became popular) but it's > very tedious, and error prone. > > And of course you can't inherit from Modules! > > However, it is important to say that you don't need to use classes. > They are powerful tools, especially where you need to reuse code across > projects and in organizing larger projects. But Python modules do a lot of > the same things and in smaller projects are often sufficient. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Nov 25 16:45:58 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Nov 2013 02:45:58 +1100 Subject: [Tutor] Usefulness of classes and necessity of inheriting classes In-Reply-To: References: Message-ID: <20131125154557.GF2085@ando> On Mon, Nov 25, 2013 at 12:07:47PM +0530, Reuben wrote: > Hi, > > > Question no 1: > ---------------------- > I would like to know why do we actually inherit classes? What would be the > benefit of inheriting? > > If possible, a practical example would be of great help Fundamentally, inheritence is a way of re-using code. You've written a class to do something, to solve some problem, and now you need to solve a slightly different problem. If you can borrow code from the original class, 95% of the work is already done. You certainly don't want to just *copy and paste* the code from one class into another class, because then every time you fix a bug in one, you have to remember to fix it in the other as well. And then there will be a third, and a fourth, and so on. Trying to manage all those independent copies will be a nightmare. Instead, but using inheritence, you have one "master copy", the parent class, and then each subclass "inherits" code from the parent, changing only the bits they actually need to. Usually by adding new code, or by modifying existing code. Here's a good video about subclassing, by one of the top Python developers: http://www.youtube.com/watch?v=miGolgp9xq8? > Question no 2: > ---------------------- > > Why would I ever use a class? I understand this is strange question Because classes bring data and the code to work on that data together. Because classes help make code reusable and extendable. Because classes help avoid copy-and-paste programming. All the basic data types in Python are classes. Strings, ints, floats, lists, dicts... they're all classes. So you're already using classes. Why might you write your own class, instead of using an existing one? That's a good question. Sometimes the answer is, you shouldn't. http://www.youtube.com/watch?v=o9pEzgHorH0 This is Python, not Java, and there is no need to wrap every piece of functionality in a class: http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html? Still, there are good reasons for writing your own classes: - you want to extend an existing class - you want something which is best understood as a set of data plus the functions to work with that data. - http://lucumr.pocoo.org/2013/2/13/moar-classes/ (warning: quite technical) Confused? Don't be. Classes are a tool. The ultimate aim is to write good programs. Sometimes you need a screwdriver, and sometimes you need a hammer. A good programming language comes with both screwdrivers and hammers. Let's start with a small toy class: class Parrot: def __init__(self, breed, colour, name="Polly"): # Create a new Parrot instance. self.breed = breed self.colour = colour self.name = name def talk(self): message = "%s wants a cracker!" % self.name print(message) def squawk(self): print("Squawk!!!") def describe(self): message = """\ You see a bird in a cage. It is a %s parrot. It has an intelligent look to its eyes, a very sharp beak, and beautiful %s plummage.""" print(message % (self.breed, self.colour)) Here the class expects three pieces of data, the breed of the parrot, its colour, and the name of the individual bird. The class also defines three methods (four, if you include __init__, which is used for initialising a new instance of the class). The "describe" method describes the bird. The "squawk" method isn't very exciting, but the "talk" method knows the bird's own name. Try it: py> polly = Parrot("Norwegian Blue", "blue") py> polly.talk() Polly wants a cracker! If we change the bird's name, the method automatically does the right thing: py> polly.name = "Jackie" py> polly.talk() Jackie wants a cracker! > May be an example to make me understand would be useful. > > Or may be answering the question should be rephrased as "Why not use > modules instead of classes?" Modules and classes are complementary, not in opposition. Classes live inside modules, you can't have a class without a module to put it in. -- Steven From callumwilson2 at me.com Mon Nov 25 16:54:31 2013 From: callumwilson2 at me.com (Callum Wilson) Date: Mon, 25 Nov 2013 15:54:31 +0000 (UTC) Subject: [Tutor] Patchwork Help Message-ID: Hi, I am a relatively beginner to python. I am currently studying Digital Forensics at University and programming using Python is currently a unit i am studying. I have to complete a worksheet for Friday 29th, but i am having trouble in doing this and wanted to seek external help. I have to create a patchwork of which begins by prompting user to enter: the patchwork size (common width & height in terms of patches) the desired 3 colours (of which my program should ensure are all different from eachother). Would you be able to help me? if so, how do I do the things listed above? Many Thanks, Callum. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Mon Nov 25 19:07:22 2013 From: dfjennings at gmail.com (Don Jennings) Date: Mon, 25 Nov 2013 13:07:22 -0500 Subject: [Tutor] Patchwork Help In-Reply-To: References: Message-ID: <76B646CB-28E0-4CCF-8227-D7B0CB419662@gmail.com> On Nov 25, 2013, at 10:54 AM, Callum Wilson wrote: > Hi, > > I am a relatively beginner to python. I am currently studying Digital Forensics at University and programming using Python is currently a unit i am studying. > > I have to complete a worksheet for Friday 29th, but i am having trouble in doing this and wanted to seek external help. > > I have to create a patchwork of which begins by prompting user to enter: > the patchwork size (common width & height in terms of patches) > the desired 3 colours (of which my program should ensure are all different from eachother). > > Would you be able to help me? Yes, we can help, but we don't do homework for you. Instead, you attempt to write the code, and then when you get stuck, you ask (good) questions. > > if so, how do I do the things listed above? Since you are taking a course, surely the instructor has provided you with some information or resources. Which ones have you tried? What doesn't make sense to you? Take care, Don From alan.gauld at btinternet.com Mon Nov 25 19:15:10 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Nov 2013 18:15:10 +0000 Subject: [Tutor] Patchwork Help In-Reply-To: References: Message-ID: On 25/11/13 15:54, Callum Wilson wrote: > Hi, > I am a relatively beginner to python. I am currently studying Digital > Forensics at University I have no idea what Digital Forensics might be but I assume that part is not pertinent to the actual question below so I'll ignore it for now! :-) > I have to complete a worksheet for Friday 29th, but i am having trouble > in doing this and wanted to seek external help. Thanks for telling us its homework. We can help but won;t do it for you. > I have to create a patchwork of which begins by prompting user to enter: > the patchwork size (common width & height in terms of patches) > the desired 3 colours (of which my program should ensure are all > different from eachother). OK, That is fairly easy so far. Prompt the user for some input and read it. Do you know how to do that bit? Then you have to validate the colours to ensure they are different. Can you do that bit? The hard bit is, I suspect the creating the patchwork? That will require a table data structure - probably a two dimensional list. Do you know how to create a table? You then need to populate the table with colours - are there any rules about which colours can be next to each other? Finally you need to display it. This could be a simple text output or it could be a graphic - how clever do you need to get? How much of the above can you do? Which bits do you need help with? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From jared at thehelloworldprogram.com Mon Nov 25 19:18:17 2013 From: jared at thehelloworldprogram.com (Jared Nielsen) Date: Mon, 25 Nov 2013 10:18:17 -0800 Subject: [Tutor] how to only loop over first 'x' items of a list; writing a Twitter bot with tweepy Message-ID: Hi all, Noob. For a beginner project I'm hacking together a Twitter bot with tweepy. I've got one more or less functional, but I'm running into a problem when making a list of followers by calling the Twitter api. I'm getting a 'Rate limit exceeded' error, which, evidently is due to changes in the Twitter api not allowing one to make more than a certain number of calls. I think 150 at a time. I have more than 150 followers in the account. My code is: for follower in tweepy.Cursor(api.followers).items(): follower_ids.append(follower.id) My question is: how do I grab the first 'x' items in tweepy.Cursor(api.followers)items(), say 15 or 20, without looping through the entire list of items, which then gives me the error. Thanks! -- http://thehelloworldprogram.com http://dototot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Nov 25 19:33:06 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 25 Nov 2013 18:33:06 +0000 Subject: [Tutor] how to only loop over first 'x' items of a list; writing a Twitter bot with tweepy In-Reply-To: References: Message-ID: On 25/11/2013 18:18, Jared Nielsen wrote: > Hi all, > Noob. For a beginner project I'm hacking together a Twitter bot with tweepy. > > I've got one more or less functional, but I'm running into a problem > when making a list of followers by calling the Twitter api. I'm getting > a 'Rate limit exceeded' error, which, evidently is due to changes in the > Twitter api not allowing one to make more than a certain number of > calls. I think 150 at a time. I have more than 150 followers in the > account. > > My code is: > > for follower in tweepy.Cursor(api.followers).items(): > follower_ids.append(follower.id ) > > My question is: how do I grab the first 'x' items in > tweepy.Cursor(api.followers)items(), say 15 or 20, without looping > through the entire list of items, which then gives me the error. > > Thanks! > One way, there are others. for i, follower in enumerate(tweepy.Cursor(api.followers).items()): if i == 20: break follower_ids.append(follower.id ) -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From alan.gauld at btinternet.com Mon Nov 25 22:09:08 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Nov 2013 21:09:08 +0000 Subject: [Tutor] how to only loop over first 'x' items of a list; writing a Twitter bot with tweepy In-Reply-To: References: Message-ID: On 25/11/13 18:18, Jared Nielsen wrote: > Hi all, > Noob. For a beginner project I'm hacking together a Twitter bot with tweepy. > > I've got one more or less functional, but I'm running into a problem > when making a list of followers by calling the Twitter api. I'm getting > a 'Rate limit exceeded' error, which, evidently is due to changes in the > Twitter api not allowing one to make more than a certain number of > calls. I think 150 at a time. I have more than 150 followers in the > account. > > My code is: > > for follower in tweepy.Cursor(api.followers).items(): > follower_ids.append(follower.id ) > > My question is: how do I grab the first 'x' items in > tweepy.Cursor(api.followers)items(), say 15 or 20, without looping > through the entire list of items, which then gives me the error. You could create a slice on the items() return value (assuming its a list or similar... limit = 20 for follower in tweepy.Cursor(api.followers).items()[:limit]: follower_ids.append(follower.id ) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From denis.spir at gmail.com Tue Nov 26 10:19:46 2013 From: denis.spir at gmail.com (spir) Date: Tue, 26 Nov 2013 10:19:46 +0100 Subject: [Tutor] string codes Message-ID: <529467B2.3080500@gmail.com> Hello, I am coming back to Python after quite a long time, have forgotten everything, and don't know anything of python 3. I use python 3.3 for its nice unicode text type. === codes === What is the method to get a code or list of codes inside a string: s = "abcde" c = s.code(2) assert(c == 0x63) ? === sub compare === Is there a method to compare a substring, without building a substring from the big one? Like startswith or endswith, but anywhere inside the string? test = s[1, -1] == "bcd" # no!, builds a substring test = s.sub_is(1, -1, "bcd") # yes! what I'm searching If this method does not exist, what do you think of it? (Well, the name is not great, but could not find better ;-) Thank you, Denis From reuben.dlink at gmail.com Tue Nov 26 08:30:18 2013 From: reuben.dlink at gmail.com (Reuben) Date: Tue, 26 Nov 2013 13:00:18 +0530 Subject: [Tutor] How to set variables inside a class() Message-ID: Hi, Following is my code: ############################################# class Animal(): flag = True print flag def __init__(self,name): self.name = name print self.name def walk(self): print "I am walking" if __name__ == '__main__': test = Animal('boxer') test.flag = False test.walk() ############################################# My question is: ____________ 1)Inside the Animal class(), How can I set the variable 'flag' to FALSE? Regards, Reuben -------------- next part -------------- An HTML attachment was scrubbed... URL: From nik at naturalnet.de Tue Nov 26 11:00:03 2013 From: nik at naturalnet.de (Dominik George) Date: Tue, 26 Nov 2013 11:00:03 +0100 Subject: [Tutor] How to set variables inside a class() In-Reply-To: References: Message-ID: <20131126100002.GL5299@keks.naturalnet.de> Hi Reuben, > class Animal(): > > flag = True > print flag Are you sure you know what this does ;)? Normally, you initialize all variables in the constructor. > test.flag = False > 1)Inside the Animal class(), How can I set the variable 'flag' to FALSE? Your qustion is a bit unclear. In your above code, you showed at least two ways of achieving that - one would be in the place where you have flag = True in your class definition, and the second is when you do test.flag = False on the instance. But remember that classes are schemes; what really counts are the copies of them called instances. So I think your question is: "When calling a method in an instance of my class, how do I make it set the attribute flag to False?" The simple answer is: In the same way you set the name in the constructor - self.flag = False . I suggest you should pay more attention to the repeating patterns you find when programming Python. I have observed that the answer to your question was all in your code sample ;). So while I (and others) will happily help you anyway, in order to improve your learning efforts, please do the following next time you ask: - Look at the code you have - Try to find a pattern that looks similar to what you want to achieve - Try it ;) - If it fails or is unclear, report that, your assumptions and the results so we can clarify it - If you do not find such a pattern, go ahead and just ask, but give a statement of what you looked out for :). Cheers, Nik -- Ein Jabber-Account, sie alle zu finden; ins Dunkel zu treiben und ewig zu binden; im NaturalNet, wo die Schatten droh'n ;)! PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From alan.gauld at btinternet.com Tue Nov 26 11:01:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Nov 2013 10:01:14 +0000 Subject: [Tutor] string codes In-Reply-To: <529467B2.3080500@gmail.com> References: <529467B2.3080500@gmail.com> Message-ID: On 26/11/13 09:19, spir wrote: > What is the method to get a code or list of codes inside a string: > s = "abcde" > c = s.code(2) > assert(c == 0x63) If I understand what you want then I think its the ord() function you are looking for c = ord(s[2]) > > === sub compare === > > Is there a method to compare a substring, without building a substring > from the big one? Like startswith or endswith, but anywhere inside the > string? > test = s[1, -1] == "bcd" # no!, builds a substring I assume you mean test = s[1:-1] == "bcd" > test = s.sub_is(1, -1, "bcd") # yes! what I'm searching You can use startswith() (or endswith) by providing the optional start and end arguments: test = s.startswith("bcd", 1, -1) The help() command at the >>> prompt is your friend. Try >>> help(str) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Nov 26 11:53:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Nov 2013 10:53:27 +0000 Subject: [Tutor] How to set variables inside a class() In-Reply-To: References: Message-ID: On 26/11/13 07:30, Reuben wrote: > Hi, > > Following is my code: > ############################################# > class Animal(): > > flag = True > print flag > > def __init__(self,name): > self.name = name > print self.name > > def walk(self): > print "I am walking" > > > if __name__ == '__main__': > test = Animal('boxer') > test.flag = False If you really want the flag to be a class attribute rather than an instance one you should set it using the class name. So instead of test.flag use Animal.flag = False That works inside the class methods too. By setting test.flag you are creating a new instance level attribute that exists only within the test instance. That's legal Python but usually its not a good idea to have different instances of the same class having different attributes. >>> class C: ... f = True ... def g(self): self.f = 42 ... >>> c = C() >>> c.f True >>> c.g() >>> c.f 42 >>> C.f True >>> d = C() >>> d.f = 66 >>> d.f 66 >>> C.f True >>> -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From sunil.techspk at gmail.com Tue Nov 26 12:07:28 2013 From: sunil.techspk at gmail.com (Sunil Tech) Date: Tue, 26 Nov 2013 16:37:28 +0530 Subject: [Tutor] Dict Message-ID: Hi Friends, Is it possible to sort dict & to get result as dict? if it is possible, please give some example. Thank you in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nik at naturalnet.de Tue Nov 26 12:13:52 2013 From: nik at naturalnet.de (Dominik George) Date: Tue, 26 Nov 2013 12:13:52 +0100 Subject: [Tutor] How to set variables inside a class() In-Reply-To: References: Message-ID: <20131126111352.GQ5299@keks.naturalnet.de> Hi, > By setting test.flag you are creating a new instance level attribute > that exists only within the test instance. That's legal Python > but usually its not a good idea to have different instances of > the same class having different attributes. maybe this becomes clearer by breaking down the whole thing to something more basic: dictionaries. As I mentioned before, classes and their instances are more or less dictionaries containing their attributes. When you set a variable at class scope (like your flag in the class definition), then this is added to the dictionary of the class. Now when zou instantiate the class, then the dictionary is copied to the instance (carying references to the same data inside it, mind you!), so the instance has an attribute called flag available, pointing to the same data as the flag in the class. You can do things such as: my_instance.f = False or self.f = False This will then assign the *new* data to the named attribute in the instance, thus releasing that reference to the class' attribute data. And that's all of the magic - shallow copies of a dictionary that you sometimes overwrite. There's not much more to static attributes in Python. You can prove this by manipulating the copy of a class attribute in an isntance without replacing it, like so: class C(): entries = [] c = C() c.entries.append('foo') c.entries C.entries You will find that both the last lines return the same thing - the list with 'foo' appended, because you just manipulated the same list object in place. One last thing, when you create an instance-level attribute, you do that inside a method by adding it to the self reference. This only adds it to the dictionary of that instance - normally, you setup all attributes in the constructor because that guarantees that they are set for all new instances. You could as well use class-level attributes to initialize attributes for all instances, but as noted above, you must pay very close attention then because if you happen to manipulate such an attribute in place in one class before replacing it, you manipulate it for all other isntances, too. -nik -- Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From steve at pearwood.info Tue Nov 26 12:34:14 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Nov 2013 22:34:14 +1100 Subject: [Tutor] string codes In-Reply-To: <529467B2.3080500@gmail.com> References: <529467B2.3080500@gmail.com> Message-ID: <20131126113413.GH2085@ando> On Tue, Nov 26, 2013 at 10:19:46AM +0100, spir wrote: > What is the method to get a code or list of codes inside a string: > s = "abcde" > c = s.code(2) > assert(c == 0x63) > ? Use indexing to get the character you want, then ord() to return its ordinal value. ord(s[2]) > === sub compare === > > Is there a method to compare a substring, without building a substring from > the big one? Like startswith or endswith, but anywhere inside the string? > test = s[1, -1] == "bcd" # no!, builds a substring > test = s.sub_is(1, -1, "bcd") # yes! what I'm searching The word I think you want is "view". A view is a look inside another object without copying the part that you want. I think that views would be useful for *very large strings*, but very large probably means a lot larger than you might think. For small strings, say under a few hundred or perhaps even thousand characters, making a copy of the substring will probably be faster. I say "probably", but I'm only guessing, because strings in Python don't have views. (Perhaps they should?) So for the time being, don't worry about it. Copying a substring in Python is very efficient, the simplest way is to just compare the substring directly: s[1:-1] = "bcd" Take note that a slice (substring) of a string uses a colon : and not a comma. -- Steven From nik at naturalnet.de Tue Nov 26 12:57:29 2013 From: nik at naturalnet.de (Dominik George) Date: Tue, 26 Nov 2013 12:57:29 +0100 Subject: [Tutor] Dict In-Reply-To: References: Message-ID: <20131126115726.GT5299@keks.naturalnet.de> Hi, > Is it possible to sort dict & to get result as dict? > if it is possible, please give some example. By what do you want to sort it? By key? By value? By a combination of both? Cheers, Nik -- Ein Jabber-Account, sie alle zu finden; ins Dunkel zu treiben und ewig zu binden; im NaturalNet, wo die Schatten droh'n ;)! PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From steve at pearwood.info Tue Nov 26 12:59:26 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Nov 2013 22:59:26 +1100 Subject: [Tutor] string codes In-Reply-To: References: <529467B2.3080500@gmail.com> Message-ID: <20131126115926.GI2085@ando> On Tue, Nov 26, 2013 at 10:01:14AM +0000, Alan Gauld wrote: > >Is there a method to compare a substring, without building a substring > >from the big one? Like startswith or endswith, but anywhere inside the > >string? > > test = s[1, -1] == "bcd" # no!, builds a substring > > I assume you mean test = s[1:-1] == "bcd" > > > test = s.sub_is(1, -1, "bcd") # yes! what I'm searching > > You can use startswith() (or endswith) by providing the optional > start and end arguments: > > test = s.startswith("bcd", 1, -1) That doesn't work, unfortunately: py> s = "abcdZZZZZZZ" py> s[1:-1] == "bcd" False py> s.startswith("bcd", 1, -1) True Oops. You'd have to do both startswith() and endswith() tests, and even then it doesn't work: py> s = "abcdZZZZZZZZabcde" py> s[1:-1] == "bcd" False py> s.startswith("bcd", 1, -1) and s.endswith("bcd", 1, -1) True -- Steven From steve at pearwood.info Tue Nov 26 13:07:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Nov 2013 23:07:17 +1100 Subject: [Tutor] Dict In-Reply-To: References: Message-ID: <20131126120717.GJ2085@ando> On Tue, Nov 26, 2013 at 04:37:28PM +0530, Sunil Tech wrote: > Hi Friends, > > Is it possible to sort dict & to get result as dict? > if it is possible, please give some example. No it is not possible, dicts are deliberately unsorted. Please read my explanation why from yesterday: https://mail.python.org/pipermail/tutor/2013-November/098436.html Instead, you can use an OrderedDict, which is ordered by insertion order, not sort order. But if you sort the items first, then insert them into the OrderedDict, it will be sorted. py> from collections import OrderedDict py> data = {'a':1, 'c':3, 'd':4, 'b':2} py> items = sorted(data.items()) py> data = OrderedDict(items) py> data OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)]) Another solution is to only sort the items when you're ready to use them: py> data = {'a':1, 'c':3, 'd':4, 'b':2} py> for key in sorted(data.keys()): ... print(key, data[key]) ... ('a', 1) ('b', 2) ('c', 3) ('d', 4) A third is to write your own SortedDict class. If you google for it, you will probably find dozens of ideas. -- Steven From steve at pearwood.info Tue Nov 26 13:12:58 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 26 Nov 2013 23:12:58 +1100 Subject: [Tutor] How to set variables inside a class() In-Reply-To: References: Message-ID: <20131126121258.GK2085@ando> On Tue, Nov 26, 2013 at 01:00:18PM +0530, Reuben wrote: > Hi, > > Following is my code: > ############################################# > class Animal(): > > flag = True > print flag This "flag" is a class attribute, which means it is shared by all instances. Every Animal will see the same flag. (Unless you set a new one on the individual animal.) > def __init__(self,name): > self.name = name > print self.name This "name" is an instance attribute, which means it is not shared. > def walk(self): > print "I am walking" > > > if __name__ == '__main__': > test = Animal('boxer') > test.flag = False > test.walk() The line test.flag creates a new instance attribute on that specific Animal, which shadows (hides) the class attribute. > My question is: > ____________ > > 1)Inside the Animal class(), How can I set the variable 'flag' to FALSE? The same way you set it to true, only use False instead. class Animal(): flag = False If you want it specific to the individual instead of shared, put it inside the __init__ method, using self: class Animal(): def __init__(self,name): self.name = name self.flag = False -- Steven From alan.gauld at btinternet.com Tue Nov 26 15:41:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Nov 2013 14:41:44 +0000 Subject: [Tutor] string codes In-Reply-To: <20131126115926.GI2085@ando> References: <529467B2.3080500@gmail.com> <20131126115926.GI2085@ando> Message-ID: On 26/11/13 11:59, Steven D'Aprano wrote: >> test = s.startswith("bcd", 1, -1) > > That doesn't work, unfortunately: > > py> s = "abcdZZZZZZZ" > py> s[1:-1] == "bcd" > False > py> s.startswith("bcd", 1, -1) > True > > > Oops. > > You'd have to do both startswith() and endswith() tests, and even then > it doesn't work: Since the OP suggested startswith/endswith I assumed that's what he wanted... His example: s = "abcde" test = s[1, -1] == "bcd" # no!, builds a substring test = s.sub_is(1, -1, "bcd") # yes! what I'm searching tests the substring 'bcde' and apparently was expected to return True for 'bcd'... hence the suggestion to use startswith If he wants to test for equality of a substring then provided the start/end are set correctly startwith will still work, but you need to ensure that end is exactly (start+len(subst)). ie test = s.startswith('bcd', 1, 1+len('bcd') ) And that's a bit error prone so I'd still opt for slicing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From mail at peterzorn.de Tue Nov 26 15:22:54 2013 From: mail at peterzorn.de (Peter Zorn) Date: Tue, 26 Nov 2013 15:22:54 +0100 (CET) Subject: [Tutor] Output not legible when debugging with ipdb Message-ID: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Hi everyone - I'm fairly new to Python and I'm working through this ( ) tutorial to learn the language. I've encountered a problem with the ipdb debugger and I wonder if anyone can help. When I run this code ( ) and include the "import ipdb; ipdb.set_trace()" command line, the ipdb debugger starts but its output is not legible (see debugging1.pdf in attach). In addition, after I ran the code, the layout of any other terminal output is also changed (see debugging2.pdf). I'm running Python(x,y) on Windows 7 64-bit in the Windows Powershell, but I've had the same problem with the Anaconda distribution of Python. Thanks, Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: debugging1.pdf Type: application/pdf Size: 139010 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: debugging2.pdf Type: application/pdf Size: 88508 bytes Desc: not available URL: From reuben.dlink at gmail.com Tue Nov 26 11:57:57 2013 From: reuben.dlink at gmail.com (Reuben) Date: Tue, 26 Nov 2013 16:27:57 +0530 Subject: [Tutor] How to set variables inside a class() In-Reply-To: References: Message-ID: Yes! I got my answer now. Thanks all @Dominick: sorry about my explanation. On 26-Nov-2013 4:24 PM, "Alan Gauld" wrote: > On 26/11/13 07:30, Reuben wrote: > >> Hi, >> >> Following is my code: >> ############################################# >> class Animal(): >> >> flag = True >> print flag >> >> def __init__(self,name): >> self.name = name >> print self.name >> >> def walk(self): >> print "I am walking" >> >> >> if __name__ == '__main__': >> test = Animal('boxer') >> test.flag = False >> > > > If you really want the flag to be a class attribute rather than an > instance one you should set it using the class name. So instead of > test.flag use > Animal.flag = False > > That works inside the class methods too. > > By setting test.flag you are creating a new instance level attribute > that exists only within the test instance. That's legal Python > but usually its not a good idea to have different instances of > the same class having different attributes. > > >>> class C: > ... f = True > ... def g(self): self.f = 42 > ... > >>> c = C() > >>> c.f > True > >>> c.g() > >>> c.f > 42 > >>> C.f > True > >>> d = C() > >>> d.f = 66 > >>> d.f > 66 > >>> C.f > True > >>> > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 26 15:59:54 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 26 Nov 2013 14:59:54 +0000 (GMT) Subject: [Tutor] string codes In-Reply-To: <52947F77.4070400@gmail.com> References: <529467B2.3080500@gmail.com> <52947F77.4070400@gmail.com> Message-ID: <1385477994.12421.YahooMailNeo@web186005.mail.ir2.yahoo.com> Pleae use ReplyAll to include the list. > c = ord(s[2]) > >Yes, that's it: i forgot about Python's builtin functions, only searched among >methods. Then, two more questions: >-1- Why isn't this a str method? s.ord() [or better s.code()] looks natural, >doesn't it?Because it operates on a single character not a whole string. And ordinal is the correct name for the numerical position of the character,? code is a woolly term that could mean just about anything. -2- Apparently, I need to create a 1-char-long substring just to get the ordinal? > >code? Isn't that unneeded runtime work? Or does the compiler translate this to >only getting the i-th code, without creating any substring?? > >You seem to have a hangup about creating substrings? ?A one char substring? it just a single byte, that's not a big deal. In the bigger scheme of things its not? going?to produce any noticeable performance overhead. Else, what about?extending the ord func with an index param: >??? ord(s, index=0)How would moving the indexing inside ord be an improvement? It's still doing? exactly the same job. or better: > >??? s.code(index=0)How would that look in a loop: for c in mystring: ? ? ?print ord(c) for index in range(len(mystring)): ? ? print mystring.code(index) I know which I prefer Aren't you as surprised as I am, that this param does not exist? >No, I'd be amazed if it did. > test = s.startswith("bcd", 1, -1) > >All right! Then, isn't startswith a misnomer? >No because its testing if the substring startswith your search string. In your example the substring is 'bcde' and it starts with 'bcd'. If you want to trest equality of a substring you need to ensure the? substring and search string are equal in length. [You are right, Alan, but I wouldn't have found there better than in the ref >manuals:?True but help() is faster! :-) help(str) at the command line does not list ord() as a string-related? >True, because it's char based so a builtin like len() Alan g. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rafael.knuth at gmail.com Tue Nov 26 17:15:31 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Tue, 26 Nov 2013 17:15:31 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. Message-ID: Hej there, simple issue I couldn't find a solution for: YourName = input(str("What is your name?")) print("Hello", YourName) When executing the program, in case the user input is "for", "not", "True", "while" Python interprets that as a command and changes the input's color to the corresponding command. The program runs without any further issues, but I was wondering: How can I make sure Python "understands" that the user input is nothing else but a string? I tried to fix that by changing input("What is your name?") to input(str("What is your name?)) but that didn't work. Thanks in advance, Raf From alan.gauld at btinternet.com Tue Nov 26 17:22:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Nov 2013 16:22:21 +0000 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: On 26/11/13 16:15, Rafael Knuth wrote: > YourName = input(str("What is your name?")) > print("Hello", YourName) > > When executing the program, in case the user input is "for", "not", > "True", "while" Python interprets that as a command Sounds like you are using Python v2. You need to yuse raw_input() instead of input(). In Python v3 the old input was removed and raw_input renamed to input() Are you by any chance reading a v3 tutorial but using v2? BTW the str() in > YourName = input(str("What is your name?")) does nothing since "What is your name?" is already a string -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Nov 26 17:35:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Nov 2013 16:35:20 +0000 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: On 26/11/13 14:22, Peter Zorn wrote: > I've encountered a problem with the ipdb debugger and I > wonder if anyone can help. When I run this code > ( http://quant-econ.net/ipython.html#setting-a-break-point) > and include the "import ipdb; ipdb.set_trace()" command line, the ipdb > debugger starts but its output is not legible (see debugging1.pdf in > attach). Please attach (or better, paste the content in the mail) the file Debugging.py we need to see the exact code that you are running not the code in the tutorial. Also what happens if you remove the debugging line and run the same code? [ Incidentally, most of the things the page says about IPython can be done nearly as easily in standard Python. Now IPyton is a fine shell but the page hardly shows its advantages! ] > I'm running Python(x,y) on Windows 7 64-bit in the Windows Powershell, That shouldn't make much difference but just in case what happens if you use a CMD prompt window? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Tue Nov 26 17:49:48 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Nov 2013 17:49:48 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. References: Message-ID: Rafael Knuth wrote: > Hej there, > > simple issue I couldn't find a solution for: > > YourName = input(str("What is your name?")) > print("Hello", YourName) > > When executing the program, in case the user input is "for", "not", > "True", "while" Python interprets that as a command and changes the > input's color to the corresponding command. The program runs without > any further issues, but I was wondering: How can I make sure Python > "understands" that the user input is nothing else but a string? I > tried to fix that by changing input("What is your name?") to > input(str("What is your name?)) but that didn't work. > > Thanks in advance, Are you running the program inside idle? The (in this case unwanted) syntax highlighting is a feature of idle's shell. You could try and make a feature request on for smarter colouring. From wprins at gmail.com Tue Nov 26 17:50:41 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 26 Nov 2013 16:50:41 +0000 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: Hi, On 26 November 2013 14:22, Peter Zorn wrote: > Hi everyone - > > I'm fairly new to Python and I'm working through this ( > http://quant-econ.net/) tutorial to learn the language. > > I've encountered a problem with the ipdb debugger and I > wonder if anyone can help. When I run this code > ( http://quant-econ.net/ipython.html#setting-a-break-point) > and include the "import ipdb; ipdb.set_trace()" command line, the ipdb > debugger starts but its output is not legible (see debugging1.pdf in > attach). In addition, after I ran the code, the layout of any other > terminal output is also changed (see debugging2.pdf). > > I'm running Python(x,y) on Windows 7 64-bit in the Windows Powershell, > but I've had the same problem with the Anaconda distribution of Python. > > All those arrows and codes you see are called "ANSI escape codes" or "ANSI control codes". It's a way to control/signal text colour and formatting inline for text terminals. I don't know whether or not it does, but if Windows Powershell does not support ANSI escape codes then I'd expect the above style of output, so either it doesn't support it, or it does but isn't enabled. You might prefer and I'd suggest you use a terminal program that does support ANSI escape codes, such as ConEmu or Console2: http://sourceforge.net/projects/console https://code.google.com/p/conemu-maximus5/ (Personally I use ConEmu with IPython as my system shell as well as Python REPL.) Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 26 17:53:37 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 26 Nov 2013 16:53:37 +0000 (GMT) Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: <1385484817.48070.YahooMailNeo@web186004.mail.ir2.yahoo.com> Please always use ReplyAll to include the list. > thanks - that's weird. I am using Python 3.3.0 and changed input() to >raw_input() but I get an error message now: > >NameError: name 'raw_input' is not defined OK, That's what you'd expect in 3.3 because raw_input is now input(). But in that case input() should not do anything with your input. Can you post a session showing the input and the odd behaviour? Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Tue Nov 26 17:57:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Nov 2013 16:57:56 +0000 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: On 26/11/13 16:49, Peter Otten wrote: >> When executing the program, in case the user input is "for", "not", >> "True", "while" Python interprets that as a command and changes the >> input's color to the corresponding command. ... > > Are you running the program inside idle? The (in this case unwanted) syntax > highlighting is a feature of idle's shell. Good catch, I didn't notice that Rafael was only complaining about the colorizing of his text. I assumed it was actually executing the input. I suspect the colorizing happens in most IDEs not just IDLE? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From rafael.knuth at gmail.com Tue Nov 26 18:02:43 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Tue, 26 Nov 2013 18:02:43 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: <1385484817.48070.YahooMailNeo@web186004.mail.ir2.yahoo.com> References: <1385484817.48070.YahooMailNeo@web186004.mail.ir2.yahoo.com> Message-ID: > OK, That's what you'd expect in 3.3 because raw_input is now input(). > > But in that case input() should not do anything with your input. > > Can you post a session showing the input and the odd behaviour? YourName = input(str("What is your name ?")) print("Hello", YourName) Exemplary input & output: Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> What is your name? for Hello for >>> Color of for is changed to orange on the input line ("What is your name?") Raf > > > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos From __peter__ at web.de Tue Nov 26 18:11:22 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 26 Nov 2013 18:11:22 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. References: Message-ID: Alan Gauld wrote: > On 26/11/13 16:49, Peter Otten wrote: > >>> When executing the program, in case the user input is "for", "not", >>> "True", "while" Python interprets that as a command and changes the >>> input's color to the corresponding command. > ... >> >> Are you running the program inside idle? The (in this case unwanted) >> syntax highlighting is a feature of idle's shell. > > Good catch, I didn't notice that Rafael was only complaining about the > colorizing of his text. I assumed it was actually executing the input. > I suspect the colorizing happens in most IDEs not just IDLE? I don't know, I think it's a side effect of idle using the same window for interaction with command line programs and as the interactive interpreter. From breamoreboy at yahoo.co.uk Tue Nov 26 18:23:09 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 26 Nov 2013 17:23:09 +0000 Subject: [Tutor] How to set variables inside a class() In-Reply-To: <20131126100002.GL5299@keks.naturalnet.de> References: <20131126100002.GL5299@keks.naturalnet.de> Message-ID: On 26/11/2013 10:00, Dominik George wrote: > Hi Reuben, > >> class Animal(): >> >> flag = True >> print flag > > Are you sure you know what this does ;)? Normally, you initialize all > variables in the constructor. > Wrong. You normally initialise names in the initialiser which is called __init__. The constructor is called __new__. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From eryksun at gmail.com Tue Nov 26 19:40:49 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Nov 2013 13:40:49 -0500 Subject: [Tutor] How to set variables inside a class() In-Reply-To: <20131126111352.GQ5299@keks.naturalnet.de> References: <20131126111352.GQ5299@keks.naturalnet.de> Message-ID: On Tue, Nov 26, 2013 at 6:13 AM, Dominik George wrote: > Now when zou instantiate the class, then the dictionary is copied to the > instance (carying references to the same data inside it, mind you!), Perhaps the above is just a simple mistake of wording, but to be clear, the class dict isn't copied to an instance. >>> class Animal(object): # extend object!!! ... flag = True ... >>> a = Animal() >>> Animal.__dict__['flag'] True >>> a.__dict__ # or vars(a) {} The generic object __getattribute__ (tp_getattro slot in the C implementation) looks in the dicts of the type and its bases, i.e. the types in the MRO: >>> class Dog(Animal): ... flag = False ... >>> Dog.__mro__ (, , ) The order of possible return values is as follows: * a data-descriptor class attribute (e.g. a property): return the result of its __get__ method * an instance attribute * a non-data descriptor class attribute (e.g. a function): return the result of its __get__ method (e.g. return a bound instance method) * a non-descriptor class attribute If the attribute isn't found it raises an AttributeError. If you implement the fallback __getattr__ method, the AttributeError is swallowed and the onus is on you. From eryksun at gmail.com Tue Nov 26 18:48:35 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Nov 2013 12:48:35 -0500 Subject: [Tutor] string codes In-Reply-To: <20131126113413.GH2085@ando> References: <529467B2.3080500@gmail.com> <20131126113413.GH2085@ando> Message-ID: On Tue, Nov 26, 2013 at 6:34 AM, Steven D'Aprano wrote: > > I think that views would be useful for *very large strings*, but very > large probably means a lot larger than you might think. For small > strings, say under a few hundred or perhaps even thousand characters, > making a copy of the substring will probably be faster. > > I say "probably", but I'm only guessing, because strings in Python don't > have views. (Perhaps they should?) In 2.7 and 3.x, you can use a memoryview for bytes, bytearray, etc. Unicode strings don't support the new buffer interface. 2.x has a buffer type, but slices create a raw byte string (UTF-16 or UTF-32): >>> b = buffer(u'abcd') >>> b[:8] 'a\x00\x00\x00b\x00\x00\x00' >>> b[:8].decode('utf-32') u'ab' In 3.3, a memoryview can compare strided views: >>> b = b'a**b**c**d**' >>> v = memoryview(b) >>> v[::3].tobytes() b'abcd' >>> v[::3] == b'abcd' True http://docs.python.org/3.3/library/stdtypes.html#memory-views In previous versions memoryview compares the raw bytes, and only for contiguous views. For example, in 2.7: >>> try: v[::3] == b'abcd' ... except NotImplementedError: print ':-(' ... :-( http://docs.python.org/3.2/library/stdtypes.html#memoryview-type http://docs.python.org/2.7/library/stdtypes.html#memoryview-type From eryksun at gmail.com Tue Nov 26 20:01:45 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Nov 2013 14:01:45 -0500 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: On Tue, Nov 26, 2013 at 11:50 AM, Walter Prins wrote: > All those arrows and codes you see are called "ANSI escape codes" or "ANSI > control codes". It's a way to control/signal text colour and formatting > inline for text terminals. I don't know whether or not it does, but if > Windows Powershell does not support ANSI escape codes then I'd expect the > above style of output, so either it doesn't support it, or it does but isn't > enabled. Windows Powershell is just another console program. It's waiting in the background for IPython to close. The console window is hosted by csrss.exe (NT 3.1-6.0) or conhost.exe (NT 6.1+). But otherwise you're correct that a Windows console window doesn't grok terminal escape sequences (its API is instead based on kernel32 functions). With ConEmu, the original console window still exists (for standard I/O), but it's hiding in shame. From dyoo at hashcollision.org Tue Nov 26 20:45:23 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 26 Nov 2013 11:45:23 -0800 Subject: [Tutor] Dict In-Reply-To: References: Message-ID: > > Is it possible to sort dict & to get result as dict? > if it is possible, please give some example. > Just to understand the question more, can you give more details? Why would you want a sorted dict? That is, it is not directly obvious what your intent is yet, so you need to say more. Are you thinking of something similar to how human language dictionary entries are traditionally sorted lexicographically, or do you mean something else? -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Tue Nov 26 20:42:29 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 26 Nov 2013 11:42:29 -0800 (PST) Subject: [Tutor] string replacement in Python 2 and 3 Message-ID: <1385494949.58173.YahooMailBasic@web163805.mail.gq1.yahoo.com> Hi, String replacement works quite differently with bytes objects in Python 3 than with string objects in Python 2. What is the best way to make example #1 below run in Python 2 and 3? Should one really decode the bytes keys and (if applicable) the values to unicode? The code gets so bloated with all these decodes all over the place. But to avoid ugly things like under #2 (Python 3) I see no other option, same for the errors of the other examples. Or am I overlooking something? I guess I am treating python 2 strings too much like python 3 bytes. #Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 >>> kwargs = {b'a': 1, b'b': 2}? ? # 1 >>> b'%(a)s, %(b)s' % kwargs '1, 2' >>> '%s' % b'ugly'? # 2 'ugly' >>> b'%s' % b'ugly'? # 3 'ugly' >>> b'%s'.decode('utf-8') % 'ugly'? #4 u'ugly' # Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32 >>> kwargs = {b'a': 1, b'b': 2}? # 1 >>> b'%(a)s, %(b)s' % kwargs Traceback (most recent call last): ? File "", line 1, in ? ? b'%(a)s, %(b)s' % kwargs TypeError: unsupported operand type(s) for %: 'bytes' and 'dict' >>> '%s' % b'ugly'? # 2 "b'ugly'" >>> b'%s' % b'ugly'? # 3 Traceback (most recent call last): ? File "", line 1, in ? ? b'%s' % b'ugly' TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes' >>> b'%s' % 'ugly'? # 4 Traceback (most recent call last): ? File "", line 1, in ? ? b'%s' % 'ugly' TypeError: unsupported operand type(s) for %: 'bytes' and 'str' >>> b'%s'.decode('utf-8') % 'ugly' 'ugly' Regards, 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 dyoo at hashcollision.org Tue Nov 26 21:01:10 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 26 Nov 2013 12:01:10 -0800 Subject: [Tutor] string codes In-Reply-To: <529467B2.3080500@gmail.com> References: <529467B2.3080500@gmail.com> Message-ID: Hi Denis, For reference, you can explore the documentation to find out what strings can do: http://docs.python.org/3/library/stdtypes.html#text-sequence-type-str > What is the method to get a code or list of codes inside a string: > s = "abcde" > c = s.code(2) > assert(c == 0x63) > ? Strings are sequences, so we can iterate over them to get the individual code points, using the ord() function: http://docs.python.org/3/library/functions.html#ord For example: ################# >>> map(ord, "abcde") [97, 98, 99, 100, 101] ################# If you prefer list comprehensions, its use is similar: ############################################# >>> [ord(ch) for ch in "hello world"] [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] ############################################# > Is there a method to compare a substring, without building a substring from the big one? Like startswith or endswith, but anywhere inside the string? > test = s[1, -1] == "bcd" # no!, builds a substring > test = s.sub_is(1, -1, "bcd") # yes! what I'm searching > According to: http://docs.python.org/3/library/stdtypes.html#str.find you can optionally pass in "start" and "end" keyword arguments to apply boundaries on the string you're searching. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Nov 26 22:28:03 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 26 Nov 2013 21:28:03 +0000 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: Hi, On 26 November 2013 19:01, eryksun wrote: > On Tue, Nov 26, 2013 at 11:50 AM, Walter Prins wrote: > > All those arrows and codes you see are called "ANSI escape codes" or > "ANSI > > control codes". It's a way to control/signal text colour and formatting > > inline for text terminals. I don't know whether or not it does, but if > > Windows Powershell does not support ANSI escape codes then I'd expect the > > above style of output, so either it doesn't support it, or it does but > isn't > > enabled. > > Windows Powershell is just another console program. It's waiting in > the background for IPython to close. The console window is hosted by > csrss.exe (NT 3.1-6.0) or conhost.exe (NT 6.1+). But otherwise you're > correct that a Windows console window doesn't grok terminal escape > sequences (its API is instead based on kernel32 functions). With > ConEmu, the original console window still exists (for standard I/O), > but it's hiding in shame. > Thanks for clarifying some of the underlying details though the point/implications of the details you're giving went over my head to be honest. Regarding Powershell (vs for example cmd.exe): The (slightly) perplexing/irritating/annoying thing is that the older cmd.exe shell, which uses a standard old-school NT console window, does support ANSI escape sequences (but is otherwise pretty braindead IMHO, for example does not support arbitrary resizing, copy and paste is clunky and so on), while the text mode/console window hosting Powershell behaves somewhat differently, and is (IIRC) at least resizable, but apparently doesn't support escape sequences, so there appears to be some differences -- though I realize these must be due to features in the shells themselves since they share some common console window functionality. Anyway, my real point/suggestion was that the OP's problem with IPython's colourized output will be most easily solved by ensuring you have something in the terminal pipleine that will interpret ANSI escape sequences, and that one of the best ways to achieve that is to use an aftermarket terminal/console emulator (which for that matter can server for Powershell as well if that's your thing.) :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 26 23:33:46 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Nov 2013 09:33:46 +1100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: <20131126223345.GL2085@ando> On Tue, Nov 26, 2013 at 05:15:31PM +0100, Rafael Knuth wrote: > Hej there, > > simple issue I couldn't find a solution for: > > YourName = input(str("What is your name?")) > print("Hello", YourName) > > When executing the program, in case the user input is "for", "not", > "True", "while" Python interprets that as a command and changes the > input's color to the corresponding command. Python does nothing of the sort. Python doesn't know anything about colours, and doesn't colour text. What is colouring the text is the environment you are running your code in. My guess is that you are using IDLE. I would consider that a bug in IDLE. There can be various things involved in running a Python script: the OS, Python itself, an external REPL like IDLE, the operating system's shell, a web server like Apache, etc. Unfortunately, until you have a bit of experience and are able to recognise which component is responsible for what, it can sometimes be tricky to decide what to blame. That is why it can be important to explain what environment you are running under or how you are running Python: "Using Python 3.3 under Windows using IDLE" "Using Python 2.7 directly under Linux" sort of thing. Don't worry, as you get more experienced you'll soon pick up when those details are irrelevant, but until then, better to mention it when you ask a question. When using an external REPL (Read, Eval, Print Loop) like IDLE or bpython, if you run into a tricky problem that doesn't make sense, you ought to try bypassing that component by running the code directly in Python. Do I need to explain how to do this, or do you already know? By the way, "What is your name?" is already a str. Calling str() on it again does nothing. -- Steven From steve at pearwood.info Tue Nov 26 23:39:06 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Nov 2013 09:39:06 +1100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: <20131126223906.GM2085@ando> On Tue, Nov 26, 2013 at 04:57:56PM +0000, Alan Gauld wrote: > On 26/11/13 16:49, Peter Otten wrote: > > >>When executing the program, in case the user input is "for", "not", > >>"True", "while" Python interprets that as a command and changes the > >>input's color to the corresponding command. > ... > > > >Are you running the program inside idle? The (in this case unwanted) syntax > >highlighting is a feature of idle's shell. > > Good catch, I didn't notice that Rafael was only complaining about the > colorizing of his text. I assumed it was actually executing the input. > I suspect the colorizing happens in most IDEs not just IDLE? Nope. I've just tested it in bpython, and it colorizes strings correctly. It's a bug in IDLE if it colorizes strings as keywords. -- Steven From eryksun at gmail.com Wed Nov 27 00:24:09 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Nov 2013 18:24:09 -0500 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: On Tue, Nov 26, 2013 at 4:28 PM, Walter Prins wrote: > > honest. Regarding Powershell (vs for example cmd.exe): The (slightly) > perplexing/irritating/annoying thing is that the older cmd.exe shell, which > uses a standard old-school NT console window, does support ANSI escape > sequences (but is otherwise pretty braindead IMHO, for example does not > support arbitrary resizing, copy and paste is clunky and so on), while the > text mode/console window hosting Powershell behaves somewhat differently, > and is (IIRC) at least resizable, but apparently doesn't support escape > sequences, so there appears to be some differences -- though I realize these > must be due to features in the shells themselves since they share some > common console window functionality. The cmd shell's built-in "type" and "echo" commands don't parse escape sequences. I think "color" is the only command that sets character attributes, and only for the entire screen buffer (e.g. "color 0D" sets light purple text on a black background). Adding escape-sequence support to existing programs such as cmd.exe has to be done in the console itself or by hacking the console API. ConEmu manages a hidden console window and does all of its own display. There's also ANSICON, which injects a DLL (ansi32.dll or ansi64.dll) into the process. My guess is that the DLL hooks kernel32 WriteConsole to look for escape sequences and then scripts the console API. However it works, it's very simple to use: ANSICON https://github.com/adoxa/ansicon Console API http://msdn.microsoft.com/en-us/library/ms682073 I agree the Windows console is braindead. It was fine for its day in NT 3 and 4 back in the 90s, but it hasn't improved much in 20 years, and I doubt it ever will. Maybe with PowerShell you're thinking of the Integrated Scripting Environment: http://technet.microsoft.com/en-us/library/dd819514 For IPython, try the Qt console: http://ipython.org/ipython-doc/stable/interactive/qtconsole.html From steve at pearwood.info Wed Nov 27 00:36:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Nov 2013 10:36:24 +1100 Subject: [Tutor] string replacement in Python 2 and 3 In-Reply-To: <1385494949.58173.YahooMailBasic@web163805.mail.gq1.yahoo.com> References: <1385494949.58173.YahooMailBasic@web163805.mail.gq1.yahoo.com> Message-ID: <20131126233624.GP2085@ando> On Tue, Nov 26, 2013 at 11:42:29AM -0800, Albert-Jan Roskam wrote: > Hi, > > String replacement works quite differently with bytes objects in > Python 3 than with string objects in Python 2. What is the best way to > make example #1 below run in Python 2 and 3? If you are working with text strings, always use the text string type. In Python 3, that is called "str". In Python 2, that is called "unicode". To make it easier, I do this at the top of the module: try: unicode except NameError: # Python 3. pass else: # Python 2. str = unicode then always use str. Or, if you prefer: try: unicode except NameError: # Python 3. unicode = str and always use unicode. As an alternative, if you need to support Python 2.7 and 3.3 only, you can use u'' string literals: s = u"Hello World!" Sadly, Python 3.1 and 3.2 (don't use 3.0, it's broken) don't support the u string prefix. If you have to support them: if sys.version < '3': def u(astr): return unicode(astr) else: def u(astr): return astr and then call: s = u("Hello World!") *but* be aware that this only works with ASCII string literals. We can make u() be smarter and handle more cases: if sys.version < '3': def u(obj, encoding='utf-8', errors='strict'): if isinstance(obj, str): return obj.decode(encoding, errors) elif isinstance(obj, unicode): return obj else: return unicode(obj) else: def u(obj, encoding='utf-8', errors='strict'): if isinstance(obj, str): return obj elif isinstance(obj, bytes): return obj.decode(encoding, errors) else: return str(obj) then use the u() function on any string, text or bytes, or any other object, as needed. But the important thing here is: * convert bytes to text as early as possible; * then do all your work using text; * and only convert back to bytes if you really need to, and as late as possible. If you find yourself converting backwards and forwards between bytes and text multiple times for each piece of data, you're doing it wrong. Look at file input in Python 3: when you open a file for reading in text mode, it returns a text string, even though the underlying file on disk is bytes. It decodes those bytes once, as early as it can (when reading), and then for the rest of your program you treat it as text. Then when you write it back out to a file, it encodes it to bytes only when doing the write(). That's the strategy you should aim to copy. Ideally, no string should be encoded or decoded more than once each in its entire lifespan. -- Steven From wprins at gmail.com Wed Nov 27 01:17:25 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 27 Nov 2013 00:17:25 +0000 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: Hi, Thanks for the highly educational response. On 26 November 2013 23:24, eryksun wrote: > On Tue, Nov 26, 2013 at 4:28 PM, Walter Prins wrote: > > > > honest. Regarding Powershell (vs for example cmd.exe): The (slightly) > > perplexing/irritating/annoying thing is that the older cmd.exe shell, > which > > uses a standard old-school NT console window, does support ANSI escape > > sequences (but is otherwise pretty braindead IMHO, for example does not > > support arbitrary resizing, copy and paste is clunky and so on), while > the > > text mode/console window hosting Powershell behaves somewhat differently, > > and is (IIRC) at least resizable, but apparently doesn't support escape > > sequences, so there appears to be some differences -- though I realize > these > > must be due to features in the shells themselves since they share some > > common console window functionality. > > The cmd shell's built-in "type" and "echo" commands don't parse escape > sequences. I think "color" is the only command that sets character > attributes, and only for the entire screen buffer (e.g. "color 0D" > sets light purple text on a black background). > Adding escape-sequence support to existing programs such as cmd.exe > has to be done in the console itself or by hacking the console API. > ConEmu manages a hidden console window and does all of its own > display. There's also ANSICON, which injects a DLL (ansi32.dll or > ansi64.dll) into the process. My guess is that the DLL hooks kernel32 > WriteConsole to look for escape sequences and then scripts the console > API. However it works, it's very simple to use: > ANSICON > https://github.com/adoxa/ansicon > > Console API > http://msdn.microsoft.com/en-us/library/ms682073 Right. Apologies for belaboring this then, but do you know why the bog standard cmd.exe (and for that matter Powershell, now that I've actually checked it as I have it on my machine) has no problem displaying IPython's colourization? Actually now that I write this -- I suddenly vaguely remembering installing PyReadline back when I was setting up IPython in order to get colour and a couple of other things working properly... so presumably it does the ANSI interpretation, and that's probably where the colourization is coming from, perhaps this is what the OP has missing then? PyReadline on PyPi: https://pypi.python.org/pypi/pyreadline/2.0 Consoles on my PC for reference: cmd.exe: http://i.imgur.com/zowlwcw.png powershell: http://i.imgur.com/HxsNlH8.png Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sl70176 at gmail.com Tue Nov 26 20:00:41 2013 From: sl70176 at gmail.com (Sam Lalonde) Date: Tue, 26 Nov 2013 14:00:41 -0500 Subject: [Tutor] Splitting lists with strings and integers Message-ID: Hi, I am very new to python. I have a list with mixed strings/integers. I want to convert this to a list of lists, and I want the numbers to get stored as integers. >>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6'] >>> list2 = [] >>> for animal in list1: ... animal = animal.split() ... list2.append(animal) ... >>> print list2 [['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']] >>> >>> for animal in list2: ... print animal[1] + animal[2] ... 12 34 56 You can see that it just appended the numbers to each other. I'd like the output to be: 3 7 11 Is there a clean way to get the numbers stored as int instead of str when I build list2? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From nik at naturalnet.de Wed Nov 27 01:57:38 2013 From: nik at naturalnet.de (Dominik George) Date: Wed, 27 Nov 2013 01:57:38 +0100 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: References: Message-ID: <20131127005737.GF4637@keks.naturalnet.de> Hi, > I have a list with mixed strings/integers. I want to convert this to a > list of lists, and I want the numbers to get stored as integers. First, let's do it with a list comprehension. You should really learn those if you do serious Python programming ;)! list2 = [[int(z) if z.isdigit() else z for z in y] for y in [x.split(" ") for x in list1]] Now, to convert every possible numeric string in a list to int in a more readable fashion: for x in xrange(len(animal)): if animal[x].isdigit(): animal[x] = int(animal[x]) So: - the isdigit() method of a string tells you if it is numeric - int() casts to an integer The list comprehension does the whole converion with list comprehensions. You should consider readability when doing such things, but you should learn it. -nik -- # apt-assassinate --help Usage: apt-assassinate [upstream|maintainer] PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From amitsaha.in at gmail.com Wed Nov 27 02:00:23 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 27 Nov 2013 11:00:23 +1000 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: References: Message-ID: On Wed, Nov 27, 2013 at 5:00 AM, Sam Lalonde wrote: > Hi, I am very new to python. > > I have a list with mixed strings/integers. I want to convert this to a list > of lists, and I want the numbers to get stored as integers. > >>>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6'] >>>> list2 = [] >>>> for animal in list1: > ... animal = animal.split() > ... list2.append(animal) > ... >>>> print list2 > [['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']] >>>> >>>> for animal in list2: > ... print animal[1] + animal[2] > ... > 12 > 34 > 56 The numbers are appended because: '1' + '2' = '12' and so on. > > You can see that it just appended the numbers to each other. I'd like the > output to be: > > 3 > 7 > 11 > > Is there a clean way to get the numbers stored as int instead of str when I > build list2? Consider your original list: >>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6'] For each item of the list, you want to extract the numbers and add them with the sums in a new list. Let's take it one step at a time >>> # extract the numbers only ... for item in list1: ... print item.split()[1:] ... ['1', '2'] ['3', '4'] ['5', '6'] But, we want each number as integer and print their sum instead of the individual numbers: >>> for item in list1: ... print int(item.split()[1]) + int(item.split()[2]) ... 3 7 11 So, we have our numbers. But we would like this to be a list instead. So, instead of printing, simply create a list. Hope that helps. Best, Amit. > > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- http://echorand.me From alan.gauld at btinternet.com Wed Nov 27 02:09:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Nov 2013 01:09:27 +0000 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: References: Message-ID: On 26/11/13 19:00, Sam Lalonde wrote: > >>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6'] > >>> list2 = [] > >>> for animal in list1: > ... animal = animal.split() > ... list2.append(animal) > ... This could be a list comprehension: list2 = [animal.split() for animal in list1] > >>> print list2 > [['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']] > >>> > >>> for animal in list2: > ... print animal[1] + animal[2] > ... > 12 > > You can see that it just appended the numbers to each other. I'd like > the output to be: > > 3 > > Is there a clean way to get the numbers stored as int instead of str > when I build list2? Define "clean". You can use int() on the last two in a second comprehension: list2 = [ [type, int(x), int(y)] for type,x,y in list2 ] Or you could just wait to the point of use... for animal in list2: print int(animal[1]) + int(animal[2]) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From breamoreboy at yahoo.co.uk Wed Nov 27 02:13:00 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 27 Nov 2013 01:13:00 +0000 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: <20131127005737.GF4637@keks.naturalnet.de> References: <20131127005737.GF4637@keks.naturalnet.de> Message-ID: On 27/11/2013 00:57, Dominik George wrote: > Hi, > >> I have a list with mixed strings/integers. I want to convert this to a >> list of lists, and I want the numbers to get stored as integers. > > First, let's do it with a list comprehension. You should really learn those if you do serious Python programming ;)! > > list2 = [[int(z) if z.isdigit() else z for z in y] for y in [x.split(" ") for x in list1]] > > Now, to convert every possible numeric string in a list to int in a more > readable fashion: > > for x in xrange(len(animal)): > if animal[x].isdigit(): > animal[x] = int(animal[x]) > Before posting anything else would you please do a tutorial yourself. The above for loop is appalling newbie code, I'll leave you to post the Pythonic format. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From nik at naturalnet.de Wed Nov 27 02:18:45 2013 From: nik at naturalnet.de (Dominik George) Date: Wed, 27 Nov 2013 02:18:45 +0100 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: References: <20131127005737.GF4637@keks.naturalnet.de> Message-ID: <20131127011845.GG4637@keks.naturalnet.de> > > for x in xrange(len(animal)): > > if animal[x].isdigit(): > > animal[x] = int(animal[x]) > > > > Before posting anything else would you please do a tutorial > yourself. The above for loop is appalling newbie code, I'll leave > you to post the Pythonic format. Can I trust my ears? Did you just make a move to expell me from posting newbie-readable code on a newbie-list :D? Believe me, I do not need a tutorial. Seriously not. Just in case you missed it, the pythonic code is a few lines above in my post. If that is not enough for you, start a private Python helpdesk with all your glory and remove me from the list. And in the future, please refrain from carpeting me on a public mailing list. Thanks! -- Wer den Gr?nkohl nicht ehrt, ist der Mettwurst nicht wert! PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From eryksun at gmail.com Wed Nov 27 02:28:24 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Nov 2013 20:28:24 -0500 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: On Tue, Nov 26, 2013 at 7:17 PM, Walter Prins wrote: > Actually now that I write this -- I suddenly vaguely remembering installing > PyReadline back when I was setting up IPython in order to get colour and a > couple of other things working properly... so presumably it does the ANSI > interpretation, and that's probably where the colourization is coming from, > perhaps this is what the OP has missing then? > > PyReadline on PyPi: https://pypi.python.org/pypi/pyreadline/2.0 That's the ticket. PyReadline has a console subpackage that uses ctypes to access the Windows console API. The AnsiWriter class splits the string into chunks with a given character attribute state (i.e. color, bold, reverse) to be set by SetConsoleTextAttribute before writing the chunk to the console. https://github.com/pyreadline/pyreadline/tree/master/pyreadline/console From __peter__ at web.de Wed Nov 27 09:45:20 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Nov 2013 09:45:20 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. References: Message-ID: Rafael Knuth wrote: > simple issue I couldn't find a solution for: > > YourName = input(str("What is your name?")) > print("Hello", YourName) > > When executing the program, in case the user input is "for", "not", > "True", "while" Python interprets that as a command and changes the > input's color to the corresponding command. The program runs without > any further issues, but I was wondering: How can I make sure Python > "understands" that the user input is nothing else but a string? I > tried to fix that by changing input("What is your name?") to > input(str("What is your name?)) but that didn't work. > > Thanks in advance, I took the freedom to report it myself: http://bugs.python.org/issue19808 From rafael.knuth at gmail.com Wed Nov 27 09:54:16 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Wed, 27 Nov 2013 09:54:16 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: Thank you, Peter! On Wed, Nov 27, 2013 at 9:45 AM, Peter Otten <__peter__ at web.de> wrote: > Rafael Knuth wrote: > >> simple issue I couldn't find a solution for: >> >> YourName = input(str("What is your name?")) >> print("Hello", YourName) >> >> When executing the program, in case the user input is "for", "not", >> "True", "while" Python interprets that as a command and changes the >> input's color to the corresponding command. The program runs without >> any further issues, but I was wondering: How can I make sure Python >> "understands" that the user input is nothing else but a string? I >> tried to fix that by changing input("What is your name?") to >> input(str("What is your name?)) but that didn't work. >> >> Thanks in advance, > > I took the freedom to report it myself: > > http://bugs.python.org/issue19808 > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From breamoreboy at yahoo.co.uk Wed Nov 27 11:12:00 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 27 Nov 2013 10:12:00 +0000 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: On 27/11/2013 08:45, Peter Otten wrote: > Rafael Knuth wrote: > >> simple issue I couldn't find a solution for: >> >> YourName = input(str("What is your name?")) >> print("Hello", YourName) >> >> When executing the program, in case the user input is "for", "not", >> "True", "while" Python interprets that as a command and changes the >> input's color to the corresponding command. The program runs without >> any further issues, but I was wondering: How can I make sure Python >> "understands" that the user input is nothing else but a string? I >> tried to fix that by changing input("What is your name?") to >> input(str("What is your name?)) but that didn't work. >> >> Thanks in advance, > > I took the freedom to report it myself: > > http://bugs.python.org/issue19808 > Thanks Peter. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From fomcl at yahoo.com Wed Nov 27 11:24:45 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 27 Nov 2013 02:24:45 -0800 (PST) Subject: [Tutor] string replacement in Python 2 and 3 In-Reply-To: <20131126233624.GP2085@ando> Message-ID: <1385547885.85652.YahooMailBasic@web163804.mail.gq1.yahoo.com> -------------------------------------------- On Wed, 11/27/13, Steven D'Aprano wrote: Subject: Re: [Tutor] string replacement in Python 2 and 3 To: tutor at python.org Date: Wednesday, November 27, 2013, 12:36 AM On Tue, Nov 26, 2013 at 11:42:29AM -0800, Albert-Jan Roskam wrote: > Hi, > > String replacement works quite differently with bytes objects in > Python 3 than with string objects in Python 2. What is the best way to > make example #1 below run in Python 2 and 3? If you are working with text strings, always use the text string type. In Python 3, that is called "str". In Python 2, that is called "unicode". To make it easier, I do this at the top of the module: try: ? ? unicode except NameError: ? ? # Python 3. ? ? pass else: ? ? # Python 2. ? ? str = unicode then always use str. Or, if you prefer: try: ? ? unicode except NameError: ? ? # Python 3. ? ? unicode = str and always use unicode. As an alternative, if you need to support Python 2.7 and 3.3 only, you can use u'' string literals: s = u"Hello World!" Sadly, Python 3.1 and 3.2 (don't use 3.0, it's broken) don't support the u string prefix. If you have to support them: if sys.version < '3': ? ? def u(astr): ? ? ? ? return unicode(astr) else: ? ? def u(astr): ? ? ? ? return astr and then call: s = u("Hello World!") *but* be aware that this only works with ASCII string literals. We can make u() be smarter and handle more cases: if sys.version < '3': ? ? def u(obj, encoding='utf-8', errors='strict'): ? ? ? ? if isinstance(obj, str): ? ? ? ? ? ? return obj.decode(encoding, errors) ? ? ? ? elif isinstance(obj, unicode): ? ? ? ? ? ? return obj ? ? ? ? else: ? ? ? ? ? ? return unicode(obj) else: ? ? def u(obj, encoding='utf-8', errors='strict'): ? ? ? ? if isinstance(obj, str): ? ? ? ? ? ? return obj ? ? ? ? elif isinstance(obj, bytes): ? ? ? ? ? ? return obj.decode(encoding, errors) ? ? ? ? else: ? ? ? ? ? ? return str(obj) then use the u() function on any string, text or bytes, or any other object, as needed. But the important thing here is: * convert bytes to text as early as possible; * then do all your work using text; * and only convert back to bytes if you really need to, ? and as late as possible. If you find yourself converting backwards and forwards between bytes and text multiple times for each piece of data, you're doing it wrong. Look at file input in Python 3: when you open a file for reading in text mode, it returns a text string, even though the underlying file on disk is bytes. It decodes those bytes once, as early as it can (when reading), and then for the rest of your program you treat it as text. Then when you write it back out to a file, it encodes it to bytes only when doing the write(). That's the strategy you should aim to copy. Ideally, no string should be encoded or decoded more than once each in its entire lifespan. ===> Hi Steven, Thanks for your advice (esp. the bullets are placemat-worthy ;-). I will have a crtical look at my code to see where I can improve it. I am reading binary data so I start with str (Python 2) or bytes (Python 3). Before I was adapting my code for use in both Python versions, I simply returned string (Python 2 sense of the word) data. So in Pyhon 3 it seemed consisent to return bytes. In one case, I add padding to values to get rid of null bytes. That's a small operation that's done very very often. The first example below is MUCH faster than ljust, but it does not work in Python 3. Maybe Donald Knuth should slap me because I am optimzing prematurely, >>> value = b"blah" >>> b"%-50s" % value # fast, but not python 3 proof 'blah ' >>> value.ljust(50) # okay, this will have to do for python 3, then 'blah ' ' regards, Albert-Jan From steve at pearwood.info Wed Nov 27 11:54:00 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Nov 2013 21:54:00 +1100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: References: Message-ID: <20131127105400.GR2085@ando> On Wed, Nov 27, 2013 at 09:45:20AM +0100, Peter Otten wrote: > I took the freedom to report it myself: > > http://bugs.python.org/issue19808 Thanks for reporting the issue! [off-topic] You might like to know that the standard English idiom is "I took the liberty" rather than "freedom". In general, liberty is a synonym for freedom. We might fight for liberty from oppression or freedom from hunger. However, the phrases "to take the liberty" and "to take liberties" are a little different. Both carry connotations of going a bit too far, both are very old-fashioned, with the flavour of Victorian England, or perhaps as late as the 1920s. To take liberties is (potentially) a criticism, typically spoken by a women to a man who has been a little too enthusiastic about making romantic advances. The image it often brings to the mind of English speakers is of a very prim and proper young women mildly chastising a young gentleman for being too forward with his romantic overtures (but often with a twinkle in her eye, as if to say they're not completely unwelcome). Alternatively, the words may be said by an elderly matron, severely chastising a young gentleman who has been a bit too keen on the matron's daughter or niece (definitely NOT with a twinkle in the eye!), or perhaps to a servant for talking back, relaxing, or otherwise not obeying her every whim. To take *the* liberty is less negative and more a self-deprecating acknowledgement that the speaker has stepped out of bounds and taken on more responsibility than he should have, but has done so from the best of motives. (Sometimes spoken seriously, these days more often ironically.) The image it brings to mind is of an exceedingly polite, very proper, and hyper-competent butler or valet: "Sir has an appointment with the bank this morning. I have taken the liberty of laying out Sir's best trousers and tweed jacket." Think of Jeeves: http://en.wikipedia.org/wiki/Jeeves Personally, I love both phrases :-) Does German have anything similar? (I presume you are German.) -- Steven From rafael.knuth at gmail.com Wed Nov 27 12:29:22 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Wed, 27 Nov 2013 12:29:22 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. In-Reply-To: <20131127105400.GR2085@ando> References: <20131127105400.GR2085@ando> Message-ID: > Does German have anything similar? (I presume you are German.) Ich nehme mir die Freiheit. (present) Ich habe mir die Freiheit genommen. (past) And in Polish: Pozwalam sobie. (present) Pozwoli?em sobie. (past) ;-) Cheers, Raf From denis.spir at gmail.com Wed Nov 27 10:59:22 2013 From: denis.spir at gmail.com (spir) Date: Wed, 27 Nov 2013 10:59:22 +0100 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: <20131127011845.GG4637@keks.naturalnet.de> References: <20131127005737.GF4637@keks.naturalnet.de> <20131127011845.GG4637@keks.naturalnet.de> Message-ID: <5295C27A.3040600@gmail.com> On 11/27/2013 02:18 AM, Dominik George wrote: >> >Before posting anything else would you please do a tutorial >> >yourself. The above for loop is appalling newbie code, I'll leave >> >you to post the Pythonic format. > Can I trust my ears? Did you just make a move to expell me from posting > newbie-readable code on a newbie-list :D? > > Believe me, I do not need a tutorial. Seriously not. Just in case you > missed it, the pythonic code is a few lines above in my post. > > If that is not enough for you, start a private Python helpdesk with all > your glory and remove me from the list. > > And in the future, please refrain from carpeting me on a public mailing > list. Maybe i'm wrong on this: isn't python-tutor supposed to be a place for mutual help & cooperation, rather than universal war & competition...? ;-) Denis From denis.spir at gmail.com Wed Nov 27 11:19:19 2013 From: denis.spir at gmail.com (spir) Date: Wed, 27 Nov 2013 11:19:19 +0100 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: References: Message-ID: <5295C727.9050805@gmail.com> On 11/26/2013 08:00 PM, Sam Lalonde wrote: > Hi, I am very new to python. > > I have a list with mixed strings/integers. I want to convert this to a > list of lists, and I want the numbers to get stored as integers. > >>>> list1 = ['dog 1 2', 'cat 3 4', 'mouse 5 6'] There is a little interpretation error in your terms "a list with mixed strings/integers": list1 is a simple list of strings, meaning pieces of textual data. Right? Ii just happens that parts of each of those strings match a standard _notation_ of numbers (natural integers expressed in positional indo-arabic numeral notation, for the matter). Think at this, you could also have: list1 = ['dog I II', 'cat III IV',... or list1 = ['dog uno due', 'cat tre cuatro',... It would be textual data the same way. Number notations are pieces of text. >>>> list2 = [] >>>> for animal in list1: > ... animal = animal.split() > ... list2.append(animal) > ... >>>> print list2 > [['dog', '1', '2'], ['cat', '3', '4'], ['mouse', '5', '6']] >>>> >>>> for animal in list2: > ... print animal[1] + animal[2] > ... > 12 > 34 > 56 > > You can see that it just appended the numbers to each other. I'd like the > output to be: > > 3 > 7 > 11 > > Is there a clean way to get the numbers stored as int instead of str when I > build list2? You must ask Python to _decode_ the numeric notation nested in the pieces of strings into actual numbers, then perform numeric operations on them. Also, before that, for a "clean way" as you say, you may isolate each numeric notation. As a side note, an issue apparent here is that python uses the same operator sign '+' for arithmetic sum and string (con)catenation. (Not all language share this choice, it is a language design point.) Else, you would get a Type Error saying than one cannot add pieces of text. You can get an answer to this question in the Python programming FAQ at [http://docs.python.org/2/faq/programming.html#is-there-a-scanf-or-sscanf-equivalent] (scanf is the C function that does what you need). Also [http://docs.python.org/2/faq/programming.html#how-do-i-convert-a-string-to-a-number]. > Thanks Denis From silamike at ymail.com Wed Nov 27 11:15:22 2013 From: silamike at ymail.com (Mike Sila) Date: Wed, 27 Nov 2013 02:15:22 -0800 (PST) Subject: [Tutor] Returns an iterator of tuples In-Reply-To: References: Message-ID: <1385547322.66271.YahooMailNeo@web160205.mail.bf1.yahoo.com> I know what return, iteration and tuples are.? Can anyone please tell me what an iterator of tuples is? Thanks On Wednesday, November 27, 2013 11:00 AM, "tutor-request at python.org" wrote: Welcome to the Tutor at python.org mailing list! This list is for folks who want to ask (and/or answer) questions from folks who wish to learn how to program with Python.? Feel free to ask even the most basic of questions -- that's what the list is for! For best results when asking a question on this list: - Try to write some code to solve your problem - Show the code you have written - Describe what the code does and what you want it to do - If the code generates an error, copy and paste the entire error message, including the traceback, into your email. - Tell us what OS and Python version you are using. - Don't ask us to do your homework. - Don't assume we know what you are talking about. If you are having trouble with a third-party library, include a link to the library home page. When replying to a posting: - Use Reply All to reply to the entire list - Don't top post - put your reply after the text to which you are replying For all posts: - Format your email as plain text, not HTML To post to this list, send your message to: ? tutor at python.org General information about the mailing list is at: ? https://mail.python.org/mailman/listinfo/tutor If you ever want to unsubscribe or change your options (eg, switch to or from digest mode, change your password, etc.), visit your subscription page at: ? https://mail.python.org/mailman/options/tutor/silamike%40ymail.com You can also make such adjustments via email by sending a message to: ? Tutor-request at python.org with the word `help' in the subject or body (don't include the quotes), and you will get back a message with instructions. You must know your password to change your options (including changing the password, itself) or to unsubscribe without confirmation.? It is: ? tu_2012_tor Normally, Mailman will remind you of your python.org mailing list passwords once every month, although you can disable this if you prefer.? This reminder will also include instructions on how to unsubscribe or change your account options.? There is also a button on your options page that will email your current password to you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Nov 27 15:52:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 28 Nov 2013 01:52:03 +1100 Subject: [Tutor] Returns an iterator of tuples In-Reply-To: <1385547322.66271.YahooMailNeo@web160205.mail.bf1.yahoo.com> References: <1385547322.66271.YahooMailNeo@web160205.mail.bf1.yahoo.com> Message-ID: <20131127145203.GS2085@ando> On Wed, Nov 27, 2013 at 02:15:22AM -0800, Mike Sila wrote: > I know what return, iteration and tuples are.? Can anyone please tell > me what an iterator of tuples is? An iterator is a thing which returns objects one at a time instead of all at once. The easiest way to get one is to pass a sequence object like a list, string or tuple to the function iter(). An example: py> it = iter("Hello!") py> next(it) 'H' py> next(it) 'e' py> next(it) 'l' py> next(it) 'l' py> next(it) 'o' py> next(it) '!' py> next(it) Traceback (most recent call last): File "", line 1, in StopIteration So an iterator of tuples is an iterator which returns tuples. Here's a simple example: py> it = iter([ (1,2), (3,4), (5,6) ]) py> next(it) (1, 2) py> next(it) (3, 4) py> next(it) (5, 6) -- Steven From rafael.knuth at gmail.com Wed Nov 27 17:08:11 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Wed, 27 Nov 2013 17:08:11 +0100 Subject: [Tutor] Nested for loops Message-ID: Hej there, I am trying to figure out how exactly variables in nested loops are generated, and don't get it 100% right yet. Here's my code: for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n//x) break else: print(n, 'is a prime number') And here's what I assume happens inside these for loops: #1 Round: n = 2 x = no result >>> 2 is a prime number #2 Round: n = 3 x = 2 >>> 3 is a prime number #3 Round: n = 4 x = 3 >>> My assumption about the way these two for loops work is wrong, because the output cannot be "4 is a prime number" for obvious reasons. Can anyone help me understand? I am using Python 3.3.0. Thank you! All the best, Raf From joel.goldstick at gmail.com Wed Nov 27 17:27:34 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 27 Nov 2013 11:27:34 -0500 Subject: [Tutor] Nested for loops In-Reply-To: References: Message-ID: On Wed, Nov 27, 2013 at 11:08 AM, Rafael Knuth wrote: > Hej there, > > I am trying to figure out how exactly variables in nested loops are > generated, and don't get it 100% right yet. Here's my code: > > for n in range(2, 10): > for x in range(2, n): > if n % x == 0: > print(n, 'equals', x, '*', n//x) > break > else: > print(n, 'is a prime number') > > And here's what I assume happens inside these for loops: > > #1 Round: > n = 2 > x = no result > >>> > 2 is a prime number > > #2 Round: > n = 3 > x = 2 > >>> > 3 is a prime number > > #3 Round: > n = 4 > x = 3 > >>> > Round 3 would be n = 4, x = 2. The inner loop starts from its own beginning (x = 2) and repeats as often as necessary to get the break condition or complete to the x = n condition > My assumption about the way these two for loops work is wrong, because > the output cannot be "4 is a prime number" for obvious reasons. > > Can anyone help me understand? > I am using Python 3.3.0. Thank you! > > All the best, > > Raf > I copied your code into a python 2.7 shell and got this: >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... print(n, 'is a prime number') ... (2, 'is a prime number') (3, 'is a prime number') (4, 'equals', 2, '*', 2) (5, 'is a prime number') (6, 'equals', 2, '*', 3) (7, 'is a prime number') (8, 'equals', 2, '*', 4) (9, 'equals', 3, '*', 3) What exactly do you get when you run the code? Since print is a function in python 3, my output will look slightly different than yours > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Wed Nov 27 17:38:13 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Wed, 27 Nov 2013 17:38:13 +0100 Subject: [Tutor] Nested for loops In-Reply-To: References: Message-ID: <20131127173813.38ded403@Hof> Rafael Knuth wrote: >I am trying to figure out how exactly variables in nested loops are >generated, and don't get it 100% right yet. Here's my code: Maybe it's easier if you look at a simpler example like: for i in range(4): for j in range(4): print("i: {}, j: {}".format(i, j)) Do you understand how that works? Bye, Andreas From breamoreboy at yahoo.co.uk Wed Nov 27 19:48:50 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 27 Nov 2013 18:48:50 +0000 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: <20131127011845.GG4637@keks.naturalnet.de> References: <20131127005737.GF4637@keks.naturalnet.de> <20131127011845.GG4637@keks.naturalnet.de> Message-ID: On 27/11/2013 01:18, Dominik George wrote: >>> for x in xrange(len(animal)): >>> if animal[x].isdigit(): >>> animal[x] = int(animal[x]) >>> >> >> Before posting anything else would you please do a tutorial >> yourself. The above for loop is appalling newbie code, I'll leave >> you to post the Pythonic format. > > Can I trust my ears? Did you just make a move to expell me from posting > newbie-readable code on a newbie-list :D? > > Believe me, I do not need a tutorial. Seriously not. Just in case you > missed it, the pythonic code is a few lines above in my post. > > If that is not enough for you, start a private Python helpdesk with all > your glory and remove me from the list. > > And in the future, please refrain from carpeting me on a public mailing > list. > > Thanks! > Dominik, I'm very sorry about the above, I really should know better than to post at stupid o'clock in the morning when I'm already exhausted. -- Python is the second best programming language in the world. But the best has yet to be invented. Christian Tismer Mark Lawrence From nik at naturalnet.de Wed Nov 27 19:52:22 2013 From: nik at naturalnet.de (Dominik George) Date: Wed, 27 Nov 2013 19:52:22 +0100 Subject: [Tutor] Splitting lists with strings and integers In-Reply-To: References: <20131127005737.GF4637@keks.naturalnet.de> <20131127011845.GG4637@keks.naturalnet.de> Message-ID: Mark Lawrence schrieb: >Dominik, > >I'm very sorry about the above, I really should know better than to >post >at stupid o'clock in the morning when I'm already exhausted. Thanks, Mark :)! -nik From davea at davea.name Wed Nov 27 22:33:01 2013 From: davea at davea.name (Dave Angel) Date: Wed, 27 Nov 2013 16:33:01 -0500 Subject: [Tutor] Nested for loops In-Reply-To: References: Message-ID: On Wed, 27 Nov 2013 17:08:11 +0100, Rafael Knuth wrote: > for x in range(2, n): > if n % x == 0: > print(n, 'equals', x, '*', n//x) > #3 Round: > n = 4 > x = 3 When n is 4, the inner loop will test 2, then 3. But since n% x is zero for values 4 and 2, it will print, then break. Because of the break, it won't even get to 3. -- DaveA From __peter__ at web.de Wed Nov 27 23:08:12 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Nov 2013 23:08:12 +0100 Subject: [Tutor] Issue w/ string input "for", "not", "while", "else" etc. References: <20131127105400.GR2085@ando> Message-ID: Steven D'Aprano wrote: > On Wed, Nov 27, 2013 at 09:45:20AM +0100, Peter Otten wrote: > >> I took the freedom to report it myself: >> >> http://bugs.python.org/issue19808 > > Thanks for reporting the issue! > > > [off-topic] > > You might like to know that the standard English idiom is "I took the > liberty" rather than "freedom". It must sound really odd to an English ear, as I got another off-list correction ;) My Bad English is beyond the point where I naively translate German expressions, though, so I have either seen it in the text of another speaker of Bad English, or misremembered the correct phrase. > In general, liberty is a synonym for freedom. We might fight for liberty > from oppression or freedom from hunger. However, the phrases "to take > the liberty" and "to take liberties" are a little different. Both carry > connotations of going a bit too far, both are very old-fashioned, with > the flavour of Victorian England, or perhaps as late as the 1920s. > > To take liberties is (potentially) a criticism, typically spoken by a > women to a man who has been a little too enthusiastic about making > romantic advances. The image it often brings to the mind of English > speakers is of a very prim and proper young women mildly chastising a > young gentleman for being too forward with his romantic overtures (but > often with a twinkle in her eye, as if to say they're not completely > unwelcome). > > Alternatively, the words may be said by an elderly matron, severely > chastising a young gentleman who has been a bit too keen on the matron's > daughter or niece (definitely NOT with a twinkle in the eye!), or > perhaps to a servant for talking back, relaxing, or otherwise not > obeying her every whim. > > To take *the* liberty is less negative and more a self-deprecating > acknowledgement that the speaker has stepped out of bounds and taken on > more responsibility than he should have, but has done so from the best > of motives. (Sometimes spoken seriously, these days more often > ironically.) That's the meaning I was aiming to convey. > The image it brings to mind is of an exceedingly polite, > very proper, and hyper-competent butler or valet: > > "Sir has an appointment with the bank this morning. I have taken the > liberty of laying out Sir's best trousers and tweed jacket." > > Think of Jeeves: http://en.wikipedia.org/wiki/Jeeves > > > Personally, I love both phrases :-) > > Does German have anything similar? (I presume you are German.) [I kept my .de email address because I don't like the idea that we're all from planet google ;)] In German liberty and freedom are both covered by "Freiheit" (I presume that's how it would be in English were it not for the Normans). For example "Freiheitsstatue" is "Statue of Liberty" whereas "Schadstofffreiheit" indicates that something contains no poisonous substances. We also have sich die Freiheit nehmen - to take the liberty sich Freiheiten (heraus)nehmen - to take liberties with roughly the same meanings as the English counterparts. A woman might say Was nehmen sie sich heraus? to a "too enthusiastic" male, without an explicit "Freiheit", but most likely in a stuffy comedy or light opera. From arnaud.legout at inria.fr Wed Nov 27 16:04:15 2013 From: arnaud.legout at inria.fr (Arnaud Legout) Date: Wed, 27 Nov 2013 16:04:15 +0100 Subject: [Tutor] Python scope and variable binding Message-ID: <529609EF.3030109@inria.fr> Hi, I have some experience on Python programming, but I have hard time to understand to full variable and attribute lookup in Python in corner cases. This mail will be a bit long with many examples, but I hope it will help me and others to better grasp the full story of variables and attribute lookup in the Python 2.7 branch. I am using the terms of PEP 227 (http://www.python.org/dev/peps/pep-0227/) for code blocks (such as modules, class definition, function definitions, etc.) and variable bindings (such as assignments, argument declarations, class and function declaration, for loops, etc.) I am using the terms variables for names that can be called without a dot, and attributes for names that need to be qualified with an object name (such as obj.x for the attribute x of object obj). There are three scopes in Python for all code blocks, but the functions: -local -global -builtin There are four blocks in Python for the functions only (according to PEP 227): -local -enclosing functions -global -builtin The rule for a variable to bind it to and find it in a block is quite simple: -any binding of a variable to an object in a block makes this variable local to this block, unless the variable is declared global (in that case the variable belongs to the global scope) -a reference to a variable is looked up using the rule LGB (local, global, builtin) for all blocks, but the functions -a reference to a variable is looked up using the rule LEGB (local, enclosing, global, builtin) for the functions only. Let me know take examples validating this rule, and showing many special cases. For each example, I will give my understanding. Please correct me if I am wrong. For the last example, I don't understand the outcome. example 1: x = "x in module" class A(): print "A: " + x #x in module x = "x in class A" print locals() class B(): print "B: " + x #x in module x = "x in class B" print locals() def f(self): print "f: " + x #x in module self.x = "self.x in f" print x, self.x print locals() >>>A.B().f() A: x in module {'x': 'x in class A', '__module__': '__main__'} B: x in module {'x': 'x in class B', '__module__': '__main__'} f: x in module x in module self.x in f {'self': <__main__.B instance at 0x00000000026FC9C8>} There is no nested scope for the classes (rule LGB) and a function in a class cannot access the attributes of the class without using a qualified name (self.x in this example). This is well described in PEP227. example 2: z = "z in module" def f(): z = "z in f()" class C(): z = "z in C" def g(self): print z print C.z C().g() f() >>> z in f() z in C Here variables in functions are looked up using the LEGB rule, but if a class is in the path, the class arguments are skipped. Here again, this is what PEP 227 is explaining. example 3: var = 0 def func(): print var var = 1 >>> func() Traceback (most recent call last): File "", line 1, in func() File "C:/Users/aa/Desktop/test2.py", line 25, in func print var UnboundLocalError: local variable 'var' referenced before assignment We expect with a dynamic language such as python that everything is resolved dynamically. But this is not the case for functions. Local variables are determined at compile time. PEP 227 and http://docs.python.org/2.7/reference/executionmodel.html describe this behavior this way "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." example 4: x = "x in module" class A(): print "A: " + x x = "x in A" print "A: " + x print locals() del x print locals() print "A: " + x >>> A: x in module A: x in A {'x': 'x in A', '__module__': '__main__'} {'__module__': '__main__'} A: x in module But we see here that this statement in PEP227 "If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block." is wrong when the code block is a class. Moreover, for classes, it seems that local name binding is not made at compile time, but during execution using the class namespace in __dict__. In that respect, PEP227 and the execution model in the Python doc is misleading and for some parts wrong. example 5: x = 'x in module' def f2(): x = 'x in f2' def myfunc(): x = 'x in myfunc' class MyClass(object): x = x print x return MyClass myfunc() f2() >>> x in module my understanding of this code is the following. The instruction x = x first look up the object the right hand x of the expression is referring to. In that case, the object is looked up locally in the class, then following the rule LGB it is looked up in the global scope, which is the string 'x in module'. Then a local attribute x to MyClass is created in the class dictionary and pointed to the string object. example 6: Now here is an example I cannot explain. It is very close to example 5, I am just changing the local MyClass attribute from x to y. x = 'x in module' def f2(): x = 'x in f2' def myfunc(): x = 'x in myfunc' class MyClass(object): y = x print y return MyClass myfunc() f2() >>> x in myfunc Why in that case the x reference in MyClass is looked up in the innermost function? Best, Arnaud. From denis.spir at gmail.com Wed Nov 27 22:20:03 2013 From: denis.spir at gmail.com (spir) Date: Wed, 27 Nov 2013 22:20:03 +0100 Subject: [Tutor] string codes In-Reply-To: <20131126115926.GI2085@ando> References: <529467B2.3080500@gmail.com> <20131126115926.GI2085@ando> Message-ID: <52966203.8080200@gmail.com> On 11/26/2013 12:59 PM, Steven D'Aprano wrote: > On Tue, Nov 26, 2013 at 10:01:14AM +0000, Alan Gauld wrote: > >>> Is there a method to compare a substring, without building a substring >> >from the big one? Like startswith or endswith, but anywhere inside the >>> string? >>> test = s[1, -1] == "bcd" # no!, builds a substring >> >> I assume you mean test = s[1:-1] == "bcd" >> >>> test = s.sub_is(1, -1, "bcd") # yes! what I'm searching >> >> You can use startswith() (or endswith) by providing the optional >> start and end arguments: >> >> test = s.startswith("bcd", 1, -1) > > That doesn't work, unfortunately: > > py> s = "abcdZZZZZZZ" > py> s[1:-1] == "bcd" > False > py> s.startswith("bcd", 1, -1) > True > > > Oops. > > You'd have to do both startswith() and endswith() tests, and even then > it doesn't work: > > py> s = "abcdZZZZZZZZabcde" > py> s[1:-1] == "bcd" > False > py> s.startswith("bcd", 1, -1) and s.endswith("bcd", 1, -1) > True Hum, I don't understand the reasoning, here. * First, why use the end-index param? (Here in this case, or in any other)? It contradicts the idea of starting with in my view, but also is useless for sub-equality checking. * Second, imagining we'd like to use it anyway, shouldn't it be adjusted according to the lenth of the checked substring? In other words, why do you use '-1'? All in all, startswith plus start-index only seems to work fine, I guess. What is wrong? string.find also works (someone suggested it on the python-ideas mailing list) but requires both start- and end- indexes. Also, startswith returns true/false, which is more adequate conceptually for a checking instruction. spir at ospir:~$ python3 Python 3.3.1 (default, Sep 25 2013, 19:29:01) [GCC 4.7.3] on linux Type "help", "copyright", "credits" or "license" for more information. >>> s = "abcde" >>> s.startswith("bcd", 1) True >>> s.find("bcd", 1, 4) 1 >>> s = "abcdefghi" >>> s.startswith("bcd", 1) True >>> s.startswith("bcd", 2) False >>> s = "fghiabcde" >>> s.startswith("bcd", 5) True >>> s.startswith("bcd", 1) False >>> s.startswith("bcd", 9) False I really want to know if I'm missing an obvious logical point, here; else, I will stupidly use startswith, which seems to do the job, and this w/o unduly creating unneeded string objects. Denis From rudaguerman at gmail.com Wed Nov 27 19:22:13 2013 From: rudaguerman at gmail.com (Ruben Guerrero) Date: Wed, 27 Nov 2013 13:22:13 -0500 Subject: [Tutor] building table from textfile Message-ID: Dear tutor. I am trying to build the matrix and get some other information from the following text files: file1: -O- 1 2 3 4 5 6 1 C 6.617775 -0.405794 0.371689 -0.212231 0.064402 0.064402 2 C -0.405794 6.617775 -0.212231 0.371689 -0.010799 -0.010799 3 C 0.371689 -0.212231 4.887381 -0.005309 0.263318 0.263318 4 C -0.212231 0.371689 -0.005309 4.887381 -0.005500 -0.005500 5 H 0.064402 -0.010799 0.263318 -0.005500 0.697750 -0.062986 6 H 0.064402 -0.010799 0.263318 -0.005500 -0.062986 0.697750 7 H 0.064402 -0.010799 0.263318 -0.005500 -0.062986 -0.062986 8 H -0.010799 0.064402 -0.005500 0.263318 0.003816 -0.001380 9 H -0.010799 0.064402 -0.005500 0.263318 -0.001380 -0.001380 10 H -0.010799 0.064402 -0.005500 0.263318 -0.001380 0.003816 7 8 9 10 1 C 0.064402 -0.010799 -0.010799 -0.010799 2 C -0.010799 0.064402 0.064402 0.064402 3 C 0.263318 -0.005500 -0.005500 -0.005500 4 C -0.005500 0.263318 0.263318 0.263318 5 H -0.062986 0.003816 -0.001380 -0.001380 6 H -0.062986 -0.001380 -0.001380 0.003816 7 H 0.697750 -0.001380 0.003816 -0.001380 8 H -0.001380 0.697750 -0.062986 -0.062986 9 H 0.003816 -0.062986 0.697750 -0.062986 10 H -0.001380 -0.062986 -0.062986 0.697750 file 2: -O- 1 2 3 4 5 1 C 5.898497 0.292009 0.177195 0.177195 0.177195 2 H 0.292009 0.686184 -0.099114 -0.099114 -0.099114 3 Cl 0.177195 -0.099114 17.045753 -0.129074 -0.129074 4 Cl 0.177195 -0.099114 -0.129074 17.045753 -0.129074 5 Cl 0.177195 -0.099114 -0.129074 -0.129074 17.045753 using the following script: #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import subprocess import numpy as np import time import signal nombreInput=sys.argv[1] inputFile = open (nombreInput,"r") inputFileRead = inputFile.readlines() out = open (nombreInput+".out","w") mu = 0 nu = 0 countAtom = { 'H': 0, 'Li': 0, 'C': 0, 'N': 0, 'O': 0, 'F': 0, 'Na': 0, 'Si': 0, 'P': 0, 'S': 0, 'Cl': 0, } electrons = { 'H': 1, 'Li': 3, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'Na': 11, 'Si': 14, 'P': 15, 'S': 16, 'Cl': 17, } numberOfLines = len(inputFileRead) maxNumberOfOrbitals = 0 # Contar el numero de orbitales for iline in range(0,numberOfLines) : inputFileRead[iline] = inputFileRead[iline].replace("\n","") # Quitar los saltos de linea # print (inputFileRead[iline]) if ( len(inputFileRead[iline].split()) == 6+2 ) : numberOfOrbital = int(inputFileRead[iline].split()[0]) if ( numberOfOrbital > maxNumberOfOrbitals ) : maxNumberOfOrbitals = numberOfOrbital # Contar los atomos for k in range(0,maxNumberOfOrbitals) : atom = inputFileRead[k+2].split()[1] countAtom[atom] = countAtom[atom] + 1 # Imprimir la formula quimica for k in countAtom : if ( countAtom[k] > 0) : out.write( k+"_{"+str(countAtom[k])+"}" ) out.write("\n") # Imprimir el numero de electrones numberOfElectrons = 0 for k in countAtom : numberOfElectrons = numberOfElectrons + electrons[k]*countAtom[k] out.write (str(numberOfElectrons) + "\n") # Imprimir el numero de filas out.write (str(maxNumberOfOrbitals) + "\n") # Armar la matriz matrix = np.zeros((maxNumberOfOrbitals,maxNumberOfOrbitals),dtype=float) i = 0 m = 0 for l in range(0,numberOfLines) : if ( len(inputFileRead[l].split()) == 6+2 ) : for j in range(0,6) : matrix[i][j+6*m] = float (inputFileRead[l].split()[j+2]) if ( i + 1 == maxNumberOfOrbitals) : i = 0 m = m + 1 else: i = i + 1 elif ( len(inputFileRead[l].split()) == maxNumberOfOrbitals%6+2 ) : for j in range(0,maxNumberOfOrbitals%6) : matrix[i][j+6*m] = float (inputFileRead[l].split()[j+2]) i = i + 1 else : i = 0 # Imprimir la matriz for i in range(0,maxNumberOfOrbitals) : for j in range(0,maxNumberOfOrbitals) : out.write ("%.6f"%matrix[i][j]+" ") out.write("\n") #::::::::::::::::::::::::::::::::::: # Cerrando los archivos #::::::::::::::::::::::::::::::::::: inputFile.close() out.close() but when I run teh script on file 1 I get the error: Traceback (most recent call last): File "get_matrix.py", line 88, in matrix[i][j+6*m] = float (inputFileRead[l].split()[j+2]) IndexError: index 10 is out of bounds for axis 0 with size 10 And with file 2 I don't get errors but the information in the matrix in not in the file. so where is the error? Thanks in advance, -Ruben. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vipul.sharma20 at gmail.com Wed Nov 27 20:13:17 2013 From: vipul.sharma20 at gmail.com (Vipul Sharma) Date: Thu, 28 Nov 2013 00:43:17 +0530 Subject: [Tutor] pygame error Message-ID: Hello ! I am a beginner in pygame, i was just trying a simple pygame program where I wanted to load an image (.png) from the same directory where my actual source code was. I wrote this line in my source code to load the image : Img = pygame.image.load('cat.png') But I got a traceback : pygame.error: File is not a Windows BMP file Can anyone pls tell what is the problem with the code, why this error arises ? I am using python 2.7.4 on Ubuntu Thanks for the help in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Nov 28 02:12:36 2013 From: wprins at gmail.com (Walter Prins) Date: Thu, 28 Nov 2013 01:12:36 +0000 Subject: [Tutor] string codes In-Reply-To: <52966203.8080200@gmail.com> References: <529467B2.3080500@gmail.com> <20131126115926.GI2085@ando> <52966203.8080200@gmail.com> Message-ID: Hi, On 27 November 2013 21:20, spir wrote: > All in all, startswith plus start-index only seems to work fine, I guess. > What is wrong? string.find also works (someone suggested it on the > python-ideas mailing list) but requires both start- and end- indexes. Also, > startswith returns true/false, which is more adequate conceptually for a > checking instruction. > Sorry to wade in after all the other answers you've had, but a) string.find() does not *require* start and end indexes, they are optional: http://docs.python.org/2/library/string.html And b) if you're just trying to find out whether a substring exists in a string (which I'm getting the impression you're all you're doing), you can use "in": Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 1.0.0 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. walter-desktop[c:\users\walterp\src]|1> s = "abcdefghi" walter-desktop[c:\users\walterp\src]|2> 'bcd' in s <2> True walter-desktop[c:\users\walterp\src]|3> 'fgh' in s <3> True walter-desktop[c:\users\walterp\src]|4> 'iab' in s <4> False walter-desktop[c:\users\walterp\src]|5> s.find('bcd') <5> 1 walter-desktop[c:\users\walterp\src]|6> s.find('fghi') <6> 5 walter-desktop[c:\users\walterp\src]|7> Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 28 02:34:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Nov 2013 01:34:28 +0000 Subject: [Tutor] string codes In-Reply-To: <52966203.8080200@gmail.com> References: <529467B2.3080500@gmail.com> <20131126115926.GI2085@ando> <52966203.8080200@gmail.com> Message-ID: On 27/11/13 21:20, spir wrote: >> py> s.startswith("bcd", 1, -1) and s.endswith("bcd", 1, -1) >> True > > Hum, I don't understand the reasoning, here. > * First, why use the end-index param? (Here in this case, or in any > other)? It contradicts the idea of starting with in my view, but also is > useless for sub-equality checking. Not so. If you are looking for a string and know the string ends with that string you want the end point to exclude the known result at the end. And it is a startswith because you are checking from the start of the substring. One use case would be in checking a list of filenames that have a fixed format. For example I usually name my files with a common tag followed by a number followed by the type CuteKitten0001.jpg to CuteKitten0130.jpg Now I can use a startswith() start point of len('CuteKitten') to find the files in the range 0010-0019. Or if a braindead program always adds a file extension and I've mistakenly specified one so that some files are like filename.txt.txt I can search for endswith '.txt' but omit the last .txt which all(or many) files will have. I'm sure there are other cases, and I agree there are other ways to achieve the same end, but the start,end indexes are useful on occasion. Having said that I've only ever used the start index in practice. But its nice to have an option. > * Second, imagining we'd like to use it anyway, shouldn't it be adjusted > according to the lenth of the checked substring? In other words, why do > you use '-1'? To access the last character. It could be say -3 or -4 in the filename examples above. The reason I used it was that it was what you used in your original post... > All in all, startswith plus start-index only seems to work fine, I > guess. What is wrong? string.find also works (someone suggested it on > the python-ideas mailing list) but requires both start- and end- > indexes. Also, startswith returns true/false, which is more adequate > conceptually for a checking instruction. Yes, it depends on whether you are after a predicate or a search result. find() is for locating a substring in a string. 'in' is the preferred predicate for general testing. startswith/endswith are for the special cases where you know which end the string will be and (presumably!) are optimised for those cases. >>>> s = "abcde" >>>> s.startswith("bcd", 1) > True >>>> s.find("bcd", 1, 4) > 1 >>>> s = "abcdefghi" >>>> s.startswith("bcd", 1) > True >>>> s.startswith("bcd", 2) > False You missed the cases using end index: >>> s.startswith('bcd',2,4) False >>> s.startswith('bcd',2,5) True If you have a fixed record size string then testing against only the specific substring may be important. > I really want to know if I'm missing an obvious logical point, here; > else, I will stupidly use startswith, which seems to do the job, and > this w/o unduly creating unneeded string objects. Again I'd suggest you are over stressing this temporary string thing. testing against a slice is the easiest (and most flexible) way and really is not much of an overhead. And if you just want to know if a substring exists use 'in'. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Nov 28 02:39:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Nov 2013 01:39:20 +0000 Subject: [Tutor] pygame error In-Reply-To: References: Message-ID: On 27/11/13 19:13, Vipul Sharma wrote: > Hello ! I am a beginner in pygame, i was just trying a simple pygame > program where I wanted to load an image (.png) from the same directory > where my actual source code was. > I wrote this line in my source code to load the image : > > Img = pygame.image.load('cat.png') > > But I got a traceback : > > pygame.error: File is not a Windows BMP file I don't know Pygame but it looks like it expects a bitmap image type as an argument. But try the Pygame mailing list for more expert advice. BTW when posting error messages it really helps if you post the complete error traceback not just the last line. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From alan.gauld at btinternet.com Thu Nov 28 02:55:17 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Nov 2013 01:55:17 +0000 Subject: [Tutor] building table from textfile In-Reply-To: References: Message-ID: On 27/11/13 18:22, Ruben Guerrero wrote: > Dear tutor. > > I am trying to build the matrix and get some other information from the > following text files: > > file1: > -O- > 1 2 3 4 5 6 > 1 C 6.617775 -0.405794 0.371689 -0.212231 0.064402 > 0.064402 > 2 C -0.405794 6.617775 -0.212231 0.371689 -0.010799 > -0.010799 > 3 C 0.371689 -0.212231 4.887381 -0.005309 0.263318 > 0.263318 > 4 C -0.212231 0.371689 -0.005309 4.887381 -0.005500 > -0.005500 > 7 8 9 10 > 1 C 0.064402 -0.010799 -0.010799 -0.010799 > 2 C -0.010799 0.064402 0.064402 0.064402 > 3 C 0.263318 -0.005500 -0.005500 -0.005500 > 4 C -0.005500 0.263318 0.263318 0.263318 > > file 2: > -O- > 1 2 3 4 5 > 1 C 5.898497 0.292009 0.177195 0.177195 0.177195 > 2 H 0.292009 0.686184 -0.099114 -0.099114 -0.099114 > 3 Cl 0.177195 -0.099114 17.045753 -0.129074 -0.129074 > 4 Cl 0.177195 -0.099114 -0.129074 17.045753 -0.129074 > > using the following script: > > nombreInput=sys.argv[1] > > inputFile = open (nombreInput,"r") > inputFileRead = inputFile.readlines() > out = open (nombreInput+".out","w") > > > mu = 0 > nu = 0 > > countAtom = { ... > } > electrons = { ... > } > > numberOfLines = len(inputFileRead) > > maxNumberOfOrbitals = 0 > > # Contar el numero de orbitales > for iline in range(0,numberOfLines) : > inputFileRead[iline] = inputFileRead[iline].replace("\n","") You could do this more simply using for line in inputFile: line = line.rstrip() > if ( len(inputFileRead[iline].split()) == 6+2 ) : > numberOfOrbital = int(inputFileRead[iline].split()[0]) And this becomes line = line.split() if len(line) == 8: # 8 = 6+2 no point in extra math numberOfOrbital = int(line[0]) > if ( numberOfOrbital > maxNumberOfOrbitals ) : > maxNumberOfOrbitals = numberOfOrbital > # Contar los atomos > > for k in range(0,maxNumberOfOrbitals) : > atom = inputFileRead[k+2].split()[1] This assumes you have 2 more lines than there are maxNumberofOrbitals. I didn't check, but is it true? Also it would be more efficient to store the split line in the first loop above. I didn't go through the rest in detail but I suspect the +2 thing may be to do with your error message: > elif ( len(inputFileRead[l].split()) == maxNumberOfOrbitals%6+2 ) : > for j in range(0,maxNumberOfOrbitals%6) : > matrix[i][j+6*m] = float (inputFileRead[l].split()[j+2]) Notice the j+2 at the end? Could that be the cause? Or what about the j+6*m? I don't know where m is defined but could it be busting your index? > Traceback (most recent call last): > File "get_matrix.py", line 88, in > matrix[i][j+6*m] = float (inputFileRead[l].split()[j+2]) > IndexError: index 10 is out of bounds for axis 0 with size 10 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From oscar.j.benjamin at gmail.com Thu Nov 28 11:32:10 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 28 Nov 2013 10:32:10 +0000 Subject: [Tutor] building table from textfile In-Reply-To: References: Message-ID: On 27 November 2013 18:22, Ruben Guerrero wrote: > Dear tutor. > > I am trying to build the matrix and get some other information from the > following text files: > > file1: > -O- > 1 2 3 4 5 6 > 1 C 6.617775 -0.405794 0.371689 -0.212231 0.064402 0.064402 > 2 C -0.405794 6.617775 -0.212231 0.371689 -0.010799 -0.010799 > 3 C 0.371689 -0.212231 4.887381 -0.005309 0.263318 0.263318 > 4 C -0.212231 0.371689 -0.005309 4.887381 -0.005500 -0.005500 > 5 H 0.064402 -0.010799 0.263318 -0.005500 0.697750 -0.062986 > 6 H 0.064402 -0.010799 0.263318 -0.005500 -0.062986 0.697750 > 7 H 0.064402 -0.010799 0.263318 -0.005500 -0.062986 -0.062986 > 8 H -0.010799 0.064402 -0.005500 0.263318 0.003816 -0.001380 > 9 H -0.010799 0.064402 -0.005500 0.263318 -0.001380 -0.001380 > 10 H -0.010799 0.064402 -0.005500 0.263318 -0.001380 0.003816 > 7 8 9 10 > 1 C 0.064402 -0.010799 -0.010799 -0.010799 > 2 C -0.010799 0.064402 0.064402 0.064402 > 3 C 0.263318 -0.005500 -0.005500 -0.005500 > 4 C -0.005500 0.263318 0.263318 0.263318 > 5 H -0.062986 0.003816 -0.001380 -0.001380 > 6 H -0.062986 -0.001380 -0.001380 0.003816 > 7 H 0.697750 -0.001380 0.003816 -0.001380 > 8 H -0.001380 0.697750 -0.062986 -0.062986 > 9 H 0.003816 -0.062986 0.697750 -0.062986 > 10 H -0.001380 -0.062986 -0.062986 0.697750 I'm not sure what the problem with your code is but your method for parsing the file is generally fragile. You should write a function that parses the file and puts all the data into a convenient format first *before* you do any processing with the data. I've written a more robust parsing function for you: #!/usr/bin/env python import sys import numpy as np def read_file(inputfile): atomnames = [] matrix = [] rows = [] nextcol = 1 for n, line in enumerate(inputfile): lineno = '%s %r' % (n, line) words = line.split() # Skip this line at the beginning if words == ['-0-']: continue # Either this line is column numbers # or it is a row. If it is a row then # the atom name is the second element. if words[1].isdigit(): # Column numbers, check them for consistency expected = range(nextcol, nextcol+len(words)) expected = [str(e) for e in expected] assert words == expected, lineno nextcol += len(words) elif words[1].isalpha(): # A row index, atom, numbers = words[0], words[1], words[2:] index = int(index) - 1 numbers = [float(s) for s in numbers] if index < len(atomnames): # We've already seen this index assert atomnames[index] == atom matrix[index].extend(numbers) elif index == len(atomnames): # First time we see the index atomnames.append(atom) matrix.append(numbers) else: assert False, lineno else: # Not a column or a row assert False, lineno matrix = np.array(matrix, float) return atomnames, matrix filename = sys.argv[1] with open(filename, 'r') as fin: atomnames, matrix = read_file(fin) print(atomnames) print(matrix) With that you should find it easier to implement the rest of the script. Oscar From denis.spir at gmail.com Thu Nov 28 13:52:29 2013 From: denis.spir at gmail.com (spir) Date: Thu, 28 Nov 2013 13:52:29 +0100 Subject: [Tutor] string codes In-Reply-To: References: <529467B2.3080500@gmail.com> <20131126115926.GI2085@ando> <52966203.8080200@gmail.com> Message-ID: <52973C8D.5000705@gmail.com> On 11/28/2013 02:12 AM, Walter Prins wrote: > Sorry to wade in after all the other answers you've had, but a) > string.find() does not *require* start and end indexes, they are optional: > http://docs.python.org/2/library/string.html And b) if you're just trying > to find out whether a substring exists in a string (which I'm getting the > impression you're all you're doing), you can use "in": It's about parsing: I'm not trying to find whether it is _anywhere_ in source, but _there_ at the present index. Thank you, anyway. denis From denis.spir at gmail.com Thu Nov 28 14:10:39 2013 From: denis.spir at gmail.com (spir) Date: Thu, 28 Nov 2013 14:10:39 +0100 Subject: [Tutor] string codes In-Reply-To: References: <529467B2.3080500@gmail.com> <20131126115926.GI2085@ando> <52966203.8080200@gmail.com> Message-ID: <529740CF.3000306@gmail.com> On 11/28/2013 02:34 AM, Alan Gauld wrote: > Not so. If you are looking for a string and know the string ends with that > string you want the end point to exclude the known result at the end. And it is > a startswith because you are checking from the > start of the substring. Ah, thank you, Alan! Denis From rafael.knuth at gmail.com Thu Nov 28 17:04:58 2013 From: rafael.knuth at gmail.com (Rafael Knuth) Date: Thu, 28 Nov 2013 17:04:58 +0100 Subject: [Tutor] Nested for loops In-Reply-To: <20131127173813.38ded403@Hof> References: <20131127173813.38ded403@Hof> Message-ID: > Do you understand how that works? Yep. It's crystal clear now. Thank you. It took a while till I got it, though ;-) From sunithanc at gmail.com Thu Nov 28 20:12:18 2013 From: sunithanc at gmail.com (SM) Date: Thu, 28 Nov 2013 14:12:18 -0500 Subject: [Tutor] Pretty printing XML using LXML on Python3 Message-ID: Hello, I am using lxml with Python3, to generate xml code. "pretty_print" doesn't seem to indent the generated lines. I have installed the following lxml package: /usr/local/lib/python3.2/dist-packages/lxml-3.2.4-py3.2-linux-x86_64.egg/lxml The following is the example code I found on stack overflow, which runs fine on Python2.7. But it concatenates all the lines if I run the same code with Python3. Does anybody know what is the solution to make it work on Python3? from lxml import etree # create XML root = etree.Element('root') root.append(etree.Element('child')) # another child with text child = etree.Element('child') child.text = 'some text' root.append(child) # pretty string s = etree.tostring(root, pretty_print=True) print(s) Run with Python: $ python testx.py some text $ Run with Python3: $ python3 testx.py b'\n \n some text\n\n' $ Thanks in advance. -SM -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Nov 28 20:45:59 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 28 Nov 2013 14:45:59 -0500 Subject: [Tutor] Pretty printing XML using LXML on Python3 In-Reply-To: References: Message-ID: On Thu, Nov 28, 2013 at 2:12 PM, SM wrote: > Run with Python3: > > $ python3 testx.py > b'\n \n some text\n\n' print() first gets the object as a string. tostring() returns bytes, and bytes.__str__ returns the same as bytes.__repr__. You can decode the bytes before printing, or instead use tounicode(): >>> s = etree.tounicode(root, pretty_print=True) >>> print(s) some text From steve at pearwood.info Fri Nov 29 00:45:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 29 Nov 2013 10:45:34 +1100 Subject: [Tutor] string codes In-Reply-To: <52966203.8080200@gmail.com> References: <529467B2.3080500@gmail.com> <20131126115926.GI2085@ando> <52966203.8080200@gmail.com> Message-ID: <20131128234533.GX2085@ando> On Wed, Nov 27, 2013 at 10:20:03PM +0100, spir wrote: > On 11/26/2013 12:59 PM, Steven D'Aprano wrote: > >On Tue, Nov 26, 2013 at 10:01:14AM +0000, Alan Gauld wrote: > > > >>>Is there a method to compare a substring, without building a substring > >>>from the big one? Like startswith or endswith, but anywhere inside the > >>>string? > >>> test = s[1, -1] == "bcd" # no!, builds a substring > >> > >>I assume you mean test = s[1:-1] == "bcd" > Hum, I don't understand the reasoning, here. > * First, why use the end-index param? (Here in this case, or in any other)? Because it matches the example you gave. You showed an example of slicing a string from the second to the second last position, s[1:-1]. That corresponds to start=1 and end=-1. > It contradicts the idea of starting with in my view, but also is useless > for sub-equality checking. Well I wouldn't say that startswith() is *useless* for checking substrings, but it is tricky to get all the arguments right. > * Second, imagining we'd like to use it anyway, shouldn't it be adjusted > according to the lenth of the checked substring? In other words, why do you > use '-1'? Because I copied your example. Your example showed: -- Take the string s, and look only at the substring starting at position 1 and going to position -1, does it equal "bcd"? So I did exactly the same thing. > All in all, startswith plus start-index only seems to work fine, I guess. > What is wrong? It's not *wrong*, it's a *different question*. Question 1: Does the substring between position i and j *equal* this string? Question 2: Does the substring between position i and j *start with* this string? You started by asking Question 1, solutions using startswith answer Question 2. The two questions are only equivalent if the length of the shorter string is exactly equal to the length of the substring. -- Steven From eryksun at gmail.com Fri Nov 29 06:20:52 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 29 Nov 2013 00:20:52 -0500 Subject: [Tutor] Python scope and variable binding In-Reply-To: <529609EF.3030109@inria.fr> References: <529609EF.3030109@inria.fr> Message-ID: On Wed, Nov 27, 2013 at 10:04 AM, Arnaud Legout wrote: > > example 4: > > x = "x in module" > class A(): > print "A: " + x > x = "x in A" > print "A: " + x > print locals() > del x > print locals() > print "A: " + x >>>> > A: x in module > A: x in A > {'x': 'x in A', '__module__': '__main__'} > {'__module__': '__main__'} > A: x in module > > But we see here that this statement in PEP227 "If a name binding > operation occurs anywhere within a code block, all uses of the name > within the block are treated as references to the current block." is > wrong when the code block is a class. Moreover, for classes, it seems > that local name binding is not made at compile time, but during > execution using the class namespace in __dict__. In that respect, > PEP227 and the execution model in the Python doc is misleading and for > some parts wrong. In a module or class, even if a name is local, loading still falls back on globals and builtins. So a local name can temporarily shadow a name from globals or builtins, and once deleted the original is available again. That can't be done in function code that uses fast locals. Loading a fast local doesn't fall back to globals and builtins. For example, this initial assignment will fail: int = int. You might instead use int_ = int, or a default argument. PEP 227 is concerned with nested scopes that support lexical closures. The implementation associates a name with a cell object that can be shared across scopes. CPython bytecode operations: LOAD_NAME - locals, globals, builtins STORE_NAME - locals LOAD_FAST, STORE_FAST - fast locals array LOAD_DEREF, STORE_DEREF - local cellvar, nonlocal freevar LOAD_GLOBAL - globals, builtins STORE_GLOBAL - globals In the following example, dtype is a free variable in g and a cell variable in f. def f(dtype): def g(x): return dtype(x) return g g_int = f(int) >>> f.__code__.co_cellvars ('dtype',) >>> g_int.__code__.co_freevars ('dtype',) >>> type(g_int.__closure__[0]) >>> g_int.__closure__[0].cell_contents >>> dis.dis(g_int) 3 0 LOAD_DEREF 0 (dtype) 3 LOAD_FAST 0 (x) 6 CALL_FUNCTION 1 9 RETURN_VALUE Versions prior to 2.6 use the function attributes func_code and func_closure instead of __code__ and __closure__. The old attribute names are still available in 2.6/2.7, but not in 3.x. 3.x adds a nonlocal statement to declare free variables. Can you infer what this enables? > example 5: > > x = 'x in module' > def f2(): > x = 'x in f2' > def myfunc(): > x = 'x in myfunc' > class MyClass(object): > x = x > print x > return MyClass > myfunc() > f2() >>>> > x in module > > my understanding of this code is the following. The instruction x = x > first look up the object the right hand x of the expression is referring > to. In that case, the object is looked up locally in the class, then > following the rule LGB it is looked up in the global scope, which is > the string 'x in module'. Then a local attribute x to MyClass is > created in the class dictionary and pointed to the string object. Regarding the last sentence, basically the locals dict from the frame that executed the class body is passed to the metaclass, which stores a copy to the new type. If you've never created a type manually by calling a metaclass, here's an example. # type(name, bases, dict) -> a new type C = type('C', (object,), {'x': 'x in C'}) >>> C.__name__ 'C' >>> C.__bases__ (,) >>> C.x 'x in C' > example 6: > Now here is an example I cannot explain. > It is very close to example 5, I am just changing the local MyClass > attribute from x to y. > > x = 'x in module' > def f2(): > x = 'x in f2' > def myfunc(): > x = 'x in myfunc' > class MyClass(object): > y = x > print y > return MyClass > myfunc() > f2() >>>> > x in myfunc > > Why in that case the x reference in MyClass is looked up in the > innermost function? You aren't assigning x in the class body, so it's a free variable there, and a cell variable in myfunc. You could just use "print x" to get the same result. Let's try something similar in 3.x but with an explicit nonlocal declaration (allowing reassignment of a free variable): def f(): x = 'x in f' print('f,1:', x) class C(object): nonlocal x print('C,1:', x) x = 'x in C' print('C,2:', x) print('f,2:', x) # reassigned in C >>> f() f,1: x in f C,1: x in f C,2: x in C f,2: x in C Now again without the nonlocal declaration: x = 'x in module' def f(): x = 'x in f' print('f,1:', x) class C(object): print('C,1:', x) x = 'x in C' print('C,2:', x) print('f,2:', x) >>> f() f,1: x in f C,1: x in module C,2: x in C f,2: x in f Without a global or nonlocal declaration, assignment implicitly makes x a local in the class body. The C,1 LOAD_NAME finds x in globals. The C,2 LOAD_NAME finds x in locals. From phil_lor at bigpond.com Fri Nov 29 04:35:49 2013 From: phil_lor at bigpond.com (Phil) Date: Fri, 29 Nov 2013 13:35:49 +1000 Subject: [Tutor] Allocation of serial ports Message-ID: <52980B95.1050905@bigpond.com> Thank you for reading this. This question is not specifically related to Python, however, someone may be able to point me in the right direction. The operating system in use is Linux. I have a twin USB to serial adaptor that gives me ttyUSB0 and ttyUSB1 and my programme uses both of those ports. The problem is the random allocation of the ports. Port A, for example, could be either ttyUSB0 or ttyUSB1. So, how can I ensure that port A is always ttyUSB0 or how can I adapt my programme so that the address of the port is known to the programme? -- Regards, Phil From nik at naturalnet.de Fri Nov 29 09:17:28 2013 From: nik at naturalnet.de (Dominik George) Date: Fri, 29 Nov 2013 09:17:28 +0100 Subject: [Tutor] Allocation of serial ports In-Reply-To: <52980B95.1050905@bigpond.com> References: <52980B95.1050905@bigpond.com> Message-ID: <7300cc41-6d1f-4697-a324-2d5662510d38@email.android.com> Hi, >So, how can I ensure that port A is always ttyUSB0 http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/ -nik From denis.spir at gmail.com Fri Nov 29 09:06:20 2013 From: denis.spir at gmail.com (spir) Date: Fri, 29 Nov 2013 09:06:20 +0100 Subject: [Tutor] Python scope and variable binding In-Reply-To: References: <529609EF.3030109@inria.fr> Message-ID: <52984AFC.6050308@gmail.com> On 11/29/2013 06:20 AM, eryksun wrote: > On Wed, Nov 27, 2013 at 10:04 AM, Arnaud Legout wrote: > [...] For what it's worth, a personal point of view on Python class defs. I ended up undertanding class definitions as code blocks the following way: Imagine Python has kinds of free sections of code (like Lua or C, and many other languages), but using "section" as keyword like so, which permits to name such sections: section Def_Write_i: i = 1 print(i) Def_Write_i is a block of code, like a func, or a branch of an 'if' statement, or a loop body. Unlike a func, it cannot be called, it is just executed on the way. I could serve to struture code (I actually would enjoy that). Now, add to this that such as section's scope (namespace) is permanent like an object (like an object's __dict__), instead of transient like function scopes: and you get classes as code blocks and namespaces. [C's function-local static vars are somewhat similar: they remain; but unlike Python's class vars they are not accessible from outside the func.] In Lua, definition of an "object-like" table is similar, but unlike for Python classes it cannot refer to itself or its own local vars, because at definition time the object (the table) does not yet exists as such: t = { i = 1, j = i+1, -- error k = t.i+1, -- error as well } To reproduce the functionality of Python classes, it should be (but is not) that the above code is equivalent to: t = {} t.i = 1 t.j = t.i+1 t.k = t.i+1 Also, there cannot be any other statement there but assignments. I used to use this weird feature of Python classes to make free, permanent, and even computable scopes. For instance, to define parsers: sets of named patterns, with higher-level ones building on lowel-level ones: class ArithParser(Parser): digit = Range("0-9") natural = String(digit) natural.test("123") ### debug ### integer = Comp(Option('-'), natural) ... In addition, one can have such free namespaces initialised and given other attributes: arith_parser = ArithParser() # init & get instance attributes defined in Parser Denis From steve at pearwood.info Fri Nov 29 09:54:38 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 29 Nov 2013 19:54:38 +1100 Subject: [Tutor] pygame error In-Reply-To: References: Message-ID: <20131129085437.GC2085@ando> On Thu, Nov 28, 2013 at 12:43:17AM +0530, Vipul Sharma wrote: > Hello ! I am a beginner in pygame, i was just trying a simple pygame > program where I wanted to load an image (.png) from the same directory > where my actual source code was. > I wrote this line in my source code to load the image : > > Img = pygame.image.load('cat.png') > > But I got a traceback : > > pygame.error: File is not a Windows BMP file > > Can anyone pls tell what is the problem with the code, why this error > arises ? Is the error message not clear enough? The file is a PNG file, not a Windows BMP file. By default, pygame only supports BMP images. If you want to use a more useful range of image types, like PNG, JPG, and so forth, you need to build pygame with image support. See here for more information: http://www.pygame.org/docs/ref/image.html -- Steven From phil_lor at bigpond.com Fri Nov 29 10:00:24 2013 From: phil_lor at bigpond.com (Phil) Date: Fri, 29 Nov 2013 19:00:24 +1000 Subject: [Tutor] Allocation of serial ports In-Reply-To: <7300cc41-6d1f-4697-a324-2d5662510d38@email.android.com> References: <52980B95.1050905@bigpond.com> <7300cc41-6d1f-4697-a324-2d5662510d38@email.android.com> Message-ID: <529857A8.2040509@bigpond.com> On 11/29/2013 06:17 PM, Dominik George wrote: > Hi, > >> So, how can I ensure that port A is always ttyUSB0 > > http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/ > Thank you Dominik, the link answers my question exactly. -- Regards, Phil From spinefxr at aol.com Fri Nov 29 20:24:49 2013 From: spinefxr at aol.com (spinefxr at aol.com) Date: Fri, 29 Nov 2013 14:24:49 -0500 (EST) Subject: [Tutor] TypeError: range() integer end argument expected, got float. Message-ID: <8D0BB4FCE8C27B1-12A0-8C029@webmail-vd007.sysops.aol.com> Hi Newbie at this. I am getting this error: TypeError: range() integer end argument expected, got float. Using python 7.3 here is my code def PaymentTable(balance, annualInterestRate, payment): month = 0 while month < 12: balance = balance - payment interest = balance * (annualInterestRate/12) balance = balance + interest month += 1 if balance <= 0: return True balance = 4773 annualInterestRate = .2 monthlyinterest = balance * (annualInterestRate/12) lowerbound = round(balance / 12, 0) upperbound = round((balance + (monthlyinterest * 12)) / 12, 0) for payment in range(lowerbound, upperbound, 10): if PaymentTable(balance, annualInterestRate, payment) == True: ####Error occurs at this line print 'Lowest Payment: ', payment break Richard Roth -------------- next part -------------- An HTML attachment was scrubbed... URL: From ugajin at talktalk.net Fri Nov 29 14:19:37 2013 From: ugajin at talktalk.net (ugajin at talktalk.net) Date: Fri, 29 Nov 2013 08:19:37 -0500 Subject: [Tutor] empty delimiters, and None Message-ID: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> I run Inkscape (an Open Source vector drawing application) on OSX (Snow leopard) installed via .dmg pkg. The application ships with a collection of Python extensions, one of which Measure Path, failed to execute. I could not find a reference for this issue in the Inkscape archives, and I tried and worked with other workarounds including a javascript (outside Inkscape) to find the length of B?zier paths, but eventually I raised the issue and contacted launchpad/inkscape (question #239599) but to limited avail. After much continued searching I then found this Bug #803791 report which describes (as an aside) the exact same issue together with a solution. I know next to nothing about Python and I shall be glad if any Python guru can make clear (in layman's terms where possible) what the problem is/was and how the fix works. I remembered an alternative posting that I had read, which reported that Python dislikes empty delimiters. So I took a slightly different approach to the one mentioned in the above bug report. Instead of removing line 35 from the Measure Path script I replaced the empty delimiters with the Python constant None. To my great delight as well as my own amazement the 'fix' worked. The problem may or may not be limited to OSX. On trying to run the script (before the fix) I had the following traceback message: File "measure.py", line 35, in locale.setlocale(locale.LC_ALL, '') File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting If I booted from the Unix file I received the following feedback: Setting Language: .UTF-8 (process:82224): Gtk-WARNING **: Locale not supported by C library. Using the fallback 'C' locale. Line 35 (above) shows the empty delimiter. The fix that I applied was to replace line 35 in the Measure.py script with: locale.setlocale(locale.LC_ALL, None). The Measure Path script then executes correctly. No other action is/was required. I note also the Python 2 library entry for Built-in Constants as: None The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Changed in version 2.4: Assignments to None are illegal and raise a SyntaxError. And under standard type hierarchy as: None This type has a single value. There is a single object with this value. This object is accessed through the built-in name None. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don?t explicitly return anything. Its truth value is false. I have run the various scripts in a Python Validator, and line 35 (both versions) pass unremarked, although there are a few other code errors and warnings and many pep8 warnings. I have also looked at locale.py Line 494 of which is the last line of a def (def function?) I include this below, hopefully this may save you searching for locale.py (Pyhon 2.6) should you need it and wish to answer the above questions, it may help. def setlocale(category, locale=None): """ Set the locale for the given category. The locale can be a string, a locale tuple (language code, encoding), or None. Locale tuples are converted to strings the locale aliasing engine. Locale strings are passed directly to the C lib. category may be given as one of the LC_* values. """ if locale and type(locale) is not type(""): # convert to string locale = normalize(_build_localename(locale)) return _setlocale(category, locale) Many, many thanks for your interest and considering matters. -A -------------- next part -------------- An HTML attachment was scrubbed... URL: From sunithanc at gmail.com Fri Nov 29 22:21:22 2013 From: sunithanc at gmail.com (SM) Date: Fri, 29 Nov 2013 16:21:22 -0500 Subject: [Tutor] Pretty printing XML using LXML on Python3 In-Reply-To: References: Message-ID: Thank you, eryksun. using tounicode seems to work on this small piece of code. It still has issues with my code which is generating a big XML code. I will figure out why. -SM On Thu, Nov 28, 2013 at 2:45 PM, eryksun wrote: > On Thu, Nov 28, 2013 at 2:12 PM, SM wrote: > > Run with Python3: > > > > $ python3 testx.py > > b'\n \n some text\n\n' > > print() first gets the object as a string. tostring() returns bytes, > and bytes.__str__ returns the same as bytes.__repr__. You can decode > the bytes before printing, or instead use tounicode(): > > >>> s = etree.tounicode(root, pretty_print=True) > >>> print(s) > > > some text > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nik at naturalnet.de Fri Nov 29 22:26:47 2013 From: nik at naturalnet.de (Dominik George) Date: Fri, 29 Nov 2013 22:26:47 +0100 Subject: [Tutor] TypeError: range() integer end argument expected, got float. In-Reply-To: <8D0BB4FCE8C27B1-12A0-8C029@webmail-vd007.sysops.aol.com> References: <8D0BB4FCE8C27B1-12A0-8C029@webmail-vd007.sysops.aol.com> Message-ID: <20131129212603.GA4689@keks.naturalnet.de> Hi, > Using python 7.3 I think we must update 'import antigravity' to say something about python-driven flux capacitors :? ... > def PaymentTable(balance, annualInterestRate, payment): You should not CamelCase function names. > upperbound = round((balance + (monthlyinterest * 12)) / 12, 0) Your error is because round() does not cast to int. It produces an integer number in a strict mathematical sense, but not as a data type. Use int() for that. > for payment in range(lowerbound, upperbound, 10): > if PaymentTable(balance, annualInterestRate, payment) == True: ####Error occurs at this line > print 'Lowest Payment: ', payment > break A few notes about that. 1. You mentioned above that you use Python 7.3. As already said, I do not know what that is, because right now there is Python 2.x and 3.x. I assumed you meant 3.3, because that is widely used, but in that case, your print statement would not work. print() is a function, please get used to that. 2. Do not compare with True. Either the expression is True, or it is False. No need to be redundantly explicit ;). 3. There might be a more pythonic way to find the lowest payment. List comprehensions and min() come to mind; however, due to your naming conventions I do not fully understand what the code is supposed to find. Something called PaymentTable is supposed to return a table-like thing, not a boolean. Maybe you should get a bit more into detail about that (comment your code, for example ;)) and help us give you more hints on it. Cheers, Nik -- * mirabilos is handling my post-1990 smartphone * Aaah, it vibrates! Wherefore art thou, demonic device?? PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17 FD26 B79A 3C16 A0C4 F296 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 905 bytes Desc: Digital signature URL: From steve at pearwood.info Fri Nov 29 23:16:37 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 30 Nov 2013 09:16:37 +1100 Subject: [Tutor] TypeError: range() integer end argument expected, got float. In-Reply-To: <8D0BB4FCE8C27B1-12A0-8C029@webmail-vd007.sysops.aol.com> References: <8D0BB4FCE8C27B1-12A0-8C029@webmail-vd007.sysops.aol.com> Message-ID: <20131129221636.GE2085@ando> On Fri, Nov 29, 2013 at 02:24:49PM -0500, spinefxr at aol.com wrote: > Hi > > > Newbie at this. I am getting this error: > TypeError: range() integer end argument expected, got float. Note carefully that the error here is with the range() function. In your code, you have: > for payment in range(lowerbound, upperbound, 10): > if PaymentTable(balance, annualInterestRate, payment) == True: ####Error occurs at this line You are mistaken about where the error occurs. It occurs on the *previous* line, the one that says "for payment in range...". You have three arguments for range. All three need to be integers (whole numbers, like 0, 1, 2, ...) not floats (numbers with decimal points like 2.5, 5.25, or even 7.0). Even if the fraction part is "point zero", Python will insist it is a float. You have two solutions here: the best one is to go back to where you define lowerbound and upperbound and make sure they are whole numbers with no decimal point. The less-good solution is to change the line to this: for payment in range(int(lowerbound), int(upperbound), 10): -- Steven From eryksun at gmail.com Fri Nov 29 23:30:09 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 29 Nov 2013 17:30:09 -0500 Subject: [Tutor] empty delimiters, and None In-Reply-To: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> References: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> Message-ID: On Fri, Nov 29, 2013 at 8:19 AM, wrote: > > On trying to run the script (before the fix) I had the following traceback > message: > File "measure.py", line 35, in > locale.setlocale(locale.LC_ALL, '') > File > "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", > line 494, in setlocale > return _setlocale(category, locale) > locale.Error: unsupported locale setting > > If I booted from the Unix file I received the following feedback: > Setting Language: .UTF-8 > (process:82224): Gtk-WARNING **: Locale not supported by C library. Using > the fallback 'C' locale. It looks like you have a misconfigured environment. ".UTF-8" is missing the language, such as "en_GB.UTF-8". locale.setlocale calls the C runtime setlocale. Passing an empty string as the 2nd argument instructs setlocale to use the environment variables LC_ALL, LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME, and LANG. It uses the first one it finds. The search order might vary depending on the implementation. Just check them all: os.environ["LANG"], etc. If you pass None (translated to NULL in the C call) as the 2nd argument, then it only queries the current locale. This avoids the immediate problem without really fixing it. The process will use the default "C" locale. From steve at pearwood.info Fri Nov 29 23:44:35 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 30 Nov 2013 09:44:35 +1100 Subject: [Tutor] empty delimiters, and None In-Reply-To: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> References: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> Message-ID: <20131129224434.GF2085@ando> On Fri, Nov 29, 2013 at 08:19:37AM -0500, ugajin at talktalk.net wrote: [...] > After much continued searching I then found this > Bug #803791 report which describes (as an aside) the exact same issue > together with a solution. It might help if you provide a link to that bug report. Remember, you've read it, but we haven't. > I know next to nothing about Python and I shall be glad if any Python > guru can make clear (in layman's terms where possible) what the > problem is/was and how the fix works. > > I remembered an alternative posting that I had read, which reported > that Python dislikes empty delimiters. In general, that is certainly not true. Empty delimiters like [], '', {} and even () are legal and perfectly accepted in Python in many places. More context would be needed. [...] > On trying to run the script (before the fix) I had the following traceback message: > File "measure.py", line 35, in > locale.setlocale(locale.LC_ALL, '') > File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 494, in setlocale > return _setlocale(category, locale) > locale.Error: unsupported locale setting Ah, now we're getting somewhere! The locale settings control the internationalization of your operating system. For example, instead of everything being English all throughout the world, using locale, your computer can display buttons and menus in Greek when in Greece, in Japanese in Japan, and so on, provided the correct settings are available. The locale.setlocale() function takes two arguments, the first locale.LC_ALL is okay, the problem is with the second one. Originally it was set to the empty string '' which tells Python to return the current locale. Python complains about that which means either: - your system has no locale set at all; - your system is set to use a locale which has been removed from your computer. To fix this, you can set an environment variable. I don't know how to do this in OS-X, but in Linux systems I would edit my .bashrc config file and add the line: export LANG="blah blah blah" where "blah blah blah" is the name of a locale. You can find out which locales are available by running the system command: locale -a at the shell. If you need help doing this, you can try asking here, with luck somebody will know how to do this on a Mac. For reference, here is the relevant part of the docs: http://docs.python.org/2/library/locale.html#locale.setlocale > If I booted from the Unix file I received the following feedback: > Setting Language: .UTF-8 > (process:82224): Gtk-WARNING **: Locale not supported by C library. Using the fallback 'C' locale. I have no idea what you mean by this, sorry. What does "booted from the Unix file" mean? > Line 35 (above) shows the empty delimiter. The fix that I applied was > to replace line 35 in the Measure.py script with: > locale.setlocale(locale.LC_ALL, None). The Measure Path script then > executes correctly. No other action is/was required. I'm glad that this fixes the problem for you, but I'd be wary about leaving None in place. Passing None rather than '' does subtly different things, and I'm not sure if the Measure Path script does what it is supposed to do with None in place. Still, it appears to work, and I guess that provided there are no obvious problems with it, it seems harmless enough. The best thing would be to report this problem, and the apparent fix, to the author of the Measure Path script, and see what he or she thinks about it. > I note also the Python 2 library entry for Built-in Constants as: > None > The sole value of types.NoneType. [...] Thanks for that, but we're very familiar with None, as Python programmers you can barely go five minutes without needing to use None or see None in a piece of code. -- Steven From eryksun at gmail.com Sat Nov 30 00:05:25 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 29 Nov 2013 18:05:25 -0500 Subject: [Tutor] empty delimiters, and None In-Reply-To: <20131129224434.GF2085@ando> References: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> <20131129224434.GF2085@ando> Message-ID: On Fri, Nov 29, 2013 at 5:44 PM, Steven D'Aprano wrote: > Originally it was set to the empty string '' which tells Python to > return the current locale. Rather, an empty string instructs it to set the locale based on the environment. The default value of None queries the category's locale. From richkappler at gmail.com Sat Nov 30 02:17:54 2013 From: richkappler at gmail.com (richard kappler) Date: Fri, 29 Nov 2013 20:17:54 -0500 Subject: [Tutor] IndexError: list index out of range Message-ID: I have a script that makes use of the Google speech recognition API as follows: import shlex print " say something" os.system('sox -r 16000 -t alsa default recording.flac silence 1 0.1 1% 1 1.5 1%') cmd='wget -q -U "Mozilla/5.0" --post-file recording.flac --header="Content-Type: audio/x-flac; rate=16000" -O - " http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium"' args = shlex.split(cmd) output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate() if not error: a = eval(output) #a = eval(open("data.txt").read()) confidence= a['hypotheses'][0]['confidence'] speech=a['hypotheses'][0]['utterance'] print "you said: ", speech, " with ",confidence,"confidence" When I run that script by itself, it works fine. When I insert the script into a larger program, I get the following error: ERROR: Traceback (most recent call last): File "inga.py", line 146, in confidence= a['hypotheses'][0]['confidence'] IndexError: list index out of range If I understand it correctly, the traceback is telling me that there is no position [0] in my list, but I don't understand how that can be true. I'm not using the variable "confidence" anywhere else in the program. Here's the larger script/program into which the offending bits were inserted, up to the point of the error: #!/usr/bin/env python # -*- coding: utf-8 -*- import sys import aiml import commands import subprocess import marshal import datetime import os import os.path from os.path import exists ####################################################################### #################### read sensors ##################################### ####################################################################### ############ environmental ############ def environRead(): import serial from time import sleep sensors = dict.fromkeys('Sonar1 Sonar2 Sonar3 Sonar4 Dewpoint Temperature Humidity Light'.split()) arduino = serial.Serial('/dev/ttyACM0', 9600) sleep(1) line = arduino.readline().strip() line = line.lstrip('{').rstrip('}').strip() envSense = {} for item in line.split(','): item = item.strip() key, value = item.split(':') key = key.strip() value = value.strip() envSense[key]=int(value) return envSense ######## end environmental ####################### ########### somatic ############################## def somaticRead(): import psutil as ps cpu = ps.cpu_percent() mem = ps.virtual_memory() disk = ps.disk_usage('/') # need code to strip % out of disk, leaving just hdd = and some number # convert it all into a dictionary and return it ############ end somatic ########################## ####################################################################### ################ end sensor read ###################################### ####################################################################### ####################################################################### ############## facerec ################################################ ####################################################################### from SimpleCV import Camera import Image # initialize camera cam = Camera() #snap a picture using the camera img = cam.getImage() # find the face faces = img.findHaarFeatures('/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml') if faces: for face in faces: face.draw() # crop at box around detected face cropped = face.crop() # save to file for processing im = cropped.copy() im.save("temp.png") # process image - grayscale and size im = Image.open("temp.png").convert("L") im = im.resize((125, 150), Image.ANTIALIAS) #delete the temp.png file # filelist = [ f for f in os.listdir(".") if f.endswith(".png") ] # for f in filelist: # os.remove(f) #save image for face recognizer im.save("match.png") subprocess.check_call(["python", "facerec", "match.png", "faceDbase", "18", "3"]) filelist = [ f for f in os.listdir(".") if f.endswith(".png") ] for f in filelist: os.remove(f) tmp = open("namefile.txt") name = tmp.read() #print("Hello " + name) greet = ("Hello " + name) print greet festivalCmd = '(SayText "%s")' % greet subprocess.Popen(['/usr/bin/festival', '-b', festivalCmd]) # need to add functions for not finding or not recognizing a face ############# return from a function #def get_face(arg): # some_variable = 10 * arg # return some_variable #result = get_face(5) ######################################################################## ############## end facerec ############################################# ######################################################################## ######################################################################## ############## sphinx speech rec will go here ########################## ######################################################################## ######################################################################## ####################### Google speech rec ############################## ######################################################################## import shlex print " say something" os.system('sox -r 16000 -t alsa default recording.flac silence 1 0.1 1% 1 1.5 1%') cmd='wget -q -U "Mozilla/5.0" --post-file recording.flac --header="Content-Type: audio/x-flac; rate=16000" -O - " http://www.google.com/speech-api/v1/recognize?lang=en-us&client=chromium"' args = shlex.split(cmd) output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate() if not error: a = eval(output) #a = eval(open("data.txt").read()) confidence= a['hypotheses'][0]['confidence'] speech=a['hypotheses'][0]['utterance'] print "you said: ", speech, " with ",confidence,"confidence" ######################################################################## ################# end Google speech rec code ########################### ######################################################################## Any help would be greatly appreciated. regards, Richard -- *Mater tua criceta fuit, et pater tuo redoluit bacarum sambucus* -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Nov 30 03:23:15 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 30 Nov 2013 13:23:15 +1100 Subject: [Tutor] IndexError: list index out of range In-Reply-To: References: Message-ID: <20131130022315.GH2085@ando> On Fri, Nov 29, 2013 at 08:17:54PM -0500, richard kappler wrote: > I have a script that makes use of the Google speech recognition API as > follows: [...] > args = shlex.split(cmd) > output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= > subprocess.PIPE).communicate() > > if not error: > a = eval(output) A trivial typo here: the line a = eval(output) needs to be indented. More importantly though, this is quite risky. You're downloading data from the internet, then executing it as code. I really, really, really hope you trust the source of that data. By eval()ing their code, you give them complete and total control of your PC -- anything you can do, they can do. It's not just *them* that you have to trust, but anyone in the world who manages to compromise their server or the communication channel between them and you. How safe do you feel? > ERROR: > Traceback (most recent call last): > File "inga.py", line 146, in > confidence= a['hypotheses'][0]['confidence'] > IndexError: list index out of range > > If I understand it correctly, the traceback is telling me that there is no > position [0] in my list, but I don't understand how that can be true. I'm > not using the variable "confidence" anywhere else in the program. It's not "confidence" that has no position 0, but a['hypotheses'], whatever that is. Start by printing a['hypotheses'] and seeing what it contains. My guess is that it probably contains an empty list, []. Here's another reason for avoiding eval(). Presumably a['hypotheses'] is set by the code you download and then eval. That makes it completely opaque -- you can't easily see what it is doing, and if it plays up, you can't do anything about it. It's a complete black box that either works or doesn't work. What can we do about this? Well, if using eval() really is the only way to do this, I'd say the risk is not worth it. That sort of gung-ho attitude to security suggests that it's only a matter of time before the source is hacked, and once they're hacked, anyone using it is vulnerable too. [Aside: This sort of crap really makes me angry -- code injection vulnerabilities are one of the most common ways that viruses, spyware and other malware get into people's computers, and Google should know better than this. If Google actually recommend you use eval() to access their service, that just demonstrates that the Speech Recognition team don't give a monkey's toss for your security.] In the meantime, you can start by printing the code before eval()'ing it. That way at least we can see what it's supposed to be getting. Go back to the lines: if not error: a = eval(output) and change the block to: print(output) a = eval(output) # WARNING WARNING DANGER DANGER print(a) and then we can see what the code was supposed to do and what it actually did. My guess is that it was working before, but you've exceeded some limit on the number of requests per day, or possibly the speech recognition can't make out any words so it just returns an empty list. [soapbox] This is not aimed at you, you're a beginner and can be excused. But the Google techs have NO EXCUSE. I am so effing sick of coders in the 21st century who have no effing clue about even the most common-sense basics of security. No wonder there are so many malware and viruses around. Using eval here is like posting the keys to your house to some arbitrary tradesperson you've never met with instructions "I'll be away all next week, come around whenever you like and do whatever jobs you think need doing." You damn well better trust them, AND the post office. -- Steven From dyoo at hashcollision.org Sat Nov 30 04:14:50 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 29 Nov 2013 19:14:50 -0800 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <20131130022315.GH2085@ando> References: <20131130022315.GH2085@ando> Message-ID: > > > Here's another reason for avoiding eval(). Presumably a['hypotheses'] is > set by the code you download and then eval. That makes it completely > opaque -- you can't easily see what it is doing, and if it plays up, you > can't do anything about it. It's a complete black box that either works > or doesn't work. > > The API is undocumented, as far as I can tell. That being said, it appears to be JSON-oriented. http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ So the original questioner should use a JSON parser, rather than eval(). For example: http://www.athoughtabroad.com/2013/05/22/using-google-s-speech-recognition-web-service-with-python -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sat Nov 30 04:52:10 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 29 Nov 2013 22:52:10 -0500 Subject: [Tutor] IndexError: list index out of range In-Reply-To: References: Message-ID: On Fri, Nov 29, 2013 at 8:17 PM, richard kappler wrote: > > args = shlex.split(cmd) > output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= > subprocess.PIPE).communicate() Output to stderr doesn't necessarily mean a command failed. The process returncode is what you need to inspect. Use subprocess.check_output. It raises a subprocess.CalledProcessError for a non-zero return code. > if not error: > a = eval(output) Please post plain text to the list. Automatic conversion from rich to plain text isn't Python friendly. Don't use eval like this. Google isn't sending Python code in response to a web query. They're sending JSON data: import json output = ('{"status":0,"id":"","hypotheses":' '[{"utterance":"Python","confidence":0.58060002}]}') a = json.loads(output) >>> a['hypotheses'][0] {u'confidence': 0.58060002, u'utterance': u'Python'} >>> a['hypotheses'][0]['utterance'] u'Python' Remember to check the status code. I found a short list, but nothing official: 0 - correct 4 - missing audio file 5 - incorrect audio file When the speech recognition fails to form a hypothesis, print "Ozzy, is that you again?" ;) From stefan_ml at behnel.de Sat Nov 30 10:04:38 2013 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 30 Nov 2013 10:04:38 +0100 Subject: [Tutor] Pretty printing XML using LXML on Python3 In-Reply-To: References: Message-ID: SM, 29.11.2013 22:21: > On Thu, Nov 28, 2013 at 2:45 PM, eryksun wrote: >> On Thu, Nov 28, 2013 at 2:12 PM, SM wrote: >>> Run with Python3: >>> >>> $ python3 testx.py >>> b'\n \n some text\n\n' >> >> print() first gets the object as a string. tostring() returns bytes, >> and bytes.__str__ returns the same as bytes.__repr__. Meaning, it's a pure matter of visual representation on the screen, not a difference in the data. >> You can decode >> the bytes before printing, or instead use tounicode(): >> >> >>> s = etree.tounicode(root, pretty_print=True) >> >>> print(s) >> >> >> some text >> > > Thank you, eryksun. using tounicode seems to work on this small piece of > code. It still has issues with my code which is generating a big XML code. Well, I'm sure you are not generating a large chunk of XML just to print it on the screen, so using tostring(), as you did before, is certainly better. However, if it's really that much output, you should serialise into a file instead of serialising it into memory first and then writing that into a file. So, use ElementTree.write() to write the output into a file directly. Stefan From richkappler at gmail.com Sat Nov 30 19:40:00 2013 From: richkappler at gmail.com (richard kappler) Date: Sat, 30 Nov 2013 13:40:00 -0500 Subject: [Tutor] strip and split? Message-ID: I'm using psutil to generate some somatic data with the following script: import psutil as ps cpu = ps.cpu_percent() mem = ps.virtual_memory() disk = ps.disk_usage('/') All works well, but except for cpu I am struggling to learn how to strip out what I don't need. For example, once I do the above, if I then enter "disk" I get: disk usage(total=302264549376, used=73844322304, free=213066088448, percent=24.4) So if I want only the number following percent, I get that I need to convert this to a built in type and do some split and strip, but that's where I'm floundering. Might I get a little guidance on this please? regards, Richard -- *Mater tua criceta fuit, et pater tuo redoluit bacarum sambucus* -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfgang.maier at biologie.uni-freiburg.de Sat Nov 30 22:32:57 2013 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Sat, 30 Nov 2013 21:32:57 +0000 (UTC) Subject: [Tutor] strip and split? References: Message-ID: richard kappler gmail.com> writes: > > I'm using psutil to generate some somatic data with the following script: > > import psutil as ps > > cpu = ps.cpu_percent() > mem = ps.virtual_memory() > disk = ps.disk_usage('/') > > All works well, but except for cpu I am struggling to learn how to strip out what I don't need. > > For example, once I do the above, if I then enter "disk" I get: > > disk usage(total=302264549376, used=73844322304, free=213066088448, percent=24.4) > > So if I want only the number following percent, I get that I need to convert this to a built in type and do some split and strip, but that's where I'm floundering. Might I get a little guidance on this please? > I don't think you have to do any such thing. AFAICT, your code sets disk to a usage object that has all the information stored in its attributes. Try, e.g., disk.percent and it should give you what you want. Best, Wolfgang From dfjennings at gmail.com Sat Nov 30 22:34:31 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 30 Nov 2013 16:34:31 -0500 Subject: [Tutor] strip and split? In-Reply-To: References: Message-ID: <30F6C62E-DA37-49EB-A2CA-D17710A32A6B@gmail.com> On Nov 30, 2013, at 1:40 PM, richard kappler wrote: > I'm using psutil to generate some somatic data with the following script: > > import psutil as ps > > cpu = ps.cpu_percent() > mem = ps.virtual_memory() > disk = ps.disk_usage('/') > > All works well, but except for cpu I am struggling to learn how to strip out what I don't need. > > For example, once I do the above, if I then enter "disk" I get: > > disk usage(total=302264549376, used=73844322304, free=213066088448, percent=24.4) > > So if I want only the number following percent, I get that I need to convert this to a built in type and do some split and strip You could take that approach, but you might find that this one is easier: >>> psutil.disk_usage('/')[-1:][0] 91.2 Take care, Don From dfjennings at gmail.com Sat Nov 30 22:35:46 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sat, 30 Nov 2013 16:35:46 -0500 Subject: [Tutor] strip and split? In-Reply-To: References: Message-ID: On Nov 30, 2013, at 4:32 PM, Wolfgang Maier wrote: > richard kappler gmail.com> writes: > >> >> I'm using psutil to generate some somatic data with the following script: >> >> import psutil as ps >> >> cpu = ps.cpu_percent() >> mem = ps.virtual_memory() >> disk = ps.disk_usage('/') >> >> All works well, but except for cpu I am struggling to learn how to strip > out what I don't need. >> >> For example, once I do the above, if I then enter "disk" I get: >> >> disk usage(total=302264549376, used=73844322304, free=213066088448, > percent=24.4) >> >> So if I want only the number following percent, I get that I need to > convert this to a built in type and do some split and strip, but that's > where I'm floundering. Might I get a little guidance on this please? >> > > I don't think you have to do any such thing. AFAICT, your code sets disk to > a usage object that has all the information stored in its attributes. Try, e.g., > > disk.percent Yes! I like that much better than my suggestion. Take care, Don From denis.spir at gmail.com Sat Nov 30 10:28:19 2013 From: denis.spir at gmail.com (spir) Date: Sat, 30 Nov 2013 10:28:19 +0100 Subject: [Tutor] empty delimiters, and None In-Reply-To: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> References: <8D0BB1CC62C0020-2AC-1BEE9@webmail-vfrr13.sis.aol.com> Message-ID: <5299AFB3.6000809@gmail.com> On 11/29/2013 02:19 PM, ugajin at talktalk.net wrote: > I have also looked at locale.py Line 494 of which is the last line of a def (def function?) I include this below, hopefully this may save you searching for locale.py (Pyhon 2.6) should you need it and wish to answer the above questions, it may help. > > def setlocale(category, locale=None): > > """ Set the locale for the given category. The locale can be > a string, a locale tuple (language code, encoding), or None. > > Locale tuples are converted to strings the locale aliasing > engine. Locale strings are passed directly to the C lib. > > category may be given as one of the LC_* values. > > """ > if locale and type(locale) is not type(""): > # convert to string > locale = normalize(_build_localename(locale)) > return _setlocale(category, locale) As a side-note, in addition to what other have said, the headline of the function def def setlocale(category, locale=None) says that None is the default (standard) value for the parameter 'locale'. This means that, if ever you provide no value for it when calling setlocale, then the value None is used in standard. So, you could as well call it like: locale.setlocale(locale.LC_ALL) # no value at all for param 'locale' instead of you correction locale.setlocale(locale.LC_ALL, None) for the initial version locale.setlocale(locale.LC_ALL, '') This is actually good coding practice (in all language which have default values). Denis From mail at peterzorn.de Sat Nov 30 16:21:55 2013 From: mail at peterzorn.de (Peter Zorn) Date: Sat, 30 Nov 2013 16:21:55 +0100 Subject: [Tutor] Output not legible when debugging with ipdb In-Reply-To: References: <1855108606.1304808.1385475774077.open-xchange@communicator.strato.de> Message-ID: <529A0293.4010908@peterzorn.de> PyReadline is installed with the Anaconda distribution, and Powershell displays colored IPython output, but not when I use ipdb for whatever reason. I figured out that from IPython.core.debugger import Tracer; debug_here = Tracer() debug_here() seems to yield the desired result: a debugger with colored code, tab completion, etc.... (see http://ipython.org/ipython-doc/stable/api/generated/IPython.core.debugger.html?highlight=debugger#IPython.core.debugger) Thanks, Peter On 27.11.2013 00:24, eryksun wrote: > On Tue, Nov 26, 2013 at 4:28 PM, Walter Prins wrote: >> honest. Regarding Powershell (vs for example cmd.exe): The (slightly) >> perplexing/irritating/annoying thing is that the older cmd.exe shell, which >> uses a standard old-school NT console window, does support ANSI escape >> sequences (but is otherwise pretty braindead IMHO, for example does not >> support arbitrary resizing, copy and paste is clunky and so on), while the >> text mode/console window hosting Powershell behaves somewhat differently, >> and is (IIRC) at least resizable, but apparently doesn't support escape >> sequences, so there appears to be some differences -- though I realize these >> must be due to features in the shells themselves since they share some >> common console window functionality. > The cmd shell's built-in "type" and "echo" commands don't parse escape > sequences. I think "color" is the only command that sets character > attributes, and only for the entire screen buffer (e.g. "color 0D" > sets light purple text on a black background). > > Adding escape-sequence support to existing programs such as cmd.exe > has to be done in the console itself or by hacking the console API. > ConEmu manages a hidden console window and does all of its own > display. There's also ANSICON, which injects a DLL (ansi32.dll or > ansi64.dll) into the process. My guess is that the DLL hooks kernel32 > WriteConsole to look for escape sequences and then scripts the console > API. However it works, it's very simple to use: > > ANSICON > https://github.com/adoxa/ansicon > > Console API > http://msdn.microsoft.com/en-us/library/ms682073 > > I agree the Windows console is braindead. It was fine for its day in > NT 3 and 4 back in the 90s, but it hasn't improved much in 20 years, > and I doubt it ever will. Maybe with PowerShell you're thinking of the > Integrated Scripting Environment: > > http://technet.microsoft.com/en-us/library/dd819514 > > For IPython, try the Qt console: > > http://ipython.org/ipython-doc/stable/interactive/qtconsole.html From ugajin at talktalk.net Sat Nov 30 13:04:46 2013 From: ugajin at talktalk.net (ugajin at talktalk.net) Date: Sat, 30 Nov 2013 07:04:46 -0500 Subject: [Tutor] empty delimiters, and None Message-ID: <8D0BBDB7A91DC28-2AC-1C8FB@webmail-vfrr13.sis.aol.com> Thanks for the helpful comments Eryksun/Steve Mis-configured environment (see below)? I rather felt that setting the 2nd parameter to None, was side stepping an underlying issue. However I experimented further and find; locale.setlocale(locale.LC_ALL, 'en_GB') also works OK. Perhaps this is a better fix than locale.setlocale(locale.LC_ALL, None) but again it may be side stepping the underlying issue. Here is link: https://answers.launchpad.net/inkscape/+question/239599. I think you need to register to access the both the question and Bug #803791 report. You may not want to do this. I believe the system locale is set correctly: Apples-iMac-4:~ apple$ locale LANG="en_GB.UTF-8" LC_COLLATE="en_GB.UTF-8" LC_CTYPE="en_GB.UTF-8" LC_MESSAGES="en_GB.UTF-8" LC_MONETARY="en_GB.UTF-8" LC_NUMERIC="en_GB.UTF-8" LC_TIME="en_GB.UTF-8" LC_ALL= The underlying problem appears to be with the application launcher script (see below). To explain 'booted from Unix file' is difficult for me, especially if you are unfamiliar with OSX, It is a way of running the application together with a Terminal window. Inkscape is an Open Source SVG editor with some 'proprietary' features that are not part of the SVG standard. The Measure Path script, can calculate either the length of, or the area enclosed by a path. The value is displayed as text, which is added and anchored to the path that is measured. Variables include precision (no. of significant places) and unit type (px, mm & etc.), as well as offset & font size (for text output). I did try contacting one of its authors, and I have raised the matter as a question, (see link above). The initial response was; "A workaround is to edit the launcher script (to force a valid UTF-8 language settings)." The fix provided (shown below) caused Inkscape to crash immediately after the launch routine completed: Quit all running instances of Inkscape. Then 1) Select Inkscape (the application) in the Finder 2) Choose 'Show Package Contents' from the context menu 3) Browse to 'Contents > Resources > bin' 4) Open the file 'inkscape' in a plain-text editor (e.g. TextWrangler) 5) Scroll down to line 127 6) Insert a new line before line 127 with this content: export LANG="en_US.UTF-8" 7) Save & close file (make sure that your text editor does _not_ add a hidden suffix to the file, else the application won't launch anymore) 8) Relaunch Inkscape If you prefer a different UI language, adjust the string "en_US.UTF-8" as needed. Lines 123 to 127 of the launcher script read: # NOTE: Have to add ".UTF-8" to the LANG since omitting causes Inkscape # to crash on startup in locale_from_utf8(). export LANG="`grep \"\`echo $LANGSTR\`_\" /usr/share/locale/locale.alias | \ tail -n1 | sed 's/\./ /' | awk '{print $2}'`.UTF-8" echo "Setting Language: $LANG" 1>&2 I am told this 'fix' works for OSX v10.5.8 (Leopard) and OSX 10.7.5 (Lion). However, I run OSX v10.6.8 (Snow Leopard). I am also interested in identifying the underlying issue, although I am far out of my comfort zone, and which seems to be with the launcher script. From the various postings and comments read, this seems to be something of an old chestnut. Maybe you can't suggest an alternative fix to the above, but maybe you can comment to help explain lines 123 - 127. Many many thanks, once more. -A -------------- next part -------------- An HTML attachment was scrubbed... URL: