Re: [Tutor] Converting a string into dictionary references
On 2012/04/23 03:46 PM, Gerhardus Geldenhuis wrote: Not quite, I have csvfile1: column1, column2, column3, ... column200 That is my raw data but I want to use only 5 columns for example in a specific application. I thus want a file with the following: column33,column1,column5 I then want to read the original csv file and write a new csv file with the requested columns only. Does that make more sense? Regards On 23 April 2012 14:41, Joel Goldstick joel.goldst...@gmail.com mailto:joel.goldst...@gmail.com wrote: On Mon, Apr 23, 2012 at 8:56 AM, Gerhardus Geldenhuis gerhardus.geldenh...@gmail.com mailto:gerhardus.geldenh...@gmail.com wrote: Hi Appologies about the subject I could not think of a better description. I have this very simple function: def readcsvfile(filename): f = open(filename, 'ro') csvdata = csv.DictReader(f) for row in csvdata: print row[column3]+','+row[column1] I have another inputfile that will be comma separated list of values. Eg: column3,column4,column10 The idea is that I use this inputfile to tranform the original csv file. I thus want a new file with only the specified columns. I am sure there is an elegant way of doing this but I am not sure how to convert my print statement into something more dynamic. Any pointers would be appreciated. Regards -- Gerhardus Geldenhuis ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor So you want to take 'column1' and get back 1?, 'column10' and get back 10? s = 'column1' i = int(s[6:]) This will only work if your strings all start with the text 'column' -- Joel Goldstick -- Gerhardus Geldenhuis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you don't need to use Python and are on a *nix machine you can use cut to do the work for you for eg and it might simplify your workflow. -d specifies the delimiter of the file, in this case a comma -f specifies the fields you want, in this case 1 to 3, 5, and 10 cut -d, -f1-3,5,10 input_filename output_filename -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] user created lists
On 2012/04/12 08:59 AM, Peter Otten wrote: Christian Witts wrote: On 2012/04/12 06:42 AM, john moore wrote: Hello Pyhton World, I'm new at this and was wondering how I create a number of user specified lists? Example: How many list would you like to create? User inputs 5 creates five lists, list1 [] list2 [] list3 [] list4 [] list5 [] I can create one with append, but I don't know how to loop it to create five different named list.. You can use vars() to create the variables on the fly. vars() is just a dictionary containing the variable name as the key, and the data as the value so you can do `vars()['list1'] = []` and it's easy enough to create them en masse # Set the start to 1, and add 1 to what the user inputted # as range/xrange doesn't include the top number for i in xrange(1, user_input + 1): vars()['list%s' % i] = [] This will stop working once you move your code into a function: def f(): ... vars()[list1] = [a, b] ... print list1 ... f() Traceback (most recent call last): File stdin, line 1, inmodule File stdin, line 3, in f NameError: global name 'list1' is not defined I recommend that you bite the bullet and use a dedicated dictionary or list to hold your five lists from the very begining: You could use globals() then instead of var(), although it's a do-it-at-your-own-risk situation then if you overwrite built-ins and other functions in the namespace. Creating your own dictionary with the 'variable name' as the key, would be the nicer solution instead. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need help with a script..
On 2012/04/11 03:50 PM, Khalid Al-Ghamdi wrote: Hi All, I'm using python 3.2 on a windows xp. I wrote the below script and ran it with the hope of returning a list of proctors (list_proc), but when it runs it doesn't call the function convert_proctors() as intended. On the other hand, when i import the module from the IDLE prompt and call the convert_proctors() function, the function returns the desired list. Why is this so? Thanks 1. import csv 2. 3. proctor_file=r'c:\Python32\Khalid Stuff\Testing_Scheduler\proctors.csv' 4. 5. 6. def convert_proctors(): 7. proctor_csv_reader = csv.reader(open(proctor_file)) 8. proctor_list=list(proctor_csv_reader) 9. list_proc=[] 10. for row in range(len(proctor_list)): 11. list_proc.append(proctor_list[row][0]) 12. return (list_proc) 13. 14. 15. convert_proctors() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor convert_proctors() will get called when you run the application from say the command line, but because there's no explicit printing of the resulting list it will never get displayed to your console. Whereas when you run it from IDLE it will implicitly print the return value of a function if you do not save the data to a variable. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] user created lists
On 2012/04/12 06:42 AM, john moore wrote: Hello Pyhton World, I'm new at this and was wondering how I create a number of user specified lists? Example: How many list would you like to create? User inputs 5 creates five lists, list1 [] list2 [] list3 [] list4 [] list5 [] I can create one with append, but I don't know how to loop it to create five different named list.. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You can use vars() to create the variables on the fly. vars() is just a dictionary containing the variable name as the key, and the data as the value so you can do `vars()['list1'] = []` and it's easy enough to create them en masse # Set the start to 1, and add 1 to what the user inputted # as range/xrange doesn't include the top number for i in xrange(1, user_input + 1): vars()['list%s' % i] = [] Hope that helps. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ADO with python 2.6 without additional installs
On 2012/04/10 11:13 AM, Bakkestuen Roger wrote: Hi I’m struggling with finding a way to access and query an MSAccess base in an organisation with a very standardised environment. Python 2.6 is available and Office 2010. Is there a way to access and query trough for instance ADO without having to install the Win32 package? Any suggestions or even sample code? *Best regards* *Roger Bakkestuen* ** Norwegian Public Roads Administration Eastern Region – Geodata *Post adress:*Statens vegvesen Region øst, Postboks 1010, 2605 LILLEHAMMER *Office adress*: Industrigaten 17, LILLEHAMMER *Phone:* +47 61271236 *Mobile:* +47 94833636 *e-mail:* roger.bakkest...@vegvesen.no mailto:roger.bakkest...@vegvesen.no www.vegvesen.no http://www.vegvesen.no/ *e-mail:* firmapost-...@vegvesen.no mailto:firmapost-...@vegvesen.no ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You can give PyODBC [1] a try as it does support MS Access [2]. [1] http://code.google.com/p/pyodbc/ [2] http://code.google.com/p/pyodbc/wiki/ConnectionStrings -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ADO with python 2.6 without additional installs
On 2012/04/10 03:07 PM, Bakkestuen Roger wrote: This requires install of pyodbc. I was looking for modules in std python 2.6 or higher. Med hilsen Roger Bakkestuen *Telefon:* +47 61271236 *Mobil:* +47 94833636 *e-post:* roger.bakkest...@vegvesen.no mailto:roger.bakkest...@vegvesen.no --- *Fra:*Christian Witts [mailto:cwi...@compuscan.co.za] *Sendt:* 10. april 2012 11:24 *Til:* Bakkestuen Roger *Kopi:* tutor@python.org *Emne:* Re: [Tutor] ADO with python 2.6 without additional installs On 2012/04/10 11:13 AM, Bakkestuen Roger wrote: Hi I’m struggling with finding a way to access and query an MSAccess base in an organisation with a very standardised environment. Python 2.6 is available and Office 2010. Is there a way to access and query trough for instance ADO without having to install the Win32 package? Any suggestions or even sample code? *Best regards* *Roger Bakkestuen* ** Norwegian Public Roads Administration Eastern Region – Geodata *Post adress:*Statens vegvesen Region øst, Postboks 1010, 2605 LILLEHAMMER *Office adress*: Industrigaten 17, LILLEHAMMER *Phone:* +47 61271236 *Mobile:* +47 94833636 *e-mail:* roger.bakkest...@vegvesen.no mailto:roger.bakkest...@vegvesen.no www.vegvesen.no http://www.vegvesen.no/ *e-mail:* firmapost-...@vegvesen.no mailto:firmapost-...@vegvesen.no ___ Tutor maillist -Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You can give PyODBC [1] a try as it does support MS Access [2]. [1] http://code.google.com/p/pyodbc/ [2] http://code.google.com/p/pyodbc/wiki/ConnectionStrings -- Christian Witts Python Developer Unfortunately the only DB Access that's built into Python is SQLite, for all other databases you'll need to install 3rd party packages. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to Python programing
On 2012/04/03 03:50 PM, Cranky Frankie wrote: Another resourse for learning to program is YouTube. They just had a segment on 60 Minutes about a guy who does all kinds of well regarded free courses on-line, unfortunately I can't remberber the URL. I've viewed several Stanford University programming courses, and there are many Python specific vidoes there as well. Just something else to check out. Are you possibly thinking of the Khan Academy [1] ? [1] http://www.khanacademy.org/ -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
On 2012/03/27 03:08 AM, thao nguyen wrote: Dear Support Team, I have built a function (enclosed here) to merge many files (in this example is 2 files: a1.txt and a2.txt) lines by lines. The output file is called final_file. However, i could not have it run successfully. Content of a1.txt: 1 3 5 Content of a2.txt: 2 4 6 Content of final_file.txt will be like: 1 2 3 4 5 6 In Python, i called just written module: import argument reload(argument) argument.test(2,C:/a1.txt,C:/a2.txt) and get the error as below: ValueError: I/O operation on closed file File c:\append.py, line 5, in module argument.test(2,C:/a1.txt,C:/a2.txt) File c:\argument.py, line 28, in test for line_data in f: Could you please advise the resolution for this? Thank you ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Your Exception states what the problem is, which is operating on a closed file, and your traceback indicates it is when you're iterating over it. As the error occurs in your argument.py file, you should post the relevant portions of that code too. You could also do `cat file1 file2 filen final_file` in a *nix prompt if that is your use-case. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Refactoring
On 2012/03/08 03:13 PM, Ejaj Hassan wrote: Hi, I have been hearing this refactoring of code. Well does it have any thing like this in Python and if it is then what is it all about. Thanks. Regards, Ejaj ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor /Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the code yet improves its internal structure./ -- Martin Fowler in Refactoring: Improving The Design Of Existing Code [1] As for Python IDEs that have built-in refactoring tools, I know of PyCharm [2] which handles it. [1] http://martinfowler.com/refactoring/ [2] http://www.jetbrains.com/pycharm/features/ -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about writing to Excel with slavic characters
On 2012/03/05 02:37 PM, Marko Limbek wrote: Hi everyone. I am new to list and few months old to Python. I am writing some text to Excel and I open the new book and try to write to the book and the save it using book.save Now when I write slavic characters in the text to Excel (č, š, ž, for instance 0xc5), I get an error, I can't save it. I have declared appropriate encoding # -*- coding: utf-8 -*- # coding=utf-8 #!/E:/Python and those characters appear normally in the code, but there seems to be the problem with the function book.save. Does anyone have any ideas, what would be the problem and how to solve it? Some additional encoding or some changes or parameters to the book.save method? Is that the right forum for my question? Thank you, Marko ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor What package are you using to create your Excel workbook ? If it's xlwt you can set your encoding type when you create your workbook book = xlwt.Workbook(encoding=utf-8) -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about writing to Excel with slavic characters
On 2012/03/05 03:05 PM, Marko Limbek wrote: Thank you! That was easy. Now I have another problem. I use RPy and read the spss database with method read.spss inside a nested R code in Python, that looks like that: import rpy r( library(foreign) baza- read.spss( + analysis[0] + ) print(baza$demo_izob0) ) Now when my text data labels in spss have slavic characters, they are not recognised and output is something like that: stiriletna srednja �ola nedokon�ana osnovna �ola What should I do here? Thanks a lot, Marko On Mon, Mar 5, 2012 at 1:46 PM, Christian Wittscwi...@compuscan.co.za wrote: On 2012/03/05 02:37 PM, Marko Limbek wrote: Hi everyone. I am new to list and few months old to Python. I am writing some text to Excel and I open the new book and try to write to the book and the save it using book.save Now when I write slavic characters in the text to Excel (č, š, ž, for instance 0xc5), I get an error, I can't save it. I have declared appropriate encoding # -*- coding: utf-8 -*- # coding=utf-8 #!/E:/Python and those characters appear normally in the code, but there seems to be the problem with the function book.save. Does anyone have any ideas, what would be the problem and how to solve it? Some additional encoding or some changes or parameters to the book.save method? Is that the right forum for my question? Thank you, Marko ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor What package are you using to create your Excel workbook ? If it's xlwt you can set your encoding type when you create your workbook book = xlwt.Workbook(encoding=utf-8) -- Christian Witts Python Developer Hi, you should avoid top-posting as it makes it hard to follow the thread if people have to bounce between the top and bottom of the post. As for the answer to your question, I would suggest the R Mailing List if they have any issues with Unicode or need any encodings set when loading data etc. There was a bug with Unicode support RPy 2.2 but that was fixed last year so if you have a recent version of RPy that shouldn't be the issue. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to a file/changing the file name
On 2012/02/23 07:04 AM, Michael Lewis wrote: Hi everyone, I have a program where I open a file (recipe.txt), I read that file and write it to another file. I am doing some multiplying of numbers in between; however, my question is, when I name the file I am writing to, the file extension is changed, but the file name is not. What am I doing wrong? Code: import Homework5_1 as multiply def MultiplyNumbersInFile(file_name, multiplier): '''Open file/read file/write new file that doubles all int's in the read file''' try: read_file = open(file_name) except IOError: print I can't find file: , file_name return new_file_name = file_name + '2' try: write_file = open(new_file_name, 'w') except IOError: read_file.close() print I can't open file: , new_file_name return for line in read_file: new_line = line.split() new_line = ''.join(multiply.MultiplyText(new_line, multiplier)) write_file.write(new_line + '\n') read_file.close() write_file.close() def main(): file_name = raw_input('What file do you want to open? ') multiplier = multiply.GetUserNumber() MultiplyNumbersInFile(file_name, multiplier) if __name__ == '__main__': main() What I am doing in IDLE: What file do you want to open? recipe.txt Enter a multiplier: 2 The file that is actually created in my directory is still named recipe; however, the file type is now TXT2 File. How do I make it so I am updating the file name to recipe2 instead of the file type? -- Michael J. Lewis ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor That's because your `file_name` variable contains the file name and extension. You will need to split it into it's component pieces and then put it back together once you've changed the name, and for that you can use os.path.splitext import os filename, extension = os.path.splitext('recipe.txt') print (filename, extension) ('recipe', '.txt') new_filename = filename + '2' + extension print new_filename 'recipe2.txt' -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] '__name__' == '__main__'
On 2012/02/21 06:55 AM, Michael Lewis wrote: I am back to being confused. I just tried running the module without first importing it, and it worked just fine. How do I do this properly to where the module only runs if I import it? Code: def MultiplyText(text, multiplier): '''Recieve a S int. For digits in S, multiply by multiplier and return updated S.''' return ' '.join(str(int(num) * multiplier) if num.isdigit() else num for num in text) def GetUserInput(): '''Get S multiplier. Test multiplier.isdigit(). Call MultiplyText(text, multiplier)''' text = raw_input('Enter some text: ') while True: multiplier = raw_input('Enter a multiplier: ') try: multiplier = int(multiplier) break except ValueError: continue return MultiplyText(text.split(), multiplier) if __name__ == '__main__': GetUserInput() What I did in IDLE: GetUserInput() Enter some text: 4 times Enter a multiplier: 2 '8 times' -- Michael J. Lewis mjole...@gmail.com mailto:mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you change '__main__' to the name of the file, without the extension, it will match __name__. Alternatively, you can have an else after your `__name__ == '__main__'` $ cat t1.py if __name__ == '__main__': print 'Executed from __main__' if __name__ == 't1': print 'Executed by import from t2' $ cat t2.py import t1 $ python t1.py Executed from __main__ $ python t2.py Executed by import from t2 $ cat t3.py if __name__ == '__main__': print 'Executed from __main__' else: print 'Executed by import' $ cat t4.py import t3 $ python t3.py Executed from __main__ $ python t4.py Executed by import -- Christian Witts Python Developer COMPUSCAN | CONFIDENCE IN CREDIT Telephone : +27 21 888 6000 National Call Centre : 0861 51 41 31 Fax : +27 21 413 2424 Email : cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za Website: www.compuscan.co.za http://www.compuscan.co.za Would you like to hear more from us? Register here and receive our newsletters and other business communications. http://compuscan.us2.list-manage.com/subscribe?u=b14cacd3a29021ca07d2b32b9id=163a9926e2 */NOTE:/* This e-mail (including attachments) is subject to the disclaimer published at our website http://www.compuscan.co.za/about-us/132-email-disclaimer. If you cannot access the disclaimer, request it from email.disclai...@compuscan.co.za mailto:email.disclai...@compuscan.co.za or 0861 514131. National Credit Regulator Credit Bureau Registration No. NCRCB6 /Please consider the environment before printing/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Where can I download the document for twisted?
On 2012/02/10 02:48 PM, daedae11 wrote: Where can I download the document for twisted? I could't find it on twistedmatrix.com . daedae11 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor There a link to The complete developer guide in PDF Format on http://twistedmatrix.com/trac/wiki/Documentation -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What the difference between the two RE?
On 2012/02/09 09:44 AM, daedae11 wrote: However, re.match(hello, And they said hello ) will also return None. So And they said hello also won't be matched by the regex pattern hello. daedae11 *From:* Christian Witts mailto:cwi...@compuscan.co.za *Date:* 2012-02-09 15:16 *To:* daedae11 mailto:daeda...@126.com *CC:* turor_python mailto:tutor@python.org *Subject:* Re: [Tutor] What the difference between the two RE? On 2012/02/09 08:15 AM, daedae11 wrote: import re re.match(^hello, hello) re.match(hello, hello) Please give a string that matches RE ^hello but does not match RE hello, or matches RE hello but does not match RE ^hello. daedae11 ___ Tutor maillist -Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The caret ^ means At the beginning of the line so 'And they said hello' will not be matched by the regex pattern '^hello'. The docs are pretty good on the module http://docs.python.org/library/re.html http://docs.python.org/howto/regex.html -- Christian Witts Python Developer // -- From the docs http://docs.python.org/library/re.html#re.match Note: If you want to locate a match anywhere in string, use search() instead. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What the difference between the two RE?
On 2012/02/09 08:15 AM, daedae11 wrote: import re re.match(^hello, hello) re.match(hello, hello) Please give a string that matches RE ^hello but does not match RE hello, or matches RE hello but does not match RE ^hello. daedae11 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The caret ^ means At the beginning of the line so 'And they said hello' will not be matched by the regex pattern '^hello'. The docs are pretty good on the module http://docs.python.org/library/re.html http://docs.python.org/howto/regex.html -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Character Buffer Object Error
On 2012/02/08 07:56 AM, Michael Lewis wrote: I want to find all digits in a string and then increment those digits by 1 and then return the same string with the incremented digits. I've tried the following code, but I am getting the following error. How do I do this properly? def AlterInput(user_input): print user_input new_output = '' for index, char in enumerate(user_input): if char.isdigit(): new_char = int(char) new_char += 1 new_output = ' '.join(user_input) new_output.replace(char, new_char) print new_output def GetUserInput(): '''Get a string from the user and pass it''' user_input = '''I got 432 when I counted, but Jim got 433 which is a lot for only 6 cats, or were there 12 cats?''' AlterInput(user_input.split()) Traceback (most recent call last): File C:/Python27/Homework/Homework 4_1.py, line 25, in module GetUserInput() File C:/Python27/Homework/Homework 4_1.py, line 23, in GetUserInput AlterInput(user_input.split()) File C:/Python27/Homework/Homework 4_1.py, line 15, in AlterInput new_output.replace(char, new_char) TypeError: expected a character buffer object Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor new_char is of type int and not type str, so cast it back to a string before using it in your call to .replace as it expects both arguments to be strings. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Lists/raw_input
On 2012/02/07 07:40 AM, Michael Lewis wrote: I want to prompt the user only once to enter 5 numbers. I then want to create a list out of those five numbers. How can I do that? I know how to do it if I prompt the user 5 different times, but I only want to prompt the user once. Thanks. -- Michael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You can take your input from your user in one line seperated by something like a space and then split it after you capture it so for eg. user_input = raw_input('enter 5 numbers seperated by a space each: ') list_from_input = user_input.split() # Split by default splits on spaces, otherwise you need to specify the delimiter # Then you can validate the list to ensure all 5 are actually numbers, otherwise prompt the user to re-enter them Hope that help. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] loop until a keypress
On 2012/01/30 07:20 AM, Surya K wrote: I want to run code until a enter is pressed. Well, it shouldn't wait for the user to enter enter This is my code: import msvcrt chr = 0 while chr != 'q': print my code, if msvcrt.kbhit(): chr = msvcrt.getch() This isn't working the way I wanted. When ever I press enter, the loop is starting in a new line and continuing. I even added break statement in if block but it isn't working Can you tell me how to do that? I am on windows. So, as msvcrt is for windows, I wonder if there is any module that works for both, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor There isn't a platform independent module for capturing keystrokes unfortunately. You can take a look at this StackOverflow answer though which could help you out http://stackoverflow.com/questions/5044073/python-cross-platform-listening-for-keypresses -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ASCII Conversion
On 2012/01/31 06:50 AM, Michael Lewis wrote: I am trying to do a simple test but am not sure how to get around ASCII conversion of characters. I want to pass in y have the function test to see if y is an integer and print out a value if that integer satisfies the if statement. However, if I pass in a string, it's converted to ASCII and will still satisfy the if statement and print out value. How do I ensure that a string is caught as a ValueError instead of being converted? def TestY(y): try: y = int(y) except ValueError: pass if y -1 or y 1: value = 82 print value else: pass -- Michael J. Lewis mjole...@gmail.com mailto:mjole...@gmail.com 415.815.7257 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you just want to test if `y` is an integer you can do so with `type(y) == int`, and to get the ASCII value of a character you can use `ord` like `ord('a') == 97`. And how to avoid your ValueError with a bad conversion, do your type checking before hand. Hope that helps. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] exception about ctrl+c
On 2012/01/09 02:24 PM, daedae11 wrote: I want to catch the ctrl+c exception. My program is as following. But when I run my script and press ctrl+c, the program output nothing. I don't know where did I go wrong. Please help me. Thank you! def safe_input(prompting): try: return raw_input(prompting); except KeyboardInterrupt, error: print error; return None; def main(): a = safe_input(input any thing!\n); print a; if __name__ == '__main__': main(); daedae11 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor def safe_input(prompting): try: return raw_input(prompting) except KeyboardInterrupt: print 'KeyboardInterrupt Issued' return None That will work as intended, if you had your original `except KeyboardInterrupt, error:` and did a `print repr(error)` afterwards you will see it does not contain an error message as you perhaps wanted. Also, Python does not require semi-colons to denote the end-of-line. It can be used if you want to have multiple statements on a single line though. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to calculate program compile time?
On 2011/12/08 12:59 PM, surya k wrote: I'm doing puzzles where we need to write code that works as fast a possible So, how can I check the compile time of my program ?... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You can use the `timeit` [1] module or outside of Python if you're using Linux you can use `time`. That will give you your total execution time. You can also look at further performance tips [2] if needed. [1] http://docs.python.org/library/timeit.html [2] http://wiki.python.org/moin/PythonSpeed/PerformanceTips -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] unable to use find(), index()
On 2011/12/08 01:19 PM, surya k wrote: I am using the following code astr = foobarstr1 =fooastr.find(str1, beg=0, end=3) This is showing the following error Traceback (most recent call last): File interactive input, line 1, inmoduleTypeError: find() takes no keyword arguments I even tried by importing string module, but it isn't working. This same problem with find() Could you please help me! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Your traceback message gives you the reason it's not working, `find() takes no keyword arguments`. The function only takes positional arguments so if you just write `astr.find(str1, 0, 3)` it will work as you expect it to. help(''.find) Help on built-in function find: find(...) S.find(sub [,start [,end]]) - int Return the lowest index in S where substring sub is found, such that sub is contained within s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random order program
On 2011/11/28 12:17 AM, myles broomes wrote: I requested help for this code earlier and I thought it had been corrected but apparently, there is still a problem with it... #random word order program #the user gives the program a list of words #the program then returns them in a random order import random #explain the purpose of the program to the user print(At the prompt, type in a list of words and they will be returned in a random order.) #get the users input for the list of words, one by one first_word = input(Please enter your first word: ) second_word = input(Please enter your second word: ) third_word = input(Please enter your third word: ) fourth_word = input(Please enter your fourth word: ) fifth_word = input(Please enter your fifth word: ) #create a tuple containing the users words of the words word_list = (first_word,second_word,third_word,fourth_word,fifth_word) #create an empty list that the words will go into to be returned in a random order random_word_list = [] print(Now your list will be displayed in a random order.) #random order list while len(random_word_list) != len(word_list): word = random.choice(word_list) if word not in random_word_list: random_word_list += word #display the random word list print(random_word_list) input(Press enter to exit...) And once again, the following is displayed At the prompt, type in a list of words and they will be returned in a random order. Please enter your first word: one Please enter your second word: two Please enter your third word: three Please enter your fourth word: four Please enter your fifth word: five Now your list will be displayed in a random order. Then the program just stops for some reason. Again, any help is much appreciated. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Is there anything wrong with just doing the following ? from random import shuffle # just type words with space separating the items # ie. one two three four five words = input('Please enter a list of words: ') word_list = words.split() print word_list shuffle(word_list) print word_list -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random order program
On 2011/11/28 11:37 AM, Peter Otten wrote: Christian Witts wrote: Is there anything wrong with just doing the following ? from random import shuffle # just type words with space separating the items # ie. one two three four five words = input('Please enter a list of words: ') word_list = words.split() print word_list shuffle(word_list) print word_list You're mixing 3.x input and 2.x print ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Doh, that's what you get when you retype your code instead of copy/pasta it, it was originally raw_input. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On 2011/11/25 10:41 AM, lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str(k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor pairs.items() is fine if it's a small dictionary but for larger ones it's going to slow things down as it generates the entire list of items before you continue, rather use .iteritems() as it creates an iterator which only yields one item at a time making it more efficient. str(k)[1]+str(k)[0] is string concatenation so your first key tested is '6669' and not ('66', '69') as you intended, you would have to create a new tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. Also, your check to in pairs.keys() is wasteful as you generate a new list of keys for every key and you will be better off using `in pairs:` directly as it performs a dictionary lookup to test if the key exists. With that in mind, this is how I would re-write that code segment. YMMV for key in pairs.iterkeys(): # The [::-1] creates a reverse of the iterable so ('66', '69') will be ('69', '66') if key[::-1] in pairs: try: # The first instance of the pair gets kept and the reversed gets added pairs[key] += pairs[key[::-1]] del pairs[::-1] except KeyError: print Key ('%s', '%s') already accumulated) % key Hope that helps. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to delete some quasi-duplicated keys
On 2011/11/25 11:15 AM, lina wrote: On Fri, Nov 25, 2011 at 5:05 PM, Christian Wittscwi...@compuscan.co.za wrote: On 2011/11/25 10:41 AM, lina wrote: pairs {('66', '69'): 217, ('69', '66'): 75, ('64', '71'): 25} such as here ('66', '69') and ('69', '66') is one key, I wanna keep only one and add the value of those two keys, above is a very simple example: here is the (failed) code: for k, v in pairs.items(): if str(k)[1]+str(k)[0] in pairs.keys(): print(pairs[str(k)[1]+str(k)[0]]) pairs[k]+=pairs[str(k)[1]+str( k)[0]] del pairs[str(k)[1]+str(k)[0]] print(v,k) Thanks for any advice, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor pairs.items() is fine if it's a small dictionary but for larger ones it's going to slow things down as it generates the entire list of items before you continue, rather use .iteritems() as it creates an iterator which only yields one item at a time making it more efficient. str(k)[1]+str(k)[0] is string concatenation so your first key tested is '6669' and not ('66', '69') as you intended, you would have to create a new tuple to get the key you wanted like `if (k[1], k[0]) in pairs.keys():`. Also, your check to in pairs.keys() is wasteful as you generate a new list of keys for every key and you will be better off using `in pairs:` directly as it performs a dictionary lookup to test if the key exists. With that in mind, this is how I would re-write that code segment. YMMV for key in pairs.iterkeys(): # The [::-1] creates a reverse of the iterable so ('66', '69') will be ('69', '66') $ python3 dehydron_data_stastic.py | sort -nr Traceback (most recent call last): File dehydron_data_stastic.py, line 44, inmodule for k in pairs.iterkeys(): AttributeError: 'dict' object has no attribute 'iterkeys' if key[::-1] in pairs: try: # The first instance of the pair gets kept and the reversed gets added pairs[key] += pairs[key[::-1]] del pairs[::-1] except KeyError: print Key ('%s', '%s') already accumulated) % key Hope that helps. -- Christian Witts Python Developer Ah, should have mentioned .iterkeys() / .itervalues() are in Python 2.x and .keys() and .values() have been changed in Py3 to match .iter* from Py2.x. Just change that line to `for key in pairs.keys():` then. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3 dictionary questions
On 2011/11/23 03:04 PM, Cranky Frankie wrote: In playing around with Pyton 3 dictionaries I've come up with 2 questions 1) How are duplicate keys handled? For example: Qb_Dict = {Montana: [Joe, Montana, 415-123-4567, joe.mont...@gmail.com,Candlestick Park], Tarkington: [Fran, 651-321-7657, frank.tarking...@gmail.com, Metropolitan Stadidum], Namath: [Joe, 212-222-, joe.nam...@gmail.com, Shea Stadium], Elway: [John, 303-9876-333, john.el...@gmai.com, Mile High Stadium], Elway: [Ed, 303-9876-333, john.el...@gmai.com, Mile High Stadium], Manning: [Archie,504-888-1234, archie.mann...@gmail.com, Louisiana Superdome], Staubach: [Roger,214-765-8989, roger.staub...@gmail.com, Cowboy Stadium]} print(Qb_Dict[Elway],\n)# print a dictionary entry In the above the wrong Elway entry, the second one, where the first name is Ed, is getting printed. I just added that second Elway row to see how it would handle duplicates and the results are interesting, to say the least. 2) Is there a way to print out the actual value of the key, like Montana would be 0, Tarkington would be 1, etc? A dictionary is simply a Key:Value store and keys are unique. You're overwriting your first Elway entry with the second one when it's being captured. If you want to keep duplicate key values you'll need to re-look at what data structure you want to use, you can keep using a dictionary but then you'll need to change the value side of it perhaps like `{key: {key: value, key: value}}` so you end up with `{'Elway': {'John': [tel_num, email, home_ground], 'Ed': [tel_num, email, home_ground]}}` or some other implementation specific to your requirements. As for your second question, the value of the key is a hash. So to get the value, you'll need to find what hashing algorithm is used by default for dictionaries and use that to get the value of it yourself. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to get module name from ImportError
On 2011/11/21 07:54 AM, nikunj.badja...@emc.com wrote: Hi All, Please look at the following snippet. {{{ # User defined modules try: from scripts import precheck from scripts import validate from scripts import constants except ImportError: print(ERROR: One of the modules (..scripts/precheck.py, validate.py, constants) is not present.) print(INFO : Please verify the above modules, and restart the installation) sys.exit(1) }}} See the red line. I want to get the name of the particular module which is not available and hence causing ImportError. One of the ways can be to get the STDERR and process it using re. !? Is there a better alternate available .? Thanks Nikunj ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor try: ... import nothing ... except ImportError, err_msg: ... print err_msg ... No module named nothing Hope that helps. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A recursion question
On 2011/11/18 03:16 PM, Kĩnũthia Mũchane wrote: Hi, I am trying to do something which is really stupid :-) I would like to count the number of occurrences of a certain character in a list. This is more of an exercise in recursion rather than the underlying problem. I could have used a *for* loop or simply the list *count* method. Here is the code: class Find_Ex(): count = 0 def slais(self, lst, x): if len(lst) == 0: #if list is empty just give a -1 return -1 elif lst[0] == x: Find_Ex.count += 1 # we have found 'x', increment class attribute 'count' by 1 Find_Ex.slais(self,lst[1:], x)# slice the list and go to the next element else: Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to the next element return Find_Ex.count s = Find_Ex() lst = [4,4,4,5,6,7,4,7,7,4] x = 4 print There are %d occurrences of %d%(s.slais(lst, x),x) It works as advertised but I am convincing myself that it should not! :-) If the list is empty, which is the base case, s.slais([], 4) returns -1. Now using some bush logic, in a non-empty list, in order for the recursion to terminate it has to 'hit' the base case and return -1. Where does this -1 go ? Further, why do not I get a *TypeError* when I use a simple *return* statement in the *if* clause? The reason I am asking that is that I think(wrongly, of course :-)) it should be part of the answer and therefore I should be getting an answer that is off by one or a *TypeError*!! And by the way, the reason I used a *class* was that I could not get a suitable place in the program to initialise my *count* variable otherwise. Thanks... If you pop in some print statements you can see what's happening a bit easier. You are creating a stack of functions which each return their values but in a LIFO fashion (Last In, First Out) so you can see the first return is -1 as you expected to happen when the list is exhausted, and then each subsequent return is the count which is why you get the correct return value in the end. Also, why do you think you should get a TypeError when you `return -1` ? class Find_Ex(): count = 0 def slais(self, lst, x): print lst if len(lst) == 0: #if list is empty just give a -1 print 'Returning -1' return -1 elif lst[0] == x: print 'Incrementing Count' Find_Ex.count += 1 # we have found 'x', increment class attribute 'count' by 1 Find_Ex.slais(self,lst[1:], x)# slice the list and go to the next element else: print 'Nothing Found' Find_Ex.slais(self,lst[1:], x)#'x' not found so we move to the next element print 'Returning the count' return Find_Ex.count s = Find_Ex() lst = [4,4,4,5,6,7,4,7,7,4] x = 4 print There are %d occurrences of %d%(s.slais(lst, x),x) [4, 4, 4, 5, 6, 7, 4, 7, 7, 4] Incrementing Count [4, 4, 5, 6, 7, 4, 7, 7, 4] Incrementing Count [4, 5, 6, 7, 4, 7, 7, 4] Incrementing Count [5, 6, 7, 4, 7, 7, 4] Nothing Found [6, 7, 4, 7, 7, 4] Nothing Found [7, 4, 7, 7, 4] Nothing Found [4, 7, 7, 4] Incrementing Count [7, 7, 4] Nothing Found [7, 4] Nothing Found [4] Incrementing Count [] Returning -1 Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count Returning the count There are 5 occurrences of 4 -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On 2011/11/17 11:59 AM, lina wrote: list1 [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight={} weight{list1[0]}=1 SyntaxError: invalid syntax weight[list1[0]]=1 Traceback (most recent call last): File pyshell#292, line 1, inmodule weight[list1[0]]=1 TypeError: unhashable type: 'list' I wonder how to count the occurence of the list of lists. Thanks, ^_^ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor sum(1 if type(elem) == list else 0 for elem in list1) not work for you if all you want to do is count how many lists you have in your main list ? -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On 2011/11/17 12:26 PM, lina wrote: On Thu, Nov 17, 2011 at 6:09 PM, Christian Wittscwi...@compuscan.co.za wrote: On 2011/11/17 11:59 AM, lina wrote: list1 [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight={} weight{list1[0]}=1 SyntaxError: invalid syntax weight[list1[0]]=1 Traceback (most recent call last): File pyshell#292, line 1, inmodule weight[list1[0]]=1 TypeError: unhashable type: 'list' I wonder how to count the occurence of the list of lists. Thanks, ^_^ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor sum(1 if type(elem) == list else 0 for elem in list1) not work for you if all you want to do is count how many lists you have in your main list ? not count how many sublists in the main list. wanna count the occurence of the sublists, I mean, something like dictionary[list1[1]]=occurence Traceback (most recent call last): File pyshell#298, line 1, inmodule dictionary[list1[1]]=1 TypeError: unhashable type: 'list' dictionary[list1[1]]=1 Traceback (most recent call last): File pyshell#298, line 1, inmodule dictionary[list1[1]]=1 TypeError: unhashable type: 'list' For that you'll need to convert your list to a hash-able type if you want to use dictionaries for your store, easiest would probably to use the string representation for it so you could do list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight = {} for elem in list1: ... if elem.__repr__() in weight: ... weight[elem.__repr__()] += 1 ... else: ... weight[elem.__repr__()] = 1 ... weight {['34', '58', '34', '58']: 1, ['61', '70', '61', '34']: 1, ['61', '34', '61 ', '34']: 1, ['61', '35', '61', '70', '61']: 1} or from collections import defaultdict list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '7 0', '61', '34'], ['34', '58', '34', '58']] weight = defaultdict(int) for elem in list1: ... weight[elem.__repr__()] += 1 ... weight defaultdict(type 'int', {['34', '58', '34', '58']: 1, ['61', '70', '61', '34']: 1, ['61', '34', '61', '34']: 1, ['61', '35', '61', '70', '61']: 1}) Hope that helps. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to understand unhashable type: 'list'
On 2011/11/17 03:56 PM, lina wrote: snip ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor sum(1 if type(elem) == list else 0 for elem in list1) not work for you if all you want to do is count how many lists you have in your main list ? not count how many sublists in the main list. wanna count the occurence of the sublists, I mean, something like dictionary[list1[1]]=occurence Traceback (most recent call last): File pyshell#298, line 1, inmodule dictionary[list1[1]]=1 TypeError: unhashable type: 'list' dictionary[list1[1]]=1 Traceback (most recent call last): File pyshell#298, line 1, inmodule dictionary[list1[1]]=1 TypeError: unhashable type: 'list' For that you'll need to convert your list to a hash-able type if you want to use dictionaries for your store, easiest would probably to use the string representation for it so you could do list1 = [['61', '34', '61', '34'], ['61', '35', '61', '70', '61'], ['61', '70', '61', '34'], ['34', '58', '34', '58']] weight = {} for elem in list1: ... if elem.__repr__() in weight: This is cool. May I ask which role the __repr__ plays here? __repr__ is the string representation of a Python object [1] so I'm using it to create something that is hash-able to be used as the dictionary key value. [1] http://docs.python.org/library/functions.html#repr -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Okay, this time I tried doing a little research but no luck in solving this one.
On 2011/11/11 04:00 AM, Nathaniel Trujillo wrote: Okay, I typed in python -c import sys; print sys.version at the command prompt. I didn't see a prompt ending with %. Instead I saw a prompt ending with . But here is the message I got. Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\net2010python -c import sys; print sys.version 'python' is not recognized as an internal or external command, operable program or batch file. C:\Users\net2010 Thanks for the help. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor R-Click on My Computer - Properties - Advanced - Environment Variables - Under System Variables find PATH, select it, and click Edit - Add your Python path to the end eg. c:\python27 (you will need to seperate it from all the other entries using a semi-colon, like c:\program files;c:\windows;c:\python27) - Click OK about 3 times till you've closed all the windows - Open a new Command Prompt and run python -c import sys; print sys.version -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] positional output
On 2011/11/11 02:59 PM, Cranky Frankie wrote: Thank you for your help on this. Now for the rest of the story. I'm trying to build a script to parse IBM AIX DB2 DDL to line up the data types (it drives me crazy when the column data types are not lined up). For example, typical create table DDL might be hundreds of lines long but will look like this: SNIP Something like this ? I left out checking for valid types etc, just something rudimentary to maybe point you in the right direction. a = COLUMN1 DECIMAL(8), ... COLUMN2 CHAR(20), ... COLUMN3TIMESTAMP, ... COLUMN4 INTEGER, ... COLUMN5 DATE NOT NULL WITH DEFAULT, ... COLUMN6 CHAR(40) ... for line in a.splitlines(): ... newline = line.split() ... col_name = newline[0] ... col_type = newline[1].replace(',', '') ... field_sep = ',' if ',' in line else '' ... print '%-40s%s%s' % (col_name, col_type, field_sep) ... COLUMN1 DECIMAL(8), COLUMN2 CHAR(20), COLUMN3 TIMESTAMP, COLUMN4 INTEGER, COLUMN5 DATE, COLUMN6 CHAR(40) If all you want to space it out nicely then .split(' ', 1) and '%-40s%s' % (part1, part2) should work fine for you. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to remove the coming duplication
On 2011/11/10 09:10 AM, lina wrote: Hi, How to remove the coming duplication, Here I wrote one (not working): a=['2', '5', '7', '5', '5'] for i in range(len(a)-1): if a[i+1]==a[i]: a.remove(a[i+1]) if i not in range(len(a)): break a ['2', '7', '5', '5'] I wish to get a is [2,5,7,5] just remove the coming duplication, not unique the list. Thanks for any advice, Best regards, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor def remove_coming_duplication(a_list): return [element for idx, element in enumerate(a_list) if element != a_list[idx-1]] remove_coming_duplication([2, 5, 7, 5, 5]) [2, 5, 7, 5] remove_coming_duplication([2, 5, 7, 5, 5, 5, 5, 5, 7, 7, 5]) [2, 5, 7, 5, 7, 5] remove_coming_duplication(['2', '5', '7', '5', '5']) ['2', '5', '7', '5'] With this you're simply iterating through the list and checking if the current element in the list is not equal to the previous element, and if so it is not a duplicate and will be added to the new list you're creating. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 2.7 on Ubuntu 11.10 - Do not unintall
On 2011/11/02 08:26 AM, spa...@gmail.com wrote: Shouldn't this be treated as a bug then? As a user I should be allowed to uninstall the software I want to. Or you uninstalled other things by mistake? On Wed, Nov 2, 2011 at 6:18 AM, Joel Montes de Oca joelmonte...@gmail.com mailto:joelmonte...@gmail.com wrote: On Tue 01 Nov 2011 08:56:41 PM EDT, Max gmail wrote: Heh, yeah. It's usually a bad idea to do stuff like that (I know a guy (Windows) who deleted his OS of his system). On Nov 1, 2011, at 7:40 PM, Joel Montes de Oca wrote: I just discovered that it is a bad idea to complete uninstall Python 2.7 on Ubuntu 11.10. If you do, expect a lot of things not to work, mainly your system. haha I just reinstalled Python 2.7 and I hope things are not so bad now when I reboot. -- -Joel M. ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Yea, It wiped out GNOME and UNITY along with a few other applications. It wasn't a big deal tho, I just reinstalled ubuntu-desktop threw apt-get. :) -- -Joel M. ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- http://spawgi.wordpress.com We can do it and do it better. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor It's not a bug. Ubuntu requires Python to be installed for a number of it's applications to run, and uninstalling Python will cause them to stop working. You could argue that then they should maintain a seperate install of Python to handle their core applications, but that would go against the grain of how package management is performed and how releases would need to be packaged etc. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] assign all parameters of __init__ to class variables?
On 2011/11/02 03:15 PM, Alex Hall wrote: Hi all, I have a class which takes a large number of optional arguments for its __init__. Instead of going through every single one and assigning it to self.[name], is there some quick way to take all the parameters of the constructor and assign them all to self.[name] in one step? class Test(object): def __init__(self, param1, param2, param2, **kw): self.__dict__.update(locals()) self.__dict__.update(kw) I do prefer assignment by hand, just feels nicer especially when looking at it in the future. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to calculate execution time and complexity
On 2011/10/28 07:38 AM, Praveen Singh wrote: splitWord('google', 2) ['go', 'og', 'le'] splitWord('google', 3) ['goo', 'gle'] splitWord('apple', 1) ['a', 'p', 'p', 'l', 'e'] splitWord('apple', 4) ['appl', 'e'] def splitWord(word, number): length=len(word) list1=[] x=0 increment=number while number=length+increment: list1.append(word[x:number]) x=x+increment number=number+increment for d in list1: if d=='': list1.remove('') return list1 I am getting the desired output and this code is working fine..but i think it is quite bulky for this small operation. qus.1-- can you guys suggest me some better solution?? qus 2-- i know writing just a piece of code is not going to help me. i have to write efficient code.i want to know how to calculate execution time of my code and can you guys suggest me some links so that i can learn how to find complexity of code?? Thanks in advance... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Below [1] is how I would write it, which is simply a re-factoring of your code so it's cleaner and more compact. For calculating execution time you can use the `timeit` module [2] and for more in-depth analysis you can look at `profile` [3] and further to the bare-bones `dis` [4]. [1] def splitWord(word, number): ... x = [] ... for y in xrange(0, len(word), number): ... x.append(word[y:y+number]) ... return x ... splitWord('google', 1) ['g', 'o', 'o', 'g', 'l', 'e'] splitWord('google', 2) ['go', 'og', 'le'] splitWord('google', 3) ['goo', 'gle'] splitWord('google', 4) ['goog', 'le'] splitWord('google', 5) ['googl', 'e'] splitWord('google', 6) ['google'] splitWord('google', 7) ['google'] [2] http://www.doughellmann.com/PyMOTW/timeit/ [3] http://www.doughellmann.com/PyMOTW/profile/index.html#module-profile [4] http://www.doughellmann.com/PyMOTW/dis/ -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] changing dictionary to lowercase
On 2011/10/28 11:51 AM, Albert-Jan Roskam wrote: It would be nice to generalize the solution so it could also handle definitions={Deprecated: No longer in use, DEPRECATED: No longer in use} These are unique now, but after turning them into lower case not anymore. new_d = {} for d in definitions: try: new_d[d.lower()].append(definitions[d]) except TypeError: new_d[d.lower()] = [definitions[d]] Cheers!! Albert-Jan snip ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor To save yourself the try/except you can use defaultdict which is part of the collections module. from collections import defaultdict new_d = defaultdict(list) for key, value in definitions.iteritems(): new_d[key.lower()].append(value) -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] functions and default argument
On 2011/10/21 03:00 PM, Praveen Singh wrote: In function- Default value is *evaluated only once*.This makes different when the default is a mutable object such as a list, dictionary or instance of most classes. I am not getting it properly-evaluated once?? different behaviour???-- please explain this. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Mutable defaults for function/method arguments is a Python Gotcha, you can find a good read here [1]. It's a better read than how I would explain it. [1] http://www.ferg.org/projects/python_gotchas.html#contents_item_6 -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] logging question
On 2011/10/19 09:19 PM, Alex Hall wrote: Hi all, I have never done logging before, and I am wondering how it will change my script. Currently, I have something like this: for book in results: try: checkForErrors(book) except Exception, e: print e continue That way I see any errors in a given book, but that book is skipped and the loop continues. Now, though, checkForErrors() logs exceptions instead of raising them, so my try/except won't work, right? There is my question: if a method logs an exception instead of raising it, is that exception still raised by the logging module? Do I have to make checkForErrors() return something, and check for that, instead of using try/except or can I keep my loop how it is? TIA! If you have some exception handling and want it to propagate further up the chain you can just raise it, for eg. def checkForErrors(book): try: do_something_that_could_raise_exceptions() except Exception, e: log_errors(e) raise for book in results: try: checkForErrors(book) except Exception, e: do_your_other_exception_handling() -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calling Python Functions from Powershell scripts
On 2011/10/05 09:32 AM, Nikunj Badjatya wrote: Howdy All, To give an overview of the problem, I have an installer. It is used to install virtual machines at specific location. The installer is written in Powershell and Python. The topmost script is in Python ( install.py ) which internally calls other .py and .PS1 ( powershell ) scripts using popen() . I am working on having a file based logging mechanism for this installer. i.e both for .py and .PS1 scripts. Q1. I want to use python logging module. But then how do I integrate it with powershell scripts. ? One option would be to write into a .log file using logging module in all .py scripts. Use that ( .log ) file in powershell scripts by using its own logging module ( dnt knw if it exists ! ) Q2. Can we call / run .py from inside .PS1. ? Please suggest suitable methods for effective logging mechanism. Thanks Nikunj Bangalore ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor PowerShell has built-in cmdlets for logging that use the verb write. Running the command get-command write* will list those commands for you (and a couple of other ones). Each one is controlled by a shell variable that ends with Preference. For example, to turn the warning messages up, then set the variable $WarningPreference to Continue. Other options are Stop, Inquire, and SilentlyContinue. To turn down logging, set each of the $*Preference session variables to SilentlyContinue. To turn up logging, then set them all to Continue. Here are some references for automatic logging [1] and a script template with a logging function [2] [1] http://jdhitsolutions.com/blog/2011/03/powershell-automatic-logging/ [2] http://powershell.com/cs/media/p/3950.aspx -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] guess age programme (please help)
On 2011/09/30 02:04 PM, ADRIAN KELLY wrote: Hi all, can anyone help me with the attached programme. it is fairly basic (like me) i want it to ask the user to guess the age and countdown when making incorrect guesses. it doesn't seem to count the first attempt (run it and see please). i also want to know how to go about setting a condition so that when the guesses = 0, the programme closes or stops etc. any advice would be very grateful (particularly the correct code) i am learning if's and loops so please keep explanations as simple as possible. i really appreciate everyones help adrian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Your program does count the first guess, but you print out the remaining number of tries before you subtract the attempt from your counter so if you move your `tries=tries-1` up before your if statements it will reflect the correct number of attempts left to the user. I would suggest changing your while loop to read `while tries 0:` so it exits when you've exhausted your attempts. You also do not test for equality of your age and the guess in your if statements so if the user guesses the correct age it will tell them that the number is higher. And if the user guesses the correct number you should `break` from the loop else it will carry on going till the number of attempts have been exhausted. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] last part of my programme
On 2011/09/29 11:05 AM, ADRIAN KELLY wrote: can anyone tell me why the last part of my programme wont work. i want the user to have to press enter to exit but it doesn't happen through the python interface. the programme works fine otherwise but just shuts down when finished thanks all adrian ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You should run this from the command line to see the errors and tracebacks. You have a `firstname` and `lastname` variable, no `name` variable. Traceback (most recent call last): File py_tutor.py, line 34, in module STATS() File py_tutor.py, line 26, in STATS details=name+\n+town+\n+county NameError: global name 'name' is not defined Once you fix that with something like `name = firstname + ' ' + lastname` you'll get a further error Press the enter key to exit. Traceback (most recent call last): File py_tutor.py, line 39, in module _ = input(\n\nPress the enter key to exit. ) File string, line 0 Which is because input() converts the input to an integer so you would need to type for eg 0 then enter for it to exit without failing. Changing that to raw_input() like the rest of your inputs will fix that. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How it is better than java
On 2011/09/19 03:27 PM, Ashish Gaonker wrote: My obvious thinking is : Java being compiled language , must be faster then a interpreted language. I know couple of points : Development time is less + easy to learn + python is expressive. Can you share some more especially as compared to Java / .net (two primarily used languages in enterprise language web based applications) -- Thanks Regards Ashish Gaonker ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I would suggest reading `Python is not Java` [1] and `Java is not Python, either` [2], old but good reads. And then ask what is your focus for development. Better is extremely subjective and can be liable to induce flame-wars, although this list is quite friendly. To me, I started using Python as a glue language, controlling process flows and the like, with still heavy uses of C and PL/SQL for what I do. Over time Python has taken center-stage for my projects due to ease-of-use and rapid application development and only moving time critical work that needs to be faster to C but in most cases that is not needed for me anymore. Add to that the great work on PyPy [3] which is extremely efficient, I hardly ever have to write in another language if I don't wish. [1] http://dirtsimple.org/2004/12/python-is-not-java.html [2] http://dirtsimple.org/2004/12/java-is-not-python-either.html [3] http://pypy.org/ -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What's the keyword for the Python creed?
On 2011/09/15 08:57 PM, Richard D. Moores wrote: Thanks, all. Good to have that at hand. antigravity: any more? Dick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor from __future__ import braces :) -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] _init_() arguments
On 2011/09/09 12:10 PM, Stu Rocksan wrote: I have a very basic question that I am sure has a simple answer. I would be very appreciative of anyone that would set me straight. Python 2.7.2 I am simply trying to pass arguments. Based on the documentation that I've read so far _init_() is called upon instance creation and the arguments are those passed to the class constructor expression. That all makes sense to me but the problem is when I try to actually pass the argument. I get an TypeError that states This constructor takes no arguments. Even using code direct from the tutorials included in the documentation gives me the same error. I doubt that there would be bad code coming direct from the official website...right? So the problem must be me. Example: class Complex: def _init_(self, realpart, imagpart) self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) x.r, x.i # theoretical output (3.0, -4.5) This is taken direct from the tutorial included in the documentation dated September 8, 2011. If you try to run this you will get a TypeError: this constructor takes no arguments. It even says in the explanation before this code: Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). I've tried similar code from other beginner Python books and I get the exact same result. I am sure that I am missing something simple. Thanks in advance ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor __init__() has 2 underscores pre- and post-fixed. Your example will break because of that, and also you're missing a colon at the end of your `def` line. Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... x = Complex(3.0, -4.5) x.r, x.i (3.0, -4.5) class Complex2: ... def _init_(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... x= Complex2(3.0, -4.5) Traceback (most recent call last): File stdin, line 1, in module TypeError: this constructor takes no arguments -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need advice about a dictionary ({})
On 2011/09/08 12:58 PM, Richard D. Moores wrote: I've succeeded in writing a dictionary ({}) that I can use as a small personal phone book. The dictionary (very shortened and simplified) looks like this in the script; p = {} p['bp1'] = 'xxx' p['bp2'] = 'ooo' p['ch'] = 'zzz' p['me'] = 'aaa' p['mg'] = 'vvv' p['pu1'] = 'bbb' p['pu2'] = 'ccc' p['pw'] = 'kkk' I have a function that enables the user to enter 'bp', for example, and return both 'xxx' and 'ooo'. (The keys are initials; I've disguised the values, each of which of course are name, home number, mobile number, speed dial number, etc.) But I'd like to put the lines of the dictionary in a text file so that I can add key/value items to it by writing to it with another script. I think I can do that, but I need some hints about how to get the script to access the text file in a way that lets the user look up a phone number. I'm thinking that the script needs to recreate the dictionary each time it's called, but I don't know how to do that. Thanks, Dick Moores ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You could pickle your dictionary object which will give you the persistence and then when your script starts up you can unpickle the file if it exists else create a new one. Of course if you make any changes to your object you'll need to pickle it once your app finishes otherwise new changes won't be written out. With just a plain text file you can also just grep the info out $ cat test.file bp1:xxx|yyy bp2:ooo|ppp ch:zzz|asf me:agkjh|agjh $ grep -i ^bp* test.file bp1:xxx|yyy bp2:ooo|ppp $ grep -i ^BP* test.file bp1:xxx|yyy bp2:ooo|ppp -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation if command worked
On 2011/08/25 07:51 AM, Johan Geldenhuys wrote: Hi all, I have the following code that uses pexpect to execute a system command. My problem is, I don't know how to identify if the command was successfully executed. The code works as it is to execute the SCP command, but it executes regardless if the SCP session can actually connect to something. Thanks def doScp(files): logger.log(Files to get: + `files`) fNames = ' '.join(files) cmd = 'scp %s %s@%s:%s%s' % (fNames, SCP_USERNAME, SCP_HOST, SCP_IMG_FILE_DIR, SCP_IMG_FILE_PATH) logger.log(Sending: + cmd) child = pexpect.spawn(cmd) i = child.expect(['assword:', 'yes/no'], timeout=30) if i == 0: child.sendline(SCP_PASSWD) elif i == 1: child.sendline(yes) child.expect(assword:, timeout=30) child.sendline(SCP_PASSWD) data = child.read() if data != None: success = True else: success = False child.close() logger.log(Files sent to SCP host) return success ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Once you call child.close() the exit and signal status will be stored in .exitstatus and .signalstatus, for a normal exit of the program .exitstatus will store the return code from SCP as per [1] [2] [3] and .signalstatus will be None. If SCP was terminated with a signal then .exitstatus will be None and .signalstatus will contain the signal value. Info found in the docs [4]. So the changes to your code will be: snip data = child.read() child.close() if child.exitstatus and child.exitstatus == 0: success = True else: success = False snip I'll leave putting in handling of failed error codes and abnormal termination to you. [1] http://support.attachmate.com/techdocs/2116.html [2] http://support.attachmate.com/techdocs/2487.html [3] http://support.attachmate.com/techdocs/2285.html [4] http://pexpect.sourceforge.net/pexpect.html -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Confirmation if command worked
On 2011/08/25 10:19 AM, Alan Gauld wrote: On 25/08/11 07:25, Christian Witts wrote: Once you call child.close() the exit and signal status will be stored in .exitstatus and .signalstatus, for a normal exit of the program .exitstatus will store the return code from SCP as per [1] [2] [3] and .signalstatus will be None. If SCP was terminated with a signal then .exitstatus will be None and .signalstatus will contain the signal value. Info found in the docs [4]. data = child.read() child.close() if child.exitstatus and child.exitstatus == 0: success = True else: success = False Won't that if statement always evaluate to false? If exitstatus is 0 the first part of the and will be false and so the entire and expression is false. If exitstatus is not 0 then the second part of the and will be false and again the and result will be false. Did you mean to use exitstatus for both tests? Or am I missing something subtle here? Good catch, it should be `if child.exitstatus != None and child.exitstatus == 0:` or removing the first part entirely. The zero-evaluating-as-False has bitten me before and for some reason I still on occasion forget it even though I use it often for data extracts. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using Python to send signals to the USB port
On 2011/08/17 03:28 PM, Jaidev Deshpande wrote: Hi Is there some way I can use Python to send data through a USB port and control the data in real-time? (For instance, I can make a sinusoidal wave of a given specification, and visualize it using NumPy / Matplotlib. How can I send the digitized form of this array through a USB port, and then convert it back into analog so I can view it on an oscilloscope?) Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Possibly look at the PyUSB module [1] and a tutorial on it [2]. Hopefully that helps and is enough for you. [1] http://sourceforge.net/apps/trac/pyusb/ [2] http://pyusb.sourceforge.net/docs/1.0/tutorial.html -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Adding index numbers to tuple
On 2011/08/16 03:10 PM, Timo wrote: Hello, Maybe a bit confusing topic title, probably the example will do. I have a tuple: t = ('a', 'b', 'c', 'd') And need the following output, list or tuple, doesn't matter: (0, 'a', 1, 'b', 2, 'c', 3, 'd') I tried with zip(), but get a list of tuples, which isn't the desired output. Anyone with a solution or push in the right direction? Cheers, TImo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor t = ('a', 'b', 'c', 'd') new_t = zip(xrange(len(t)), t) new_t [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] from itertools import chain list(chain.from_iterable(new_t)) [0, 'a', 1, 'b', 2, 'c', 3, 'd'] That would be for if you were using the zip way, but enumerate should be simpler as Martin pointed out. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Object designer applications - are there any?
On 2011/08/05 01:01 PM, Flynn, Stephen (L P - IT) wrote: snip It struck me that if I write a read in Sybase DDL and spit out Oracle DDL routine and so forth, I'd get a lot of reuse out of it. However, I've not done much OOP at all and consequently, my object design skills are somewhat non-existent. Whilst I have a rough idea of what my properties my table object will have I was looking for something to help me design it - something which I can say this is a table object, it has a name and multiple columns. Columns have a type, a width (which may be further comprised of scale and precision or just an integer depending on the column type) and a nullable flag.). Oh, and there may be multiple columns... so maybe a column should be an object too... etc. Anyone know if there are any such kinds of programs out there already (freeware please - I'll be doing this off my own back so funds are tight for commercial software). Failing that, does anyone use something for this kind of thing already, Visio maybe or a spreadsheet. Maybe just notepad or a post-it? snip You could take a look at SQLAlchemy [1] and possibly the migrate [2] portion of it for schema management. It supports connectivity for both Sybase and Oracle as well as being able to generate the DDL [3] [1] http://www.sqlalchemy.org/docs/ [2] http://packages.python.org/sqlalchemy-migrate/versioning.html#experimental-commands [3] http://www.sqlalchemy.org/trac/wiki/FAQ#HowcanIgettheCREATETABLEDROPTABLEoutputasastring -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python scripts into executable Windows programss
On 2011/08/03 06:25 AM, Emeka wrote: Hello All, I would want to convert Python scripts into executable Windows programs. I have already checked out py2exe, it seems like they support only Python 2.5. Mine is Python 2.7.7. Could anyone here help me out on this issue? ? Regards, Emeka -- /Satajanus Nig. Ltd / ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor They do have support for Python 2.7, it's just the latest version on SF is listed as Py2.5 64bit. http://sourceforge.net/projects/py2exe/files/py2exe/0.6.9/ -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I learn python for web development
On 2011/07/31 10:22 PM, abdulhakim haliru wrote: Hi guys, I am really interested in switching from PHP to python but there don't appear to be a book for such. Can anyone advice me please. Abdulhakim. Sent from my BlackBerry wireless device from MTN You can try Python 3 Web Development Beginner's Guide http://www.packtpub.com/python-3-web-development-beginners-guide/book It's Python 3.x, CherryPy, jQuery, jQuery UI -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Limit raw_input to hundredth decimal point
On 2011/07/01 09:30 AM, Ryan Kirk wrote: Is there a way to limit raw_input to the hundredth decimal point? For example, I'd like to allow the user to enter 5.75 but not 5.756: dollars = raw_input(Please enter a dollar amount: $) Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you're using Windows you can use the msvcrt module which has an implementation of getch() which gets 1 character at a time. Then you would just scan your input 1 character at a time and as soon as a the `.` is used you can limit it to 2 further key-strokes before you ban input and carry on in your process flow. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] set the BETWEEN range in the SQL query using the python datetime function
On 2011/06/24 01:19 PM, Norman Khine wrote: thank you, it was simpler than what i was trying to do, here is the revised version: http://pastie.org/2115586 one thing i am getting an error is on like 103, in that if, i change (http://pastie.org/2115615): -plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - GBP', 'Commission - %s GBP' % (total_commission)), +plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s GBP', 'Commission - %s GBP' % (total_adwords, total_commission)), 'upper right', shadow=True) i get the following traceback: Traceback (most recent call last): File commission.py, line 119, inmodule plt.legend(('Income - GBP', 'Discounts', 'Google AdWords - %s GBP', 'Commission - %s GBP' % (total_adwords, total_commission)), TypeError: not all arguments converted during string formatting what am i missing? thanks norman You've got 'Google AdWords - %s GBP' with no arguments and 'Commission - %s GBP' with 2 arguments. -- Christian Witts Python Developer // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] floats
On 2011/06/07 04:43 AM, Michael bridges wrote: i saw it somewhere, but where? i want to 10 / 1000 and get 0.01 not 0 if 1000 is made 1000.00 then 0.01 is printed but that gives 500 / 1000.00 is 0.5 not 0.50 i might be thinking C# not python. can someone till me how to get a two decimal precision every time? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor 100/1000 0 from __future__ import division 100/1000 0.1 100//1000 0 So you can still get the old behaving floor division using double divisors and any normal syntax will be true division. In Python 3.x it's already the standard, this is only necessary for Python 2.x -- Christian Witts // ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python scripting using ./
On 2011/05/24 03:10 PM, Hank Wilkinson wrote: I am trying to do script in python using ./ Here is a session showing bad interpreter: No such file or directory Is this a python question/problem? Last login: Sat May 21 14:22:49 on ttys000 John-Wilkinsons-iMac:~ wilkinson$ cd /Users/wilkinson/Documents/py32/p31summerfield John-Wilkinsons-iMac:p31summerfield wilkinson$ pwd /Users/wilkinson/Documents/py32/p31summerfield John-Wilkinsons-iMac:p31summerfield wilkinson$ ls hello.py hello.py John-Wilkinsons-iMac:p31summerfield wilkinson$ python hello.py Hello World! John-Wilkinsons-iMac:p31summerfield wilkinson$ chmod +X hello.py John-Wilkinsons-iMac:p31summerfield wilkinson$ ./hello.py -bash: ./hello.py: /usr/local/bin/python3.1^M: bad interpreter: No such file or directory John-Wilkinsons-iMac:p31summerfield wilkinson$ echo $PATH /opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin John-Wilkinsons-iMac:p31summerfield wilkinson$ cat hello.py #!/usr/local/bin/python3.1 print(Hello, World!) John-Wilkinsons-iMac:p31summerfield wilkinson$ python Python 3.1.2 (r312:79147, Mar 20 2011, 17:15:01) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type help, copyright, credits or license for more information. import sys sys.path ['', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python31.zip', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/plat-darwin', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/lib-dynload', '/opt/local/Library/Frameworks/Python.framework/Versions/3.1/lib/python3.1/site-packages'] Thank you. Hank ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Where is the python binary actually located ? You can check with `which python` to find the location, mine was always /usr/bin/python with *nix, can't say off-hand the location with Mac. -- Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is `if __name__ == __main__` for?
On 2011/05/20 01:09 PM, Ganesh Kumar wrote: Hi Gurus, I am new python programming.. I see many programs if __name__ == '__main__': when I check __name__ always eq __main__. what purpose use these structure.. please guide me.. -Ganesh If you execute the script directly ie. python script.py the __name__ will be __main__ but if you import it it's the name of the file. #first.py print __name__ #second.py import first $ python first.py __main__ $ python second.py first -- Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What is `if __name__ == __main__` for?
On 2011/05/20 01:29 PM, Christian Witts wrote: On 2011/05/20 01:09 PM, Ganesh Kumar wrote: Hi Gurus, I am new python programming.. I see many programs if __name__ == '__main__': when I check __name__ always eq __main__. what purpose use these structure.. please guide me.. -Ganesh If you execute the script directly ie. python script.py the __name__ will be __main__ but if you import it it's the name of the file. #first.py print __name__ #second.py import first $ python first.py __main__ $ python second.py first Sorry, forgot to add before sending that the reason I use the `if __name__ == '__main__'` structure is so that I can have a standalone application that has it's defined entry point and then if I want to reuse functions in the application I can import it without having to worry that it will execute the entire thing. -- Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting a string
On 08/02/2011 11:20, tee chwee liong wrote: hi all, i have a function which returns a string. for eg: X='101110'. i want to search for 0 and highlight the location. i am thinking of defining X as a list. but how can i split 101110 as there are no spaces in between? i'm thinking if i can put it into a list: X=['1','0','1','1','1','0'], then i can use index to point out the locations of the 0. pls advise. i'm using Python2.5 and WinXP. thanks tcl ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor In Python strings are lists of characters so you can use indexes already. You can look at the .find() function to return you index numbers for the location of your search criteria, it only returns the first within your parameters, but you can create your own function utilising it to return all occurrences. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting a string
On 08/02/2011 15:04, tee chwee liong wrote: hi all, thanks for the advice. i modified my code to be: c=('01101') i=-1 try: while 1: i=c.index('0',i+1) print Lane fail,i except ValueError: print All Lanes PASS pass when i run, the result is: Lane fail 0 Lane fail 3 All Lanes PASS Question: How do i prevent the code from executing the except ValueError part. it seems to be checking bit by bit and when is see 1 it will execute the except part. i just want the results to be: Lane fail 0 Lane fail 3 thanks tcl76 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor `while i len(c)` instead of `while 1` -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Splitting a string
On 08/02/2011 15:38, David Hutto wrote: On Tue, Feb 8, 2011 at 8:36 AM, Christian Wittscwi...@compuscan.co.za wrote: On 08/02/2011 15:04, tee chwee liong wrote: hi all, thanks for the advice. i modified my code to be: c=('01101') i=-1 try: while 1: i=c.index('0',i+1) print Lane fail,i except ValueError: print All Lanes PASS pass when i run, the result is: Lane fail 0 Lane fail 3 All Lanes PASS Question: How do i prevent the code from executing the except ValueError part. it seems to be checking bit by bit and when is see 1 it will execute the except part. i just want the results to be: Lane fail 0 Lane fail 3 thanks tcl76 `while i len(c)` instead of `while 1` You remind me of me...like it was yesterday. Explanations with no thought. Unimpressive isn't it? While the index is smaller than the length of the string do your processing. It reads like that. But thank you for your commentary. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Convert an IP address from binary to decimal
On 18/01/2011 14:45, Tom Lin wrote: Hi guys, Please help me with this: Convert an IP address from binary string to decimal format.There are some preconditions: 1.IP address is in the form of '10010001100'.32 bits with no dot. 2.int(string, base) is not allowed, You have to implement the conversion . 3.Performance should be considered. For example an IP address like ' ' would be converted to '255.255.255.255' That's how I implement it. But I think it looks ugly and I wonder if there is a better way to do this. import re import sys def convert(bin_ip): patt = re.compile(r'\d{8}') bin_list = patt.findall(str(bin_ip)) dec_list = [] for bin in bin_list: sum = 0 i = 7 for n in bin: if int(n): sum = sum + 2**i i = i - 1 dec_list.append(str(sum)) dec_ip = '.'.join(dec_list) print dec_ip if __name__ == '__main__': bin_ip = sys.argv[1:] convert(bin_ip) Thanks in advance and excuse my poor English. Best regards, Tom ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If I knew the input to be perfect it would be a simple matter '.'.join((str(int(input_ip[x:x+8], 2)) for x in range(4))) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] turn a path into nested list
On 13/01/2011 14:33, ingo wrote: Dear all, a probably simple problem I can't get my head around at the moment (old age?), some input would be appreciated. I have a path path = 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/English.lproj' I'd like to turn taht into a list with a certain structure and order: [['Audio', 'Audio'], ['site-packages', ''Audio/site-packages'], ['pygame', 'Audio/site-packages/pygame'], ['examples', 'Audio/site-packages/pygame/examples'], ['macosx', ''Audio/site-packages/pygame/examples/macosx'], . . ] How to approach this? TIA, ingo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor First split your path into segments, then iterate over those segments and build your new list (item one being the current segment, and part two a joined string of previous segments). -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cx_Oracle help
On 05/01/2011 16:33, F1r3f1y wrote: This guide helped me a lot with cx_Oracle http://codingtutorials.co.uk/blog/?p=31 Greg Lindstrom-3 wrote: Hello, I'm trying to help out a friend and am stumped. Can you help me out? Thanks, --greg - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - I will briefly explain the problem I am facing. I am using Oracle 9.2, Python 2.5 and I installed cx_Oracle- 4.3.1-win32-9i-py25 in Python. From python I tried following : import cx_Oracle myDsn = cx_Oracle.makedsn('ISCN47',1521,'AUBDBS01') CONN = cx_Oracle.connect(myusr, mypwd, myDsn) Traceback (most recent call last): File pyshell#4, line 1, inmodule conn = cx_Oracle.Connection('scott','tiger',myDsn) RuntimeError: Unable to acquire Oracle environment handle I have set the below environment variables too NLS_LANG:snip.WE8MSWIN1252 ORACLE_HOME:D:\Tools\oracle\ora92 ORACLE_SID: AUBDBS01 PYTHON_HOME:d:\Utility\Python25 PYTHONPATH: %PYTHON_HOME%\lib;%PYTHON_HOME%\DLLs;%PYTHON_HOME%\Lib\site-packages;%ORACLE_HOME%\bin LD_LIBRARY_PATH: %LD_LIBRARY_PATH%;D:\Tools\oracle\ora92\lib Not getting any idea where I am wrong? Regards, Kishore ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor You need to install the Runtime, 3rd product option in the Oracle Universal Installer. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] doing maths on lists
On 20/12/2010 12:58, Chris Begert wrote: Bonjour I have three lists with 65 float items and would like to do the following sum: L0 = ([sum(L0A[i]*cos(L0B[i]+L0C[i]*JME) for i in range(0,64,1))]) So it just should do a sum across all the items in the list: L0A[0]*cos(L0B[0]+L0C[0]*JME)+ L0A[1]*cos(L0B[1]+L0C[1]*JME)+... + L0A[64]*cos(L0B[64]+L0C[64]*JME)= some float number However, I always get this error: TypeError: can't multiply sequence by non-int of type 'float' I looked it up and there seems to be some solution using either the for-in command or the map(int,...) command but I just can't get it to work Any help will be very much appreciated :) Greetings from Sydney Chris Surely it should be L0 = sum([(L0A[i]*cos(L0B[i]+L0C[i]*JME) for i in range(0, 64)]) as you want to generate the answers and then sum it up. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Grabbing Info from Text files?
On 12/11/2010 08:28, Michael Stover wrote: Hello, I have been getting lost when trying to find the needed information on how to grab information from text files to be used in a python script I am working on. Essentially the script is calling upon other programs to grab specific information about files and putting that information into basic text files. When I say basic I mean basic, each piece of information has its own line such as: InfoOne=? InfoTwo=? Where the ? is a value ranging from 1 character up to 5 (usually numbers), and it is the value I represented with ? that I need to grab. I am hoping it is possible to grab 1 line at a time so variables can be set for use later in my script. I have tried to decipher the python documents on this, but honestly, being a dabbler in python I am getting lost, dazed and confused as friends would put it. Thankfully this is not for any homework assignments, it is merely a script I am working on for making some repetitive tasks more automated, such as grabbing information about video files, and if needed convert them. I have yet to find a program that does what I am aiming for so I started creating a python script (as python is already installed on my Linux distro). It just seems to have become more complicated that I had hoped, but I am at a point now were I do not want to leave it unfinished. If an example of my script is needed I am more than willing to provide it for clarification of what I am trying to do. Thanks, Mike ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you can ensure that a header is written to those text files so they're in format such as [SectionHeader] InfoOne=Value InfoTwo=Value ... then you can take a look at the ConfigParser module where you would simply read the file and all your values would be read in in neat pairs. $ cat test.conf [Blah] OptOne=1 OptTwo=2 OptThree=3 $ python Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11) [GCC 4.4.1] on linux2 Type help, copyright, credits or license for more information. from ConfigParser import ConfigParser cfg = ConfigParser() cfg.read('test.conf') ['test.conf'] cfg.items('Blah') [('optone', '1'), ('optthree', '3'), ('opttwo', '2')] The other way to do it yourself is to iterate over the lines in the file, split the key and value and store it in a dictionary for later use. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] True Random Numbers
On 02/11/2010 11:29, Crallion wrote: In an attempt to generate true random numbers, I found this python script- http://code.google.com/p/truerandom/ Getting to the point, I get this error when I run my program. File /dev/python/absolute/truerandom.py, line 9, inmodule from urllib import urlopen ImportError: cannot import name urlopen Is urllib and/or urlopen deprecated in 3.1.2 or is it something I forgot to do? Python is running on OSX 10.6, which I upgraded from the default install to 3.1.2. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor |The urllib2 module has been split across several modules in Python 3.0 named urllib.request and urllib.error so you should be doing `from urllib.request import urlopen`.| -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What does TypeError: 'int' object is not iterable mean?
On 21/10/2010 14:42, Richard D. Moores wrote: Traceback (most recent call last): File c:\P26Working\test_urllib2_21a.py, line 148, inmodule unchanged_count, higher_count, lower_count, secs = sleep_seconds_control(unchanged_count, higher_count, lower_count, secs) TypeError: 'int' object is not iterable I'm working on a script that keeps track of the USD - Japanese Yen exchange rate. I'm experimenting with adding functionality that changes the seconds to sleep between web scrapes, depending on consecutive outputs of no change in the exchange rate. Please see the code athttp://tutoree7.pastebin.com/KWmdk8jb I'm at a loss as to what the error means. Thanks, Dick Moores ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You are expecting 4 items back from the sleep_seconds_control function but you only return 1 (seconds). The left-hand side should either just be `secs = ...` or you should change your function to return all 4 items. What the error means is that the interpreter is trying to iterate over the results from your function in order to divide it into the 4 variables on the left-hand side. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using contents of a document to change file names, (was Re: how to extract data only after a certain ...)
On 11/10/2010 13:46, Josep M. Fontana wrote: I tried your suggestion of using .split() to get around the problem but I still cannot move forward. I don't know if my implementation of your suggestion is the correct one but here's the problem I'm having. When I do the following: - fileNameCentury = open(r'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'.split('\r')) dct = {} for pair in fileNameCentury: key,value = pair.split(',') dct[key] = value print dct -- I get the following long error message: fileNameCentury = open(r'/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt'.split('\n')) TypeError: coercing to Unicode: need string or buffer, list found What you should be doing is: fileNameCentury = open('/Volumes/DATA/Documents/workspace/GCA/CORPUS_TEXT_LATIN_1/FileNamesYears.txt', 'r') dct = {} for line in fileNameCentury: #File objects have built-in iteration key, value = line.strip().split(',') dct[key] = value What you were doing originally was splitting the input filename for the open function (hence the error message stating `need string or buffer, list found`. If you wish to read in the entire file and then split it on newline characters you would do fileObject.read().splitlines() but it is more efficient to create your file object and just iterate over it (that way there is only 1 line at a time stored in memory and you're not reading in the entire file first). It's not a Mac problem, just a problem with how you were going about it. Hope that helps. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble with list.remove() loop
On 25/09/2010 20:44, D Ryan (2) wrote: Hello all, I am currently trying to write a program which can find the solution to a game of hangman. In a part of the program, a user inputs a letter, a tester tells him if the word contains that letter, and then if the answer is no, all words containing that letter are removed from the list of remaining candidates. However, the code I've written seems to remove some, but not all the words containing the letter. Strangely though, if i run it a few more times it gets some of the ones it missed the 1st time round, untill after enough iterations it gets all of them. I cant understand why it doesnt remove all of them the first time round. I have cut the offending code and formatted it to work on its own, and also to fit into a relatively short email. # A sample list of words, one of which is the answer. candidates = [abacus,amazing, ozimandias, a,alphanumeric, functioning] # In the following code, the user has guessed the letter 'a', # and the tester has told him that the letter 'a' is not in the word. user_guess=a tester_response=no # The following code should eliminate all words which contain the letter # 'a', leaving only the word 'functioning' in the list if tester_response in (No,no,n,N,NO): for word in candidates: if user_guess in word: print word, removed.. candidates.remove(word) print candidates Running once gives this output abacus removed.. ozimandias removed.. alphanumeric removed.. ['amazing', 'a', 'functioning'] But if i run it again it successfully removes 'amazing, and the next time it removes 'a', leaving the correct answer. I'm perplexed by this strange behaviour and would be most appreciative of any help. I'm very new to python so apologies for any formatting/style errors, and also for the simplicity of the problem. Best regards Dave ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You are mutating the list that you are iterating over so in essence you are looking at the word in list index 0, testing it, and removing it, then moving onto list index 1 but now your list has 'amazing' in index 0 so that does not get checked. The simplest way is to iterate through a new list with this for word in candidates[:]: That will create a new list that you will iterate over while you mutate the original list. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] wx to convert Group 4 Tifs to Gifs
On 26/08/2010 11:46, Albert-Jan Roskam wrote: Hi, I have a small application, written in Tkinter. It is supposed to display a tif image, among other things. The problem is, PIL won't decode group 4 Tifs (G4 TIF). The tifs that I have are about 125kb and contain two pages per file. They're scanned, monochrome files. I need the second page of the tif, more specifically the lower half of the second page. I will have 5000-6000 tifs eventually, to manual conversion is not an option. While googling around, I found many other people who faced the same problem. Since I cannot download executables here, I decided to use wx. Ideally, I'd like an object that can be handled with Tkinter.PhotoImage, but I'm also very happy with a simple program that converts from G4 tif to Gif. I have zero knowledge from wx. Therefroe, I'd really appreciate some pointers as to how to make the program below work. import wx, os def tif2gif(infile): This does *not* work SECONDPAGE = 1 outfile = os.path.splitext(infile[0] + .gif) image = wx.Image(name = infile, type = wx.BITMAP_TYPE_TIF, index = SECONDPAGE) bitmap = wx.BitmapFromImage(self.image) bitmap.SaveFile(outfile, wx.BITMAP_TYPE_GIF) tif2gif(infile = d:/temp/somefile.tif) Thank you very much in advance! Cheers!! Albert-Jan ~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Any chance you run Linux ? If so you can do it with convert like for fn in ./*.tif; do convert $fn $fn.jpg; done for fn in ./*-1.jpg; do convert $fn $fn.gif; done The reason for the 2 step conversion is tif - gif seems to only give you access to the first page. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] why does this fail
On 25/08/2010 12:00, Roelof Wobben wrote: Hello, I have this programm : def remove_letter(letter, strng): remove_letter('a', 'apple') 'pple' remove_letter('a', 'banana') 'bnn' remove_letter('z', 'banana') 'banana' remove_letter('i', 'Mississippi') 'Mpp' antwoord= for letter in strng: print letter, strng if letter in strng: print false else: print true return antwoord x=remove_letter('a', 'apple') print x But now everything is false even a in apple. What is here wrong ? Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You're rebinding the variable `letter`. It is an input variable for your function but then you use it as the character store while iterating through your string variable `strng`. What your control should look like would be more like for character in strng: if letter == character: print 'false' # this should be true, it is a match just like in your example else: print 'true' I'm assuming this function is just for learning purposes because there's a built-in string function you can use called replace and you'd use it as such `'apple'.replace('a', '')`. PS: Once you've gotten it to work convert it to a list comprehension, they are incredibly useful and a great tool. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting confusing NameError
On 18/08/2010 09:15, shane brennan wrote: Hi Tutors This is my first mail to this list so firstly thank you for reading and apologies in advance for any noob mistakes i may have inadvertantly made:). Ive only started learning python as my first programming language and its all going well so far, working my way through a couple of books one of which is programming python: for absolute beginners by Michael Dawson In one of the code samples he supplies while doing loops ( namely if and else loops) im getting a NameError i dont understand and cannot find any help anywhere about it. here is the code he supplied and the error im getting # Password # Demonstrates the if statement print(Welcome to System Security Inc.) print(-- where security is our middle name\n) password = input(Enter your password: ) if password == secret: print(Access Granted) input(\n\nPress the enter key to exit.) and the traceback error im getting Traceback (most recent call last): File G:\Programming\Python\programming python\chapter3\password.py, line 7, in module password = input(Enter your password: ) File string, line 1, in module NameError: name 'secret' is not defined I know this is probably very simple but for some reason i cannot get my head around it. thank you for any help in advance shane ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor input() [1] expects a valid Python expression as input as it gets evaluated and is not technically safe. raw_input() [2] is what you should be using instead. [1] http://docs.python.org/library/functions.html#input [2] http://docs.python.org/library/functions.html#raw_input Hope that helps. Welcome to the list and enjoy your stay. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] FTP from mainframe
On 29/07/2010 18:34, Steve Bricker wrote: This is my first attempt to FTP a file from a mainframe. The code: import ftplib session = ftplib.FTP('company.lan.com','userid','passwd') myfile = open('PC.filename','w') session.retrlines(RETR 'mainframe.filename', myfile) myfile.close() session.quit() The resulting error is: Traceback (most recent call last): File ftp_from_mf.py, line 5, in module session.retrlines(RETR 'mainframe.filename', myfile) File c:\python26\lib\ftplib.py, line 428, in retrlines callback(line) TypeError: 'file' object is not callable Not sure what I'm missing. Steve Bricker ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor When I'm retrieving items I use retrbinary for eg. from ftplib import FTP ftp = FTP(url, username, password) for filename in ftp.nlst(''): ftp.retrbinary('RETR %s' % filename, open(filename, 'wb').write) ftp.delete(filename) ftp.close() I hope that helps. -- Kind Regards, Christian Witts Business Intelligence C o m p u s c a n | Confidence in Credit Telephone: +27 21 888 6000 National Cell Centre: 0861 51 41 31 Fax: +27 21 413 2424 E-mail: cwi...@compuscan.co.za NOTE: This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494. If you cannot access the disclaimer, request it from email.disclai...@compuscan.co.za or 0861 514131. National Credit Regulator Credit Bureau Registration No. NCRCB6 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] position of an element in list:
On 23/07/2010 15:22, Vineeth Rakesh wrote: Hello all, How to return the position of a character in a string. Say I have str1 = welcome to the world if i want to return the position of the first occurrence of o how to do it? Thanks Vin ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Strings have a function called index, which take a string argument which is what you're looking for. So you can do str1.index('o') which would return 4. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] SQLite database locked problem
On 20/07/2010 06:48, Che M wrote: I'm using an SQLite3 database (with Python 2.5) and every so often the application crashes or hangs because somewhere there is this error, or something like it: OperationalError: database is locked. This is probably because I am viewing and sometimes changing the database through SQLite Database Browser while working on my app, and occasionally the app tries to access the db when the Database Browser is writing to it or something like that. I'd like to a) know how to reproduce the error (haven't seen it in a while, but want to be sure know when it may happen for users and b) prevent it from being a problem in the running app. Any suggestions welcome. Thank you, Che Hotmail is redefining busy with tools for the New Busy. Get more from your inbox. See how. http://www.windowslive.com/campaign/thenewbusy?ocid=PID28326::T:WLMTAGL:ON:WL:en-US:WM_HMP:042010_2 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor SQLite is technically thread safe, but a write operation locks the entire database [1]: - Any resultset being step()'d through uses a shared read-only lock. - Any insert/update being executed requires an exclusive write lock. [1] http://www.sqlite.org/lockingv3.html -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Handling 'None' (null) values when processing sqlite cursorresults
On 14/07/2010 14:32, Alan Gauld wrote: Monte Milanuk memila...@gmail.com wrote (104, None, u'Sylvester', None, u'Evans', None, u'527-9210 Proin Av.', u'Liberal', u'VT', u'24742', u'1-135-197-1139', u'vehicula.pellentes...@idmollis.edu', u'2010-07-13 22:52:50', u'2010-07-13 22:52:50') At first I was having fits as str.join() was giving me a 'NoneType error'. I found one way around that, by processing the results so the 'None' values got omitted from the list by the time they got to str.join(). Keep the storage and manipulation of data separate from the display of that data. That is an important and fundamental principle of data processing. Store the data with the nulls. Display the data without. values omitted really messed with the list order which I was depending on i.e. list[5] could be different fields depending on how many 'None' And that is why. values had been omitted. And if I didn't omit them, when I printed out the user name in the format 'first''middle''last' from the above record, You need a display function that can strip out the nulls as needed. A simple list comprehension or generator expression would work in this case: print ' '.join(str(field) for field in data if field is not 'None') The problem with that is if you're relying on a set delimiter you are removing elements so you would be better served by doing `str(field) if field != None else '' for field in record` -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Handling 'None' (null) values when processing sqlite cursorresults
On 14/07/2010 19:34, Alan Gauld wrote: Christian Witts cwi...@compuscan.co.za wrote You need a display function that can strip out the nulls as needed. A simple list comprehension or generator expression would work in this case: print ' '.join(str(field) for field in data if field is not 'None') The problem with that is if you're relying on a set delimiter you are removing elements so you would be better served by doing `str(field) if field != None else '' for field in record` True, although in this case we do seem to have a fixed condition since it's the database's representation of null but I originally didn't notice the quotes around None. When I fixed that I should have changed is to equals.. print ' '.join(str(field) for field in data if field != 'None') But your modification confuses me. can you explain? What would the print line look like? Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I prefer not to use a space delimiter, generally a pipe |, so the output would look a lot like 104||Sylvester||Evans||527-9210 Prion Av.|Liberal|VT|24742|1-135-197-1139|vehicula.pellentes...@idmollis.edu|2010-07-13 22:52:50|2010-07-13 22:52:50 The reason I suggested that usage instead is because Monte said having the 'None' values omitted really messed with the list order which I was depending on So if you're wanting to create a new list which removes the Nones but still keeps the same indexing it would be the way to do it, imho. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Time
Ahmed AL-Masri wrote: Hi, I would calculate the running time of my simulation code. any one know how to do that? example def demo(): ### the starting point of time should be 0 f.simulate(data) ### the end of the class so need to find the time in Sec.? ### print time in sec. if __name__ == '__main__': demo() look forward to seeing the answer, Thanks a lot, A. Naufal ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor You can take a look at the timeit module [1] and some nice examples [2]. [1] http://docs.python.org/library/timeit.html [2] http://www.doughellmann.com/PyMOTW/timeit/ -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] conventions for establishing and saving default values for variables
Pete O'Connell wrote: Hi I was wondering if anyone could give me some insight as to the best way to get and save variables from a user the first time a script is opened. For example if the script prompts something like What is the path to the folder? and the result is held in a variable called thePath, what is the best way to have that variable saved for all subsequent uses of the script by the same user. Pete ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ConfigParser can read/write config files or using Pickle/cPickle to save load your variables or using something like JSON (JavaScript Object Notation) will do what you want. For something like just storing a path for future use using ConfigParser would be perfectly suited to the task. import ConfigParser cfg = ConfigParser.ConfigParser() cfg.read('options.cfg') if not cfg.sections(): work_path = raw_input('Please enter the workspace path: ') cfg.add_section('PATH') cfg.set('PATH', 'workspace', work_path) f = open('options.cfg', 'w') cfg.write(f) f.close() else: work_path = cfg.get('PATH', 'workspace') -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Different between pass continue
M. Bashir Al-Noimi wrote: Hi All, I couldn't understand the difference between pass and continue keywords, could you explain to me? Taken from the docs at http://docs.python.org/tutorial/controlflow.html The continue statement continues the next iteration of a loop for eg. for line in file: if not line.strip(): # If the line is empty then continue The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example: while True: pass # Busy-wait for keyboard interrupt (Ctrl+C) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PYTHON 3.1
Dipo Elegbede wrote: Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type copyright, credits or license() for more information. print 'hello' SyntaxError: invalid syntax (pyshell#0, line 1) print ('hello') hello the above print is what i came across having installed python 3.0 and trying to run the print command. with previous versions, a print command takes the form print 'parameter' and the output is parameter but with this new version it seems you need to put in brackets like: print ('hello') to get an output like: hello please confirm this is a new syntax for print. thank you. i will put up morte concerns as they arrive. thanks. -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com http://www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The Python 3.x series changed the print statement to a print function. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary search question
Robert Berman wrote: Hi, Given a list, list1 having 100,000 non repeating, sorted integers , which of the following methods is fastest to find an item fully understanding the item may or may not be in the list: The binary search method which is the standard search for such a small sample size, or the more python type statement is value in list1? What I am really trying to ascertain is how expensive or how efficient is 'is value in list1'. Thanks for your input Robert Berman What you don't see with your eyes, don't invent with your mouth. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Bisect and search. If the list is sorted you easily know what the first and last element is. Bisect the list, check that value, if it's higher than your target then bisect the bottom half of the list and check that and then it's a matter of rinse repeat. You'll be suprised how few bisections you will need to do in order to find your data. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop comparison
Ark wrote: Hi everyone. A friend of mine suggested me to do the next experiment in python and Java. It's a simple program to sum all the numbers from 0 to 10. result = i = 0 while i 10: result += i i += 1 print result The time for this calculations was huge. It took a long time to give the result. But, the corresponding program in Java takes less than 1 second to end. And if in Java, we make a simple type check per cycle, it does not take more than 10 seconds in the same machine. I was not expecting Python to be faster than Java, but it''s too slow. Maybe Java optimizes this case and Python doesn't. Not sure about this.} Thanks ark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Different methods and their relative benchmarks. The last two functions are shortcuts for what you are trying to do, the last function 't5' corrects the mis-calculation 't4' has with odd numbers. Remember, if you know a better way to do something you can always optimize yourself ;) def t1(upper_bounds): ... start = time.time() ... total = sum((x for x in xrange(upper_bounds))) ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t1(10) Time taken: 213.830082178 45 def t2(upper_bounds): ... total = 0 ... start = time.time() ... for x in xrange(upper_bounds): ... total += x ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t2(10) Time taken: 171.760597944 45 def t3(upper_bounds): ... start = time.time() ... total = sum(xrange(upper_bounds)) ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t3(10) Time taken: 133.12481904 45 def t4(upper_bounds): ... start = time.time() ... mid = upper_bounds / 2 ... total = mid * upper_bounds - mid ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t4(10) Time taken: 1.4066696167e-05 45 def t5(upper_bounds): ... start = time.time() ... mid = upper_bounds / 2 ... if upper_bounds % 2: ... total = mid * upper_bounds ... else: ... total = mid * upper_bounds - mid ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t5(10) Time taken: 7.15255737305e-06 45 t3(1999) Time taken: 0.003816121 1997001 t4(1999) Time taken: 3.09944152832e-06 1996002 t5(1999) Time taken: 3.09944152832e-06 1997001 -- Kind Regards, Christian Witts Business Intelligence C o m p u s c a n | Confidence in Credit Telephone: +27 21 888 6000 National Cell Centre: 0861 51 41 31 Fax: +27 21 413 2424 E-mail: cwi...@compuscan.co.za NOTE: This e-mail (including attachments )is subject to the disclaimer published at: http://www.compuscan.co.za/live/content.php?Item_ID=494. If you cannot access the disclaimer, request it from email.disclai...@compuscan.co.za or 0861 514131. National Credit Regulator Credit Bureau Registration No. NCRCB6 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop comparison
Alan Gauld wrote: Stefan Behnel stefan...@behnel.de wrote import cython @cython.locals(result=cython.longlong, i=cython.longlong) def add(): result = 0 for i in xrange(10): result += i return result print add() This runs in less than half a second on my machine, including the time to launch the CPython interpreter. I doubt that the JVM can even start up in that time. I'm astonished at these results. What kind of C are you using. Even in assembler I'd expect the loop/sum to take at least 3s on a quad core 3GHz box. Or is cython doing the precalculation optimisations you mentioned? And if so when does it do them? Because surely, at some stage, it still has to crank the numbers? (We can of course do some fancy math to speed this particular sum up since the result for any power of ten has a common pattern, but I wouldn't expect the compiler optimiser to be that clever) The precalculation optimisations are taking place. If you pass it an argument to use for the upper limit of the sequence the calculation time shoots up. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Loop comparison
Dave Angel wrote: Christian Witts wrote: div class=moz-text-flowed style=font-family: -moz-fixedArk wrote: Hi everyone. A friend of mine suggested me to do the next experiment in python and Java. It's a simple program to sum all the numbers from 0 to 10. result = i = 0 while i 10: result += i i += 1 print result The time for this calculations was huge. It took a long time to give the result. But, the corresponding program in Java takes less than 1 second to end. And if in Java, we make a simple type check per cycle, it does not take more than 10 seconds in the same machine. I was not expecting Python to be faster than Java, but it''s too slow. Maybe Java optimizes this case and Python doesn't. Not sure about this.} Thanks ark ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Different methods and their relative benchmarks. The last two functions are shortcuts for what you are trying to do, the last function 't5' corrects the mis-calculation 't4' has with odd numbers. Remember, if you know a better way to do something you can always optimize yourself ;) def t1(upper_bounds): ... start = time.time() ... total = sum((x for x in xrange(upper_bounds))) ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t1(10) Time taken: 213.830082178 45 def t2(upper_bounds): ... total = 0 ... start = time.time() ... for x in xrange(upper_bounds): ... total += x ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t2(10) Time taken: 171.760597944 45 def t3(upper_bounds): ... start = time.time() ... total = sum(xrange(upper_bounds)) ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t3(10) Time taken: 133.12481904 45 def t4(upper_bounds): ... start = time.time() ... mid = upper_bounds / 2 ... total = mid * upper_bounds - mid ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t4(10) Time taken: 1.4066696167e-05 45 def t5(upper_bounds): ... start = time.time() ... mid = upper_bounds / 2 ... if upper_bounds % 2: ... total = mid * upper_bounds ... else: ... total = mid * upper_bounds - mid ... end = time.time() ... print 'Time taken: %s' % (end - start) ... print total ... t5(10) Time taken: 7.15255737305e-06 45 t3(1999) Time taken: 0.003816121 1997001 t4(1999) Time taken: 3.09944152832e-06 1996002 t5(1999) Time taken: 3.09944152832e-06 1997001 A simpler formula is simply upper_bounds * (upper_bounds-1) / 2 No check needed for even/odd. DaveA Ah yes, that is true. :) Sometimes I feel I overlook the simplest of solutions. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Extracting lines in a file
Alan Gauld wrote: ranjan das ranjand2...@gmail.com wrote For instance lets say the unique string is documentation (and documentation occurs more than once in the file). Now, on each instance that the string documentation occurs in the file, I want to read the 25th line (from the line in which the string documentation occurs) Is there a goto kind of function in python? There is a seek() function but it would require the lines to be of constant length. Its probably easier to just use a loop: def file_jump(fileobj, n =1): for line in range(n): fileobj.readline() That will move the file pointer forward n lines. Note, if the jumps can overlap the original then you might want to use tell() before the jump to store the original location then use seek() to go back. (eg if the trigger was in line 5 and the jump was 7 lines but the trigger also occured in line 10) Pseudocode: for line in file: if trigger in line: marker = file.tell() file_jump(file, jumps[trigger]) process_file_data() file.seek(marker) # go back to original position HTH, If you know the line numbers you can use the linecache module to get any line from any file for eg. import linecache linecache.getline('/etc/passwd', 4) 'sys:x:3:3:sys:/dev:/bin/sh\n' If what you require is more complex than simply that then you might be better off doing line-for-line processing on the file. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you are using Windows and just installed Python and then tried to execute your script with python script_name.py and it tells you it cannot find the program to execute then it is likely your environment settings as the Python installer never seems to set up your path properly. Go to My Computer - Advanced Settings - Environment Settings - Double-Click on path - Add your python path eg. c:\python26 at the end - Restart and it should work. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Forwarding to the list. Martijn wrote: On Tue, Mar 30, 2010 at 12:15 PM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you are using Windows and just installed Python and then tried to execute your script with python script_name.py and it tells you it cannot find the program to execute then it is likely your environment settings as the Python installer never seems to set up your path properly. Go to My Computer - Advanced Settings - Environment Settings - Double-Click on path - Add your python path eg. c:\python26 at the end I think it should be capitalized, but I'm not sure, so: For Python 2.6: C:\Python26 For Python 3.1: C:\Python31 If you didn't install it on the C: drive, change C: to the drive letter you installed it on. Also, check if there's a semicolon ( ; ) at the end of the path before you add the python path, if there isn't, add it first. Now you can continue :) Martijn - Restart and it should work. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Windows is case insensitive when it comes to paths and executables names so it shouldn't matter. The semi-colon I forgot to mention though. :) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help
Oshan Modi wrote: I have Windows 7 and am using python 2.6.. I added python.exe's address in the path option under enviromental variables.. i can run python in command prompt.. its just that i dont know to make it execute a file directly rather than typing the whole program again and again.. On Tue, Mar 30, 2010 at 4:55 PM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Forwarding to the list. Martijn wrote: On Tue, Mar 30, 2010 at 12:15 PM, Christian Witts cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za mailto:cwi...@compuscan.co.za wrote: Oshan Modi wrote: i am only a novice and just started programming.. i am having trouble running a .py file in the command prompt.. if anyone of you could help? ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor If you are using Windows and just installed Python and then tried to execute your script with python script_name.py and it tells you it cannot find the program to execute then it is likely your environment settings as the Python installer never seems to set up your path properly. Go to My Computer - Advanced Settings - Environment Settings - Double-Click on path - Add your python path eg. c:\python26 at the end I think it should be capitalized, but I'm not sure, so: For Python 2.6: C:\Python26 For Python 3.1: C:\Python31 If you didn't install it on the C: drive, change C: to the drive letter you installed it on. Also, check if there's a semicolon ( ; ) at the end of the path before you add the python path, if there isn't, add it first. Now you can continue :) Martijn - Restart and it should work. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Windows is case insensitive when it comes to paths and executables names so it shouldn't matter. The semi-colon I forgot to mention though. :) -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Is this perhaps what you want to do ? http://www.python.org/doc/faq/windows/#how-do-i-make-python-scripts-executable -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] characters
Shurui Liu (Aaron Liu) wrote: In Python, could space be counted as a character same as a letter? len(...) len(object) - integer Return the number of items of a sequence or mapping. As a space is an item it will be counted. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble with dates and python and databases
Christopher Spears wrote: I'm trying to write a script that calculates the rate of disk usage. I think the best way to accomplish this task is to write a script that will monitor a server's capacity and how much space is being used on a daily basis and store the information in a SQLite database. Then the program can retrieve the necessary information from the database to compute the rate. Server 1 3/11/10 10 GB Used/50 GB Capacity 3/12/10 15 GB Used/50 GB Capacity 3/13/10 17 GB Used/50 GB Capacity Rate of usage = 7 GB / 3 days = 2.3 GB per day Eventually, I want the script to issue a warning if the server is in danger of becoming full in a certain number of days. My problem is I'm not sure how to store and retrieve the dates. I assume the best way to record the date is to use datetime.date. import datetime datetime.date.today() datetime.date(2010, 3, 11) How could I pass the datetime object into the database? Any advice would be appreciated! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor cursor.execute(select * fromlogs where log_date = to_date(:bind_variable, 'mmdd') , bind_variable = your_date_here) I use that style most commonly, but remember if you insert the records into the database using SYSDATE you will need to call `trunc` on your log_date field in order for it to match your input. If for example you want the last 3 days of data though to trend on you can always do your select like select log_date, usage, capacity fromlogs where log_date = trunc(sysdate) - 3 order by log_date asc -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehension possible with condition statements?
Jojo Mwebaze wrote: Hi There, i would like to implement the following in lists assuming x = 3 y = 4 z = None i want to create a dynamic list such that mylist = [ x , y, z ] , if z in not None if z is None then mylist = [x,y] Anyhelp! cheers Jojo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor output function | variable for input set, predicate So something like `x**2 for x in [1, 2, 3, 4, 5, None, 9] if x != None` would iterate over your input set pumping the current item into the variable x, it will check if x != None and if that condition evaluates true it will perform the function you set out to perform. The predicate section acts as a filter to your data set ensuring the variable you are working with meets certain conditions. If you wanted to for eg. still accept the None but perform a different function on it Python does allow it like `x**2 if x else 'Not a number' for x in [1, 2, 3, 4, 5, None, 9]`. Hope that helps. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Omitting lines matching a list of strings from a file
galaxywatc...@gmail.com wrote: But I would do this with a list comprehension or generator expression (depending on your Python version): lines = [line for line in infile if line[146:148] not in omit_states] print '\n'.join(lines) That's very helpful. Thanks. One formatting detail: there is a blank line after each line printed, how do I ged rid of the extra blank lines? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor lines = [line.strip() for line in infile if line[146:148] not in omit_states] print '\n'.join(lines) or alternatively lines = [line for line in infile if line[146:148] not in omit_states] print ''.join(lines) Just remember that doing a list comprehension like that on a large file will drastically reduce the speed of your application as well as introduce memory bloat. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Cannot open SQLite database
Timo wrote: Hello all, my program uses SQLite as database and everything worked fine until now. I have over 3000 downloads of my program, but I got 2 mails this week from people who get this error: OperationalError: unable to open database file I searched the net, and all problems seem to be of a not writeable directory or passing a tilde to connect to the database. As far as I know, this isn't the case with my program. Here is some code: # Get the application data folder # This will return: C:\Documents and Settings\user\Application Data\myapp PREFDIR = os.path.join(os.environ['APPDATA'], 'myapp') # Connect to the database def db_connect(): conn = sqlite3.connect(os.path.join(PREFDIR, 'myapp.db')) # This line gives the error conn.text_factory = str cursor = conn.cursor() return (conn, cursor) I noticed that the 2 users that got the error are Russian, so I thought that the Russian characters would cause problems. I tried on my Linux and Windows machines with some Russian names, but thet doesn't seem the problem. Some help is appreciated :-). Cheers, Timo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Is that folder write-able for the user/application under Windows Vista/7 ? There are some older games for example that cannot be installed in the default locations due to being denied write access to their own data. -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Functions returning multiple values
Giorgio wrote: I have an update: I can easily undertand why this example doesn't work: def nochange(x): x = 0 y = 1 nochange(y) print y # Prints out 1 X is a local variable, and only gets modified in the function, that doesn't return any value. But it's very difficult for me to understand WHY this works: def change(some_list): some_list[1] = 4 x = [1,2,3] change(x) print x # Prints out [1,4,3] some_list is a local list, isn't it? Maybe i can't have lists that are only existing in a function? Thankyou all 2010/2/22 Kent Johnson ken...@tds.net mailto:ken...@tds.net On Mon, Feb 22, 2010 at 9:13 AM, Giorgio anothernetfel...@gmail.com mailto:anothernetfel...@gmail.com wrote: And, i have some difficulties understanding the other strange example in that howto. Just scroll down to: However, the point is that the value of x is picked up from the environment at the time when the function is defined. How is this useful? Let’s take an example — a function which composes two other functions. He is working on a function that compose other 2 functions. This is the final solution def compose(fun1, fun2): def inner(x, fun1=fun1, fun2=fun2): return fun1(fun2(x)) return inner But also tries to explain why this example: # Wrong version def compose(fun1, fun2): def inner(x): return fun1(fun2(x)) return inner def fun1(x): return x + world! def fun2(x): return Hello, sincos = compose(sin,cos) # Using the wrong version x = sincos(3) Won't work. Now, the problem is that the inner function gets fun1 and fun2 from other 2 functions. My question is: why? inner is a sub-function of compose, where fun1 and fun2 are defined. It does work: In [6]: def compose(fun1, fun2): ...: def inner(x): ...: return fun1(fun2(x)) ...: return inner ...: In [7]: def fun1(x): ...: return x + world! ...: In [8]: def fun2(x): ...: return Hello, ...: In [9]: from math import sin, cos In [10]: sincos = compose(sin,cos) # Using the wrong version In [11]: In [12]: x = sincos(3) In [13]: In [14]: x Out[14]: -0.8360218615377305 That is a very old example, from python 2.1 or before where nested scopes were not supported. See the note A Note About Python 2.1 and Nested Scopes - that is now the default behaviour. Kent -- -- AnotherNetFellow Email: anothernetfel...@gmail.com mailto:anothernetfel...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Take a look at the Python gothcha's: http://www.ferg.org/projects/python_gotchas.html#contents_item_6 -- Kind Regards, Christian Witts ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor