Re: [Tutor] Process list elements as consecutive pairs

2010-03-06 Thread Peter Otten
Rüdiger Wolf wrote: > I am trying to Process list elements as consecutive pairs into > consecutive pairs. > Any pythonic suggestions? > > listin = [1,2,3,4,5,6,7,8,9,10] > I want to process as consecutive pairs > 1,2 > 3,4 > 5,6 > 7,8 > 9,10 >>> listin = [1,2,3,4,5,6,7,8,9,10] >>> it = iter(lis

Re: [Tutor] writing csv files

2010-05-22 Thread Peter Otten
prasad rao wrote: > hello! > > I got a problem writing csv file. > > 1) > csvw=csv.writer(open('/home/prasad/kkm','w'), > dialect='excel',fieldnames=names) > Traceback (most recent call last): > File "", line 1, in > TypeError: 'fieldnames' is an invalid keyword argument for this function >

Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Peter Otten
David Perlman wrote: > Using the csv.DictReader and csv.DictWriter lets you read and write > lists of dictionaries from files containing tabular data. I have a > system that naturally generates tabular data in the form of a > dictionary of lists: the dictionary key is the name of the column, and

Re: [Tutor] list of dicts <-> dict of lists?

2010-05-28 Thread Peter Otten
David Perlman wrote: > Oh, except one problem: the csv.DictWriter lets you tell it what order > you want the columns output in. With your version, they just show up > in whatever order Python wants them. That's not hard to fix: >>> fieldnames = "abca" >>> cols = [data[fn] for fn in fieldnames]

Re: [Tutor] accented characters to unaccented

2010-06-08 Thread Peter Otten
KB SU wrote: > Hi, > > I have open url and read like following: > > $import urllib > $txt = urllib.urlopen("http://www.terme-catez.si";).read() > $txt > If you see above, in junk of HTLM, there is text like 'Terme > \xc4\x8cate\xc5\xbe' (original is 'Terme Čatež'). Now, I want to convert > cod

Re: [Tutor] Looking for duplicates within a list

2010-06-12 Thread Peter Otten
Ken G. wrote: > I have been working on this problem for several days and I am not making > any progress. I have a group of 18 number, in ascending order, within a > list. They ranged from 1 to 39. Some numbers are duplicated as much as > three times or as few as none. > > I started with one li

Re: [Tutor] Converting audio samples from 16-bit signed int to float?

2010-06-21 Thread Peter Otten
Joe Veldhuis wrote: > Hello all. I'm writing a program that needs to capture audio from a > soundcard and run FFTs to determine peak frequency for further processing. > The soundcard's native capture format is 16-bit little-endian signed > integer samples (values 0-65535), and of course the FFT fu

Re: [Tutor] split struggle

2010-06-23 Thread Peter Otten
Richard D. Moores wrote: > Please see my Python 3.1 code pasted at > . > > This does what I want, which is to do one of: > 1. print all the elements of the list, lst. > 2. print "Done" when "" is entered. > 3. print the elements of lst whose indexes are entere

Re: [Tutor] I don't understand this code

2010-07-14 Thread Peter Otten
ZUXOXUS wrote: > Hi, > > I am a true beginner in programming, and im learning with > inventwithpython.com. > > There's something I dont understand, and i would really appreciate any > help. > > In chapter 9, the one about the Hangman game, I don't get the block of > code in line 61 > > 59. wo

Re: [Tutor] A file containing a string of 1 billion random digits.

2010-07-19 Thread Peter Otten
bob gailer wrote: > Check this out: > > import random, time > s = time.time() > cycles = 1000 > d = "0123456789"*100 > f = open("numbers.txt", "w") > for i in xrange(n): >l = [] >l.extend(random.sample(d, 1000)) >f.write(''.join(l)) > f.close() > print time.time() - s Note that this

Re: [Tutor] A file containing a string of 1 billion random digits.

2010-07-19 Thread Peter Otten
Richard D. Moores wrote: > On Mon, Jul 19, 2010 at 04:51, Peter Otten <__pete...@web.de> wrote: >> bob gailer wrote: >> >>> Check this out: >>> >>> import random, time >>> s = time.time() >>> cycles = 1000 >>> d = &quo

Re: [Tutor] "x and y" means "if x is false, then x, else y"??

2010-07-22 Thread Peter Otten
Lie Ryan wrote: > On 07/05/10 22:23, Adam Bark wrote: > >> >> I should add that this is how something like: >> >> if x != y: >> do_something() >> >> works, if expects a True or False (this isn't always true but works for >> comparison operators expressions such as this). >> > > "if" exp

Re: [Tutor] decorators

2010-07-23 Thread Peter Otten
Mary Morris wrote: > I'm trying to compile a list of decorators from the source code at my > office. > I did this by doing a > > candidate_line.find("@") > > because all of our decorators start with the @ symbol. The problem I'm > having is that the email addresses that are included in the comm

Re: [Tutor] finding duplicates within a tuple of tuples

2010-07-29 Thread Peter Otten
Norman Khine wrote: > hello, > > i have this tuple: > > http://paste.lisp.org/+2F4X > > i have this, which does what i want: > > from collections import defaultdict > > d = defaultdict(set) > for id, url in result: > d[url].add(id) > for url in sorted(d): > if len(d[url]) > 1: > print('%d --

Re: [Tutor] finding duplicates within a tuple of tuples

2010-07-30 Thread Peter Otten
Norman Khine wrote: > Here is the latest version http://pastie.org/1066582 can this be > further improved? > # get all the duplicates and clean the products table > main.execute("SELECT product_Id, url FROM %s.product WHERE url != ''" % db) > results = main.fetchall() > > d = defaultdict(set) >

Re: [Tutor] Conflict with encoding in console view and file dump

2010-07-30 Thread Peter Otten
Alex Baraibar wrote: > Hello, would you please look at the comments in the code and help me with > an answer? > Thanx. > > # -*- coding: cp1252 -*- > > def festivos(): > fest = [ 'Any Nou:\t\t\t1 de enero', > 'Reis:\t\t\t\t6 de enero', > 'Festa del Treball:\t\t1 de

Re: [Tutor] A unicode print question

2010-07-30 Thread Peter Otten
Joel Goldstick wrote: > I was reading this: http://diveintopython.org/xml_processing/unicode.html > > and tried the exercise: > s = u'La Pe\xf1a' [image: 1] print s [image: 2] > Traceback (innermost last): > File "", line 1, in ? > UnicodeError: ASCII encodi

Re: [Tutor] Maximum recursion depth problem.

2010-08-03 Thread Peter Otten
Wesley Brooks wrote: > I'm having real difficulty understanding why the following is not > working and hoped I've either missed something obvious of I'm doing > something wrong! > > class A: > def break_down(self, value, base, broken_list=[]): > I'm a little stumped as I don't think I'm usin

Re: [Tutor] Conflict with encoding in console view and file dump

2010-08-03 Thread Peter Otten
Alex Baraibar wrote: > Hi, Peter. > Sorry for the delay, I've been out for a while. > So I did what you suggested and it prints the following: > > " > import sys > print >> sys.stderr, sys.stdout.encoding > > what does the above print > (a) when you print to the console? it prints cp850 > (b) wh

Re: [Tutor] Conflict with encoding in console view and file dump

2010-08-04 Thread Peter Otten
Alex Baraibar wrote: > I just wish I understood better what happened and why. I've looked into > the Unicode section of the official docs, but I probably need to study it > more in order to fully understand it, so... Just in case you didn't come across it, there's a howto that covers the basics:

Re: [Tutor] string conversion according to the terminal

2010-08-12 Thread Peter Otten
ANKUR AGGARWAL wrote: > Hey- suppose we have a file name-"my file number" > if we want to execute it into the terminal it would be like - my\ file\ > number > > so wondering is there any one in the python that change the enter string > into the terminal string one- > like if user enter the file n

Re: [Tutor] Immutable objects

2010-08-19 Thread Peter Otten
Nitin Das wrote: > class mymut(object): > > def __setattr__(self,k,v): > if hasattr(self,k): > if self.__dict__.get(k) == None: > self.__dict__[k] = v > else: > raise TypeError("Cant Modify Attribute Value") > else: > raise T

Re: [Tutor] Immutable objects

2010-08-19 Thread Peter Otten
Peter Otten wrote: > Nitin Das wrote: > >> class mymut(object): >> >> def __setattr__(self,k,v): >> if hasattr(self,k): >> if self.__dict__.get(k) == None: >> self.__dict__[k] = v >> else: >>

Re: [Tutor] List comprehension for dicts?

2010-08-19 Thread Peter Otten
Pete wrote: > Hi, > > I've been reading up on list comprehensions lately, all userful and > powerful stuff - trying to wrap my brain around it :) > > As the examples all seem to relate to lists, I was wondering if there is > an elegant similar way to apply a function to all keys in a dictionary?

Re: [Tutor] question about import statement

2010-08-27 Thread Peter Otten
Greg Bair wrote: > On 08/26/2010 10:29 PM, Hugo Arts wrote: >> On Thu, Aug 26, 2010 at 9:16 PM, Bill Allen wrote: >>> >>> I did try that and of course it gave an error because it was necessary. >>> I >>> just did not know why. However, I later found an explanation on the >>> web. Here it is: >

Re: [Tutor] __new__ over __init__

2010-08-30 Thread Peter Otten
Payal wrote: > Can someone please give a very simple example of using __new__ wherein > __init__ cannot be used? Subclasses of immutable types, e. g. tuple: >>> class A(tuple): ... def __init__(self, a, b): ... pass ... >>> a = A(1,2) Traceback (most recent call last): File "",

Re: [Tutor] __new__ over __init__

2010-09-02 Thread Peter Otten
Alan Gauld wrote: > "Payal" wrote >> b. What does type(_) mean? > > The _ refers to the last evaluated result, in this case the tuple > (1,2). > Its a shorthand trick, I think it only works in the interpreter, I > don't like > it and never use it, but many do. (FWIW Perl has a similar shortcut >

Re: [Tutor] Exception Handling and Stack traces

2010-09-10 Thread Peter Otten
Michael Powe wrote: > I can't work out how to suppress stacktrace printing when exceptions > are thrown. [snip rant] It might have been a good idea to read a tutorial like http://docs.python.org/tutorial/errors.html#handling-exceptions or ask before you got annoyed enough to write that rant ;)

Re: [Tutor] Exception Handling and Stack traces

2010-09-10 Thread Peter Otten
Michael Powe wrote: > On Fri, Sep 10, 2010 at 03:56:51PM +0200, Peter Otten wrote: >> Michael Powe wrote: >> >> > I can't work out how to suppress stacktrace printing when exceptions >> > are thrown. >> >> [snip rant] >> >> It m

Re: [Tutor] hashlib problems

2010-09-10 Thread Peter Otten
Rance Hall wrote: > Im wanting to use the builtin hashlib functions to encrypt passwords > before storing them in a database. > > According to documentation on the python.org site it should be as simple > as > > import hashlib > > hashname = hashlib.sha234 (or whatever other hash method you wa

Re: [Tutor] exceptions problem

2010-09-11 Thread Peter Otten
Steven D'Aprano wrote: > On Sat, 11 Sep 2010 09:56:41 am bob gailer wrote: >> > I never thought that you can use a float and a integer to look if >> > the number is a integer. >> >> You can't. > > What? Of course you can. > > def is_integer(x): > """Return True if x is an integer.""" > t

Re: [Tutor] How to numerically sort strings that start with numbers?

2010-09-14 Thread Peter Otten
Pete O'Connell wrote: > theList = ["21 trewuuioi","3zxc","134445"] > print sorted(theList) > > Hi, the result of the sorted list above doesn't print in the order I > want. Is there a straight forward way of getting python to print > ['3zxc','21 trewuuioi','134445'] > rather than ['134445', '21 tr

Re: [Tutor] Regex comments

2010-09-16 Thread Peter Otten
Michael Powe wrote: > The re module includes the option to comment a regular expression with > the syntax (?#comment). e.g. > > p=r'(.*) (?PWT.dl)(?#parameter)=(?P[^&]+)(?#value).*' > > Is there a mechanism for extracting these values from the match, in > the way that group names are extracted?

Re: [Tutor] robots question

2010-09-16 Thread Peter Otten
Roelof Wobben wrote: > As a exercise from this book ( Thinking like a computer scientist ) I have > to make this programm on this > page(http://openbookproject.net/thinkcs/python/english2e/ch12.html) > Exercise 11 > def check_collisions(robots, junk, player): > defeated = check_collision

Re: [Tutor] FW: robots question

2010-09-16 Thread Peter Otten
Roelof Wobben wrote: > I change everything to this : > def check_collisions(robots, junk, player): > defeated = check_collisions(robots, player, junk) Do you see the problem? > print "type robots", type(robots) > print "type junk", type(junk) > print "type playe

Re: [Tutor] robots question

2010-09-17 Thread Peter Otten
Roelof Wobben wrote: > I changed a lot because of your suggestions. > But one thing is still a puzzle. > The robots don't move anymore. > > What I have is this : > robots = [] > place_robots(4) > move_robots(robots, player) You are only moving the robots in the 'robots' list. B

Re: [Tutor] Remove a dictionary entry

2010-09-18 Thread Peter Otten
M. 427 wrote: > (I am very new to python) > I built a dictionary d={} of lists similar to this : > > d = { > 'a': ['apricot', 'apple'], > 'b': ['beach', 'bear', 'bottle'], > 'c': ['cold', 'cook', 'coleslaw'], > 'd': ['deep'], > 'e': ['expression', 'elephant'] > } > > Now i want to go through thi

Re: [Tutor] Remove a dictionary entry

2010-09-19 Thread Peter Otten
M. 427 wrote: > Version 4 : (2 steps) > > # step 1 : list keys of unwanted rows > sck=[] # list of single children keys in dictionary > for k in d.keys() : > if len(d[k]) < 2 : > sck.append(k) > # step 2 : delete all d rows w

Re: [Tutor] Remove a dictionary entry

2010-09-19 Thread Peter Otten
Steven D'Aprano wrote: > On Sat, 18 Sep 2010 07:13:13 pm Peter Otten wrote: > >> You should never iterate over a list or dictionary and add or remove >> items to it at the same time. That is a recipe for disaster even if >> it doesn't fail explicitly. &g

Re: [Tutor] Can this be done easly

2010-09-19 Thread Peter Otten
Roelof Wobben wrote: > When I change everything to this : > I get this message : > > Traceback (most recent call last): > File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 13, in > > rechthoek = Rectangle (punt,20,30) > TypeError: object.__new__() takes no parameters Hint:

Re: [Tutor] Can this be done easly

2010-09-19 Thread Peter Otten
Roelof Wobben wrote: >> Hint: why does this work: >> >>> def __init__(self, x=0, y=0): >> >> ...while this doesnt: >> >>> def _init_(self, base_point, width=0, length=0): >> >> Peter > Maybe because base_point has no value ? No. One __init__ has two underscores (correct) on each side, the other

Re: [Tutor] FW: Can this be done easly

2010-09-19 Thread Peter Otten
Roelof Wobben wrote: > For this exercise : > > 3.Write a function named move_rect that takes a Rectangle and two > parameters named dx and dy. It should change the location of the rectangle > by adding dx to the x coordinate of corner and adding dy to the y > coordinate of corner. > > Is this on

Re: [Tutor] input and raw input

2010-09-25 Thread Peter Otten
Brian Jones wrote: > No need for the 're' module. Even in the case where both can be used > together, you can still just use string methods: > s > '12, 13 14' s.replace(',', '').split(' ') > ['12', '13', '14'] I think to replace "," with " " and then split() without explicit separator

Re: [Tutor] if value in list of dictionaries

2010-09-28 Thread Peter Otten
Norman Khine wrote: > thanks for the reply, i think i have it now, perhaps it could be done > better > >>> topics.sort(key=itemgetter('name')) > >>> for i, t in enumerate(topics): > ... for (k, v) in t.iteritems(): > ... if v == 'other': > ... topics.append(top

Re: [Tutor] trouble with list.remove() loop

2010-09-28 Thread Peter Otten
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

Re: [Tutor] generating independent random numbers

2010-09-29 Thread Peter Otten
Carter Danforth wrote: > Thanks for the replies, Dave and Joel. The reason I'm not just using the > time or datetime modules for a random date is because it's restricted to > 1970-2038; I'm pulling dates from 1600-3099. Thanks a lot for the pointer The datetime module is not restricted to 1970...

Re: [Tutor] generating independent random numbers

2010-09-29 Thread Peter Otten
Ewald Ertl wrote: >> Just an attempt from my side: > The year 1500 didn't have a 29th of February, the 28th work for me but > 29th also fails here. datetime.date( 1500, 2, 28 ) > datetime.date(1500, 2, 28) datetime.date( 1500, 2, 29 ) > Traceback (most recent call last): > File "", line

Re: [Tutor] how to extract data only after a certain condition is met

2010-10-06 Thread Peter Otten
Eduardo Vieira wrote: > The other day I was writing a script to extract data from a file from > the line where a text is found to the end of the file. The same > functionality is this sed script: > '1,/regexp/'d > I couldn't put my head to work around this and came up with a solution > using list

Re: [Tutor] Converting from unicode to nonstring

2010-10-15 Thread Peter Otten
David Hutto wrote: > Hey Buddy Pals, ? > I receive the following output from a sqlite db > > (u'graph1', u'Line', u'222', u'BLUE', u'1,2,3,4', u'True', u'0,5,0,10') How did the string u"1,2,3,4" get into the database in the first place? The sqlite3 module offers a mechanism to convert data fro

Re: [Tutor] csv DictReader/Writer question

2010-10-21 Thread Peter Otten
Ara Kooser wrote: > Hello all, > > I have a csv file (from a previous code output). It looks like this: > Species2, Protein ID, E_value, Length, Hit From, Hit to, Protein ID2, > Locus Tag, Start/Stop, Species > Streptomyces sp. AA4, ZP_05482482, 2.82936001e-140, 5256, > 1824, > 2249

Re: [Tutor] csv DictReader/Writer question

2010-10-22 Thread Peter Otten
Ara Kooser wrote: > Thank you for your response. I did try reading the documentation but I > missed something (or several somethings in this case). So what I see in > the code you supplied is: > > with open(source, "rb") as instream: >reader = csv.DictReader(instream, skipinitialspace=True)

Re: [Tutor] Simple counter to determine frequencies of words in adocument

2010-11-20 Thread Peter Otten
Alan Gauld wrote: > The loop is a bit clunky. it would be clearer just to iterate over > a_list: > > for item in a_list: >words[item] = a_list.count(item) This is a very inefficient approach because you repeat counting the number of occurrences of a word that appears N times N times: >>> w

Re: [Tutor] If os.path.lexists() isn't working properly

2010-11-24 Thread Peter Otten
Susana Iraiis Delgado Rodriguez wrote: > Hello memebers: > > I'm writing a python script to validate if files with extension .prj > exist, if they exist it should write 1 or 0 into an excel cell. I've > working to do this properly, but I'm not getting the results I need. The > script doesn't find

Re: [Tutor] Random Number Question

2010-11-25 Thread Peter Otten
Alan Gauld wrote: import random > > It tries to import itself, which then tries to import itself, > which then. infinite loop time... I think it's more like - look up module random in sys.modules - module random not found in sys.modules; locate the file random.py - file random.py found

Re: [Tutor] if syntax expression help

2010-11-25 Thread Peter Otten
Rance Hall wrote: > I have a user entered variable that I need to check to see if they > entered one of the two legal values. > > But I only need to check this if one other fact is true. > > > we have a variable called "mode" whose value is either "add" or > "edit" based on how we where called

Re: [Tutor] normalize an array

2010-11-26 Thread Peter Otten
John wrote: > I know this is a simple problem, but I want to do it the most > efficient way (that is vectorized...) > > import numpy as np > > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) > b = np.sum(a,axis=1) > > for i,elem in enumerate(a): > a[i,:] = elem/b[i] > suggestions? I'm no

Re: [Tutor] permutations?

2010-12-02 Thread Peter Otten
Alex Hall wrote: > 1. Order matters; I meant to say that direction does not. That is, 123 > is not the same as 213, but 123 is the same as 321 since the second > example is simply a reversal. > 2. I am looking for all permutations and subpermutations (if that is a > word) of 1-n where the list mus

Re: [Tutor] SAVE FILE IN A SPECIFIC DIRECTORY

2010-12-06 Thread Peter Otten
Susana Iraiis Delgado Rodriguez wrote: [UPPER CASE text is interpreted as shouting in emails and usenet posts. Please don't shout. Because spammers do it all the time it's more likely to make potential readers turn away from your writ rather than pay extra attention.] > I'm trying to save file

Re: [Tutor] role playing game - help needed

2010-12-07 Thread Peter Otten
Robert Sjöblom wrote: >> Close, but remember that input() returns a string. You need numbers >> so you need to convert strings to integers. > > Actually, input() only accept integers, consider the following: input("input: ") > input: d > > Traceback (most recent call last): > File "", line

Re: [Tutor] role playing game - help needed

2010-12-07 Thread Peter Otten
Al Stern wrote: > Apologies for all my questions. Up to this point I have been able to work > out most of the challenges but I seem to have hit a wall. Can't seem to > make any progress and completely frustrated. > > I looked at the 11/21 discussion. From the documentation, I realized I > need

Re: [Tutor] role playing game - help needed

2010-12-07 Thread Peter Otten
Al Stern wrote: > I used the following code and got the following error. The result of input is always a string. > attributes["strength"] = input("\nHow many points do you want to assign to > strength?: ") Say you type 42 when you run your script. Then the above assignment is effectively at

Re: [Tutor] Code evaluation inside of string fails with __get_item

2010-12-11 Thread Peter Otten
Tim Johnson wrote: > This is a resend. I note that the original had an incorrect > `reply-to' ID attached to it. (sorry) > -- > I'm using Python 2.6.5. > The following problem is coming from inside of a complex code base > and involve

Re: [Tutor] Generating a python file

2010-12-14 Thread Peter Otten
C.T. Matsumoto wrote: > Is it possible to create files containing python code in the same sort > of way that you can generate text files. > > A simple example perhaps could be a persistent dictionary. Keys and > values are written to the dictionary in a file, that can be imported > later. For si

Re: [Tutor] Generating a python file

2010-12-14 Thread Peter Otten
Evans Anyokwu wrote: > The page you linked to above was not found. > Could you check the link again - Sorry, I accidentally stripped off the trailing 'l' during cut-and-paste. The correct link is http://docs.python.org/library/json.html Peter ___ Tu

Re: [Tutor] pyodbc/date values in MS Access

2010-12-15 Thread Peter Otten
Albert-Jan Roskam wrote: > Hi, > > I'm using pyodbc (Python 2.5) to insert records in an MS Access database. > For security reasons, question marks should be used for string replacement > [*]. The standard %s would make the code vulnerable to sql code injection. > Problem is, string replacement i

Re: [Tutor] Parameterized Queries failing on MySQL

2010-12-16 Thread Peter Otten
Shea Grove wrote: >> I'm using pyodbc to interact with MS SQL Server and I'm starting to >> support mysql. My issue is that when I use a parameterized query, it >> works for SQL Server, but crashes when I point to MySQL. I assume it raise an Exception. >> Is there a different syntax that I sh

Re: [Tutor] How to import python dictionary into MySQL table?

2010-12-17 Thread Peter Otten
Sean Carolan wrote: >> I have a database with a table called "systems" that contains an >> auto-increment id field, as well as fields for each of the keys in >> mydata.keys(). But I can't seem to get the syntax to import >> mydata.values() into the table. I think the problem may be that some >>

Re: [Tutor] calling setters of superclasses

2010-12-18 Thread Peter Otten
Gregory, Matthew wrote: > Hi all, > > Consider the following classes where PositiveX should constrain the > attribute _x to be positive and SmallX should further constrain the > attribute _x to be less than 10. > > class PositiveX(object): > def __init__(self): > self._x = 1 > @p

Re: [Tutor] doing maths on lists

2010-12-20 Thread Peter Otten
Dave Angel wrote: > from math import cos > > JME = 0.4 > L0A = [2.3, 4.65] > L0B = [1.8, 2.2] > L0C = [12.1, 4] > limit = len(L0A) > > L0 = sum(L0A[i]*cos(L0B[i]+L0C[i]*JME) for i in range(limit)) OP, if you are planning to do this "maths on lists" a lot you should have a look at numpy. With n

Re: [Tutor] Hangman game.....problem putting strings in a list.....

2010-12-21 Thread Peter Otten
Yasin Yaqoobi wrote: > # This is the line that gives me the error don't know why? > guessed[index] = " " + (letter); ,TypeError: 'str' object does not > support item assignment I don't get this far because I run into Traceback (most recent call last): File "hangman.py", line 69, in line =

Re: [Tutor] scraping and saving in file

2010-12-29 Thread Peter Otten
Tommy Kaas wrote: > I’m trying to learn basic web scraping and starting from scratch. I’m > using Activepython 2.6.6 > I have uploaded a simple table on my web page and try to scrape it and > will save the result in a text file. I will separate the columns in the > file with > #. > It works fin

Re: [Tutor] scraping and saving in file

2010-12-29 Thread Peter Otten
Tommy Kaas wrote: > Steven D'Aprano wrote: >> But in your case, the best way is not to use print at all. You are >> writing > to a >> file -- write to the file directly, don't mess about with print. >> Untested: >> >> >> f = open('tabeltest.txt', 'w') >> url = 'http://www.kaasogmulvad.dk/unv/pyt

Re: [Tutor] scraping and saving in file SOLVED

2010-12-29 Thread Peter Otten
Tommy Kaas wrote: > With Stevens help about writing and Peters help about import codecs - and > when I used \r\n instead of \r to give me new lines everything worked. I > just thought that \n would be necessary? Thanks. > Tommy Newline handling varies across operating systems. If you are on Windo

Re: [Tutor] Problem installing pyaudiere

2010-12-30 Thread Peter Otten
Danci Emanuel wrote: > I am trying to install the pyaudiere package on linux and I get the > following error: " AudioDevice.h:6: fatal error: audiere.h: No such file > or directorycompilation terminated. " I am interested if anyone managed to > solve this problem or if someone could suggest a pack

Re: [Tutor] Checkbox problem in Tkinter

2011-01-10 Thread Peter Otten
ANKUR AGGARWAL wrote: > and i got the output as - > [image: Screenshot.png] The image doesn't survive. > When i take the var as of string variable type i am unable to edit the > checkbox. It comes slected predefined and the widget in kindof Invisible > and > u can say uneditable. Can anybody t

Re: [Tutor] Checkbox problem in Tkinter

2011-01-10 Thread Peter Otten
Alan Gauld wrote: > > "ANKUR AGGARWAL" wrote > >> from Tkinter import * >> root=Tk() >> var=StringVar() >> c=Checkbutton(root,text="hello",variable=var,onvalue="",offvalue="") >> c.pack() >> root.mainloop() > > FWIW I get a different problem, namely that the var does not seem > to get

Re: [Tutor] Checkbox problem in Tkinter

2011-01-10 Thread Peter Otten
ANKUR AGGARWAL wrote: > Hey I write this code up > > from Tkinter import * > root=Tk() > var=StringVar() > c=Checkbutton(root,text="hello",variable=var,onvalue="",offvalue="") > c.pack() > root.mainloop() > > and i got the output as - > [image: Screenshot.png] > > When i take the var a

Re: [Tutor] Sorting a List

2011-01-12 Thread Peter Otten
Bill Campbell wrote: > On Wed, Jan 12, 2011, Corey Richardson wrote: >>Hello Tutors, >> >>I am generating XML definitions for animations to be used in a >>FIFE-based game. I need to sort the frames of the animations, and I am >>currently using: >>sorted([image for image in os.listdir(path) if imag

[Tutor] Determinw Tkinter checkbox state, was Re: question

2011-01-13 Thread Peter Otten
Stinson, Wynn A Civ USAF AFMC 556 SMXS/MXDED wrote: [In the future please take the time to choose a meaningful subject] > Can someone give me some sample code to use to determine if a checkbox > has been selected using Tkinter? thanks Method 1: check the state of the underlying variable: import

Re: [Tutor] end parameter in 2.7.1?

2011-01-15 Thread Peter Otten
Bill DeBroglie wrote: > Twice in two days...! > > Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which > is using Python 3.1. The author uses the end parameter in numerous > programs but this doesn't seem to translate to 2.7. Any advice as to > how I can specify the final string o

Re: [Tutor] Is it possible to tell, from which class an method was inherited from

2011-01-19 Thread Peter Otten
Jojo Mwebaze wrote: > Is it possible to tell, from which class an method was inherited from. > take an example below > > class A: >def foo(): > pass > class B(A): >def boo(A): > pass > class C(B): >def coo() > pass > class D(C): >def doo() > pass > dir (

Re: [Tutor] Decoding from strange symbols

2011-01-19 Thread Peter Otten
Oleg Oltar wrote: > I am trying to decode a string I took from file: > > file = open ("./Downloads/lamp-post.csv", 'r') > data = file.readlines() > data[0] > > '\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x0

Re: [Tutor] Is it possible to tell, from which class an method was inherited from

2011-01-20 Thread Peter Otten
Jojo Mwebaze wrote: > Thanks guys for the responses, > > inspect.classify_class_attrs(klass) > > does the magic Argh, undocumented functions. How did you find that gem? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription opt

Re: [Tutor] not understanding a recursion example

2011-01-21 Thread Peter Otten
Bill Allen wrote: > I am not understanding the following code (I did not write it). It > demonstrates walking a tree-like data structure using recursion. It does > run and produces reasonable output. I particularly do not understand the > "traverse.level" statements. Can anyone give me an idea

Re: [Tutor] ascii codec cannot encode character

2011-01-28 Thread Peter Otten
Alex Hall wrote: > Hello again: > I have never seen this message before. I am pulling xml from a site's > api and printing it, testing the wrapper I am writing for the api. I > have never seen this error until just now, in the twelfth result of my > search: > UnicodeEncodeError: 'ASCII' codec can'

Re: [Tutor] Wrapping my head around global variables!!

2011-01-28 Thread Peter Otten
Nevins Duret wrote: > Hello Python collective, > > I am trying to wrap my head around what exactly is causing me > not to get any output or error message in the following code: > >> #!/usr/bin/env python3.1 >> >> import random >> >> def main(): >> >> def chosen_letter(): >> >>

Re: [Tutor] RE module is working ?

2011-02-03 Thread Peter Otten
Karim wrote: > I am trying to subsitute a '""' pattern in '\"\"' namely escape 2 > consecutives double quotes: > > * *In Python interpreter:* > > $ python > Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for m

Re: [Tutor] RE module is working ?

2011-02-04 Thread Peter Otten
Karim wrote: > Recall: > > >>> re.subn(r'([^\\])?"', r'\1\\"', expression) > > Traceback (most recent call last): > File "", line 1, in > File "/home/karim/build/python/install/lib/python2.7/re.py", line > 162, in subn >return _compile(pattern, flags).subn(repl, string, count)

Re: [Tutor] RE module is working ?

2011-02-04 Thread Peter Otten
Karim wrote: > That is not the thing I want. I want to escape any " which are not > already escaped. > The sed regex '/\([^\\]\)\?"/\1\\"/g' is exactly what I need (I have > made regex on unix since 15 years). Can the backslash be escaped, too? If so I don't think your regex does what you think

Re: [Tutor] making object iterable

2011-02-05 Thread Peter Otten
Alex Hall wrote: > Hi all, > I have a class which has a list as an attribute, meaning you must say > something like: > for result in obj.results: ... > I want to make life a bit easier and let users just say: > for result in obj: ... > Here is what I have tried to make my class into an iterable on

Re: [Tutor] Splitting a string

2011-02-08 Thread Peter Otten
Christian Witts 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"

Re: [Tutor] Odd behavior with eval, list comps, and name lookup

2011-02-18 Thread Peter Otten
John wrote: > I noticed some odd behavior relating to eval(). First, a baseline case for > behavior: > def test(): > ... x = 5 > ... return [a for a in range(10) if a == x] > ... test() > [5] > > So far so good. Now let's try eval: > c = compile('[a for a in range(10) if a == x]'

Re: [Tutor] reading large text file as numpy array

2011-02-23 Thread Peter Otten
Jaidev Deshpande wrote: > I have a large text file with more than 50k lines and about 784 floats in > each line. > > How can I read the whole file as a single numpy array? Have you tried numpy.loadtxt()? ___ Tutor maillist - Tutor@python.org To uns

Re: [Tutor] Python object

2011-02-24 Thread Peter Otten
Christopher Brookes wrote: > Hi, i'm new in python. > I'm trying to create a small fight program in object. > > I've created __init__ (its works) but when i'm trying to display init > param i'm getting param and "None" every time. Why ? > > def GetAllAtrib(self): > print '---

Re: [Tutor] How to vectorize a constant function?

2011-02-25 Thread Peter Otten
Jose Amoreira wrote: > I am trying to define a constant vectorized function, that is, one that > returns 1. (for instance) when called with a scalar argument x and that > returns array([1.,1.,1.]) when the argument is a three-element array, etc. With the help of google I found http://docs.scipy.

Re: [Tutor] Code structure help

2011-03-11 Thread Peter Otten
Martin De Kauwe wrote: > Note I have cross posted this as I have only just found this mailing list > and perhaps it is the more appropriate place (I am not sure)? I think your question is appropriate for both lists, it just wasn't sexy enough for anyone on c.l.py to answer ;) > I have been wor

Re: [Tutor] getting the last file in a folder (reliably)

2011-03-22 Thread Peter Otten
Steven D'Aprano wrote: > files.sort() > the_file_name = files[-1] You don't need to sort if you want only one file: the_file_name = max(files) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.o

Re: [Tutor] Recursively flatten the list

2011-03-24 Thread Peter Otten
Dharmit Shah wrote: > I am learning Python and yesterday I cam across a definition wherein I was > supposed to flatten a list recursively. I am getting the solution properly > but wanted to know if I can optimize the code further. > > #!/usr/bin/env python > new_list=[] > def flatten(num_list): >

Re: [Tutor] script conversion windows -> linux error

2011-03-26 Thread Peter Otten
Rance Hall wrote: > On Fri, Mar 25, 2011 at 1:54 PM, Walter Prins wrote: >> >> On 25 March 2011 18:26, Rance Hall wrote: >>> config_version = config.get('versions','configver',0) >>> This line fails under 3.2 Linux with the error message: >>> TypeError: get() takes exactly 3 positional argumen

Re: [Tutor] Problem recognizing '{' character?

2011-03-29 Thread Peter Otten
Ben Hunter wrote: > Hi, > > I'm completing the Python lessons on YouTube that Google posted. At the > end of section 2 of day 2, there is a task to identify files then put them > in a zip file in any directory. The code is from the 'solution' folder, so > it's not something I wrote. I suspect I h

  1   2   3   4   5   6   7   8   9   10   >