[Tutor] List of lists help
Hello, I am completely baffled by this action and would appreciate any help. My problem is occurring within a class which is within a larger program; if I need to post the entire program let me know and I will. It's only about 250 lines so far. Anyways, I am using a list of lists to store data in a GUI game called goMoku. It is kind of like a connect five game, pretty simple. When a user clicks a certain square, this line is called to store the move: self.boardarray[row][col] = self.currentPlayer self.currentPlayer is either White or Black which are constants set to 1 and 2, so that when, say, the black player clicks on row 2 column 4, self.boardarray[2][4] will be set to 2. Instead, the program is setting multiple values within the list as 2. Here is an example output, when I click on (0,0): [[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. The board is 13X13 and position 0 for each list in the list of lists is being set to 2, while only position 0 in the first list should be changed to 2. To check for errors, I've surrounded the statement by print statements to see what's going on, like this: print self.boardarray print row,col,self.currentPlayer,self.boardarray[row][col] self.boardarray[row][col] = self.currentPlayer print self.boardarray My output is: [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. 0 0 2 0 [[2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], etc. I do not understand what is going on. Everything is as expected except that the extra positions are being assigned as 2. Can anyone suggest what is going wrong? Thanks, Ben ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List of lists help
[EMAIL PROTECTED] wrote: Hello, I am completely baffled by this action and would appreciate any help. My problem is occurring within a class which is within a larger program; if I need to post the entire program let me know and I will. It's only about 250 lines so far. Anyways, I am using a list of lists to store data in a GUI game called goMoku. It is kind of like a connect five game, pretty simple. When a user clicks a certain square, this line is called to store the move: self.boardarray[row][col] = self.currentPlayer The problem is most likely in how you construct your data structure. If you want to post a follow-up with code, extract those lines and see if you can construct the problem in = 10 lines of code. (any code with more than 15 lines is most likely too large to understand in the time that people take to read a post here) With respect to your problem, a similar problem has been discussed recently at this list with dictionaries instead of lists, please read http://mail.python.org/pipermail/tutor/2008-November/065283.html If it doesn't answer your question, try to re-construct the problem in a small example, and post that. Sincerely, Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what do you use @staticmethod for?
spir wrote: Good night, I have not yet found any use for this feature. Also, I do not really understand the difference with @classmethod, from the programmer's points of view (even if I get the difference on the python side). As I see it, a classmethod is a very ordinary method, except its 'owner' is a type. [But we cannnot express its definition with standard syntax, because it conflicts with instance method definition syntax.] I would be pleased to read your views about staticmethods, and the use cases you have for them -- that could not be done (the same way) with classmethods. For me, the difference is a somewhat conceptual one: I use class methods when the operation they're performing is not (possibly cannot be) tied to a specific instance of that class. The canonical application is as a class factory. So I have classmethods called things like .from_string which return an instance of the class which is their first parameter. This will therefore work from subclasses. On the other side of the coin, static methods don't (and can't) even rely on the class they're in so they're not very different from, say, module global functions. I use them if they are in concept a part of whatever functionality the class is offering, but don't (and shouldn't) depend on any instance or any class data. Examples in my own code include a method which returns login sessions from the Windows LSA within an LSA class: you don't need any kind of LSA policy handle to enumerate logons, but it fits conceptually within the idea of an LSA class whose other operations do rely on a policy handle, so I left it there and made it static. HTH TJG ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List of lists help
[EMAIL PROTECTED] wrote self.boardarray[row][col] = self.currentPlayer 4, self.boardarray[2][4] will be set to 2. Instead, the program is setting multiple values within the list as 2. Here is an example output, when I click on (0,0): [[2, 0, 0, 0, 0], [2, 0, 0, 0, 0], [2, 0, 0, 0, 0], etc. This is almost always caused by you initialising the data wrongly. You have set every item in your list to point to the same sublist. Something like L = [[0,0,0] *3] Now L contains 3 copies of the same list so when you change any one copy it is reflected in all of the other copies. L[0][1] = 6 L [[0,6,0],[0,6,0],[0,6,0]] You can avoid this by constricting the list using a list comprehension (or any of several other solutions) L = [[0,0,0] for n in range(3)] L[0][1] = 7 L [[0, 7, 0], [0, 0, 0], [0, 0, 0]] Remember that Python does everything by references so a = foo b = foo leaves a and b pointing at the same foo object not two copies of foo. The same applies to lists. If you want a copy you need to explicitly make a copy. L1 = [1,2] L2 = L1[:] Now L1 and L2 are two separate lists. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] import data (txt/csv) into list/array and manipulation
Hi, so for this part of the problem it goes a bit like this: I have a CSV file (file1) that contains three columns, column one contains a unique ID type str, columns two and three contain start and stop coordinates type int. the other file (file2) contains two columns, column one contains a single coordinate type int and the second column contains a value type float. What I would like to do is for example be able to grab the values from file2 that lies within range defind by the start,stop coordinates associated with an ID from file1. But most importantly I would like to be able to grab say the values from file1 that are from range((start-300),start) for every single ID in file1, I guess plot them in an array and then calculate the sum/ of these values and plot them, ie for ob1 in file get values from range((1025-300),1025), for ob2((1090-300),1090) for ob3((2200-300),2200) and then plot/calculate the sum assuming the have the same start coordinate, so x axis would be (step) values from 0-300 and y axis would be the sum of values from ob1,2,3 for every single step value from 0-300. does this make sense/ cheers http://www.nabble.com/file/p20599488/file1.csv file1.csv http://www.nabble.com/file/p20599488/file2.csv file2.csv Kent Johnson wrote: On Thu, Nov 13, 2008 at 9:50 AM, trias [EMAIL PROTECTED] wrote: PS I could maybe upload a couple of small example flies or a schematic to see what I mean A small example would be very helpful. Also please subscribe to the list. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- View this message in context: http://www.nabble.com/import-data-%28txt-csv%29-into-list-array-and-manipulation-tp20424075p20599488.html Sent from the Python - tutor mailing list archive at Nabble.com. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] first python program to find citeulike duplicates
hi everybody, i wrote this to solve the problem of exact duplicate entries in my citeulike library, that i wanted to remove. so i exported my entries in ris format, and then parsed the entries to find exact duplicates based on matching fields. the exact duplicates came about because i uploaded the same RIS file twice to my citeulike library, as a result of the upload being interrupted the first time. it works (i think), but since this is my very first python program, i would really appreciate feedback on how the program could be improved.. thanks much suresh ~~ InFileName= original_library.ris; INBIBFILE=open(InFileName,'r') OutFileName= C:/users/skrishna/desktop/library_without_duplicates.ris; OUTBIBFILE=open(OutFileName,'w') OutDupFileName= C:/users/skrishna/desktop/library_of_duplicates.ris; OUTDUPBIBFILE=open(OutDupFileName,'w') current_entry=[] current_keyval=[] current_keys=[] numduplicates=0 for line in INBIBFILE: #large file, so prefer not to use readlines() if not current_entry and line.isspace(): continue #dont write out successive blanks or initial blanks elif current_entry and line.isspace(): #reached a blank that demarcates end of current entry keyvalue=''.join(current_keyval) #generated a key based on certain fields if keyvalue not in current_keys: #is a unique entry current_keys.append(keyvalue) #append current key to list of keys current_entry.append(line) #add the blank line to current entry OUTBIBFILE.writelines(current_entry) #write out to new bib file without duplicates current_entry=[] #clear current entry for next one current_keyval=[] #clear current key else: numduplicates=numduplicates+1 #increment the number of duplicates current_entry.append(line) #add the blank line at end of entry OUTDUPBIBFILE.writelines(current_entry) #write out to list of duplicates file current_entry=[] #clear current entry for next one current_keyval=[] #clear current key elif len(line)2: #not a blank, so more stuff in currrent entry current_entry.append(line) if line[0:2] in ('TY','JF','EP','TI','SP','KW','AU','PY','UR'): #only if line starts with these fields current_keyval.append(line) #append to current key INBIBFILE.close() OUTBIBFILE.close() OUTDUPBIBFILE.close() print numduplicates ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] import data (txt/csv) into list/array and manipulation
trias wrote: Hi, so for this part of the problem it goes a bit like this: I have a CSV file (file1) that contains three columns, column one contains a unique ID type str, columns two and three contain start and stop coordinates type int. the other file (file2) contains two columns, column one contains a single coordinate type int and the second column contains a value type float. What I would like to do is for example be able to grab the values from file2 that lies within range defind by the start,stop coordinates associated with an ID from file1. But most importantly I would like to be able to grab say the values from file1 that are from range((start-300),start) for every single ID in file1, I guess plot them in an array and then calculate the sum/ of these values and plot them, ie for ob1 in file get values from range((1025-300),1025), for ob2((1090-300),1090) for ob3((2200-300),2200) and then plot/calculate the sum assuming the have the same start coordinate, so x axis would be (step) values from 0-300 and y axis would be the sum of values from ob1,2,3 for every single step value from 0-300. does this make sense/ mostly, although you lost me when you started talking about ranges. Computer programming is often about making small steps at a time (trying to do everything at the same time tends to make yourself get lost in what to do first). In your case, I'd start with reading your first csv file (with the csv Python module) into memory. Once you have done that, get for example a list of start/stop coordinates from the loaded data. Then start loading the second csv file, see how you can find a value, and then a range of values. Once you have done that, you can implement you first objective. After that start thinking about storing in arrays, plotting, etc. Sincerely, Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] first python program to find citeulike duplicates
Suresh Krishna wrote: it works (i think), but since this is my very first python program, i would really appreciate feedback on how the program could be improved.. First of all, welcome, new Python programmer, My main trouble with the program is lack of structure, some lines deal with individual lines of the input file, while other deal with complete citation-records. I think the program would improve if this is more clearly expressed in the code. One of the reasons that you got the current structure may be due to the use of the 'for line in bibfile' loop, which gives you a new line at only one point in the program. Such a for-loop is good for simple line processing (for each line do ...), but your program has grown beyond that imho. For this reason I'd like to propose to throw out the for-loop, and use a while-loop with three parts instead. For simplicity, I left out the handling of the records (which we can discuss later perhaps) inbibfile = open(InFileName,'r') finished = False while not finished: # Read skip blank lines while True: line = inbibfile.readline() if len(line) == 0: finished = True break # end of file detected if len(line.rstrip()) 0: # Line contains non-white-space break # else it was a blank line, skip, read next line if finished: break # line contains the first non-whitespace line of a new record # read the entire record until the next empty line or EOF current_entry = [line] while True: line = inbibfile.readline() if len(line) == 0: finished = True break # Found EOF if len(line.rstrip()) 0: current_entry.append(line) else: # Found an empty line, finished with current record break # finished reading (empty line or EOF encountered) ## Do something with current_entry # if not finished, do the next record inbibfile.close() You can go further by introducing a few functions: inbibfile = open(InFileName,'r') finished = False while not finished: finished, line = read_blank_lines(inbibfile) if finished: break # line contains the first non-whitespace line of a new record current_entry = make_new_record(line) finished, current_entry = read_record_lines(current_entry, inbibfile) # finished reading (empty line or EOF encountered) ## Do something with current_entry inbibfile.close() and the functions then contain the details of each step. A few comments about your current program: InFileName= original_library.ris; In Python, you don't end a line with a ';'. Also, 'InFileName' is a constant, which is normally given an all-uppercase name. OUTDUPBIBFILE=open(OutDupFileName,'w') current_entry=[] numduplicates=0 One of the most difficult things to do in programming is achieving consistency. Above you have 3 global variables, and you use several different way of writing their names. You should try to write them the same. The big advantage of consistent names is that just by looking at a name you know what kind of thing it is, which reduces the chance of making errors in your program. (Don't feel bad about it, this seems a very simple and obvious problem but in fact it is very hard to achieve, especially for larger programs and projects with several people). if keyvalue not in current_keys: #is a unique entry current_keys.append(keyvalue) #append current key to list of keys current_entry.append(line) #add the blank line to current entry OUTBIBFILE.writelines(current_entry) #write out to new bib file without duplicates current_entry=[] #clear current entry for next one current_keyval=[] #clear current key Look at the code of each line above, then look at the comment at the same line. What does the comment tell you that the code didn't? continue #dont write out successive blanks or initial blanks elif current_entry and line.isspace(): #reached a blank that demarcates end of current entry keyvalue=''.join(current_keyval) #generated a key based on certain fields elif len(line)2: #not a blank, so more stuff in currrent entry Now do the same here. You see the difference? In the first lines you repeat your code in words. In the second lines, you tell what you aim to achieve at that line, ie WHY do you do what you are doing rather than just WHAT does the line do (since that is already defined in the code). In general, there is no need to comment each line. You may also assume that the reader knows Python (otherwise there is little value for him reading the code). Try to make 'blocks' of code with one or more empty lines in between (see my example code), and write a comment what that block as a whole aims to do. Hope I didn't critize you too much. For a first Python program it is quite nice. Sincerely,
Re: [Tutor] Scrolling through output in shell
Lie Ryan wrote: As the manpage of less explains: 'less - opposite of more' I've always heard it explained that more is the original paging program of UNIX, and when a new pager was created (by GNU?) they named it less because, as we all know, less is more[1]. Simón [1] http://www.phrases.org.uk/meanings/226400.html (for those to whom English is not a primary language, or just anyone who doesn't get the joke.) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Scrolling through output in shell
Lie Ryan wrote: As the manpage of less explains: 'less - opposite of more' I've always heard it explained that more is the original paging program of UNIX, and when a new pager was created (by GNU?) they named it less because, as we all know, less is more[1]. Simón [1] http://www.phrases.org.uk/meanings/226400.html (for those to whom English is not a primary language, or just anyone who doesn't get the joke.) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List of lists help
Alan Gauld [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] [snip] Something like L = [[0,0,0] *3] I think you meant: [[0,0,0]]*3 [[0, 0, 0], [0, 0, 0], [0, 0, 0]] -Mark Now L contains 3 copies of the same list so when you change any one copy it is reflected in all of the other copies. L[0][1] = 6 L [[0,6,0],[0,6,0],[0,6,0]] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] [Fwd: Re: what do you use @staticmethod for?]
[forwarded to the list] Thank you for your answers. I found Tim's example below especially helpful. Still, I am a bit surprised. Would you agree with the following: -1- Methods are usually defined as functions bound to an object, often called 'owner', meaning especially that the object is then available from insidethe method for operations to apply on it, or with it. Static methods aren't bound, no object is passed as arg, so they are not methods in fact. Simply the calling syntax looks like a method call because of the prefix. From this point of view, static methods may alternatively be called class functions instead. -2- The differences between a standard function (defined e.g. at module level) and a static method are that the latter is defined inside a class's scope, and called using the class name as prefix. This can be appropriate, or even relevant, for the developper or reader. -3- Semantically speaking: at the process/python level, there is no real difference, behind the scene a static method actually is a function. At the programmer's level, defining a static method is (can be) meaningful, for it matches the problem, his/her point of view, or design choice. In short: it makes sense. If this is True ;-), then it is the first Python feature I notice that simply exists for such a (relevant, imo) reason. Now, I will probably find many appropriate use cases for static methods. Denis Tim Golden a écrit : spir wrote: Good night, I have not yet found any use for this feature. Also, I do not really understand the difference with @classmethod, from the programmer's points of view (even if I get the difference on the python side). As I see it, a classmethod is a very ordinary method, except its 'owner' is a type. [But we cannnot express its definition with standard syntax, because it conflicts with instance method definition syntax.] I would be pleased to read your views about staticmethods, and the use cases you have for them -- that could not be done (the same way) with classmethods. For me, the difference is a somewhat conceptual one: I use class methods when the operation they're performing is not (possibly cannot be) tied to a specific instance of that class. The canonical application is as a class factory. So I have classmethods called things like .from_string which return an instance of the class which is their first parameter. This will therefore work from subclasses. On the other side of the coin, static methods don't (and can't) even rely on the class they're in so they're not very different from, say, module global functions. I use them if they are in concept a part of whatever functionality the class is offering, but don't (and shouldn't) depend on any instance or any class data. Examples in my own code include a method which returns login sessions from the Windows LSA within an LSA class: you don't need any kind of LSA policy handle to enumerate logons, but it fits conceptually within the idea of an LSA class whose other operations do rely on a policy handle, so I left it there and made it static. HTH TJG ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] what do you use @staticmethod for?
Forwarded to group. Would you mind telling me what you think of the following? /Inside/ class definition, conflict may happen between class an instance attributes. Non-callable attributes (say, properties) are diffenreciated using the syntactic convention that instance properties are prefixed with a special placeholder (usually self) taking the place of future instance name: Its not merely a syntactic convention. self is a very real local variable within the method. It is no different to any other local variable. For methods, the same convention applies at method call: * class: Clas.method(args) * instance: self.method(ergs) Strangely enough (from my point of view), this nice rule is broken at method definition: * class: Noneexpected def method(args) * instance: def method(self,args)expected def self.method(args) But self is not defined at the class level. It is not just a naming feature, self is a real local variable with a value assigned at call time just like any other function/method parameter. It does not exist outside of a method definition. In fact the self parameter of each method is different: class C: def m1(self): pass def m2(this): pass def m3(xyz): pass self, xyz and this are all independant and equally valid names for the instance reference that will be passed in when the method is called. Indeed the following is perfectly valid code: c = C() C.m3(c) # same as c.m3() As I see it, the syntax for instance method definition conflicts with 'regular' class method def. Regular class method definition is not regular. Thats the real issue! We define instance methods far more often thabn class methods so that has been optimised. The class method definition has been simplified as far as possible by the decorator but it is admittedly differenmt to the normal function definition protocol. But... If 'self' (or any other word) would be used as prefix for method def, this would be very irregular. It would not fit well with normal function definition. An instance method definition currently looks exactly like (and operates like) a normal function except its inside a class. It just happens to have some syntactic sugar added to make the calling usage more convenient. could define class methods normally. We do define them normally but we assign them as class methods as an extra step. Its not the definition of the method that is different its the step of assigning them to be class methods thats awkward. Additionally, this would allow instance attributes to be present at class top-level scope, not only inside methods. Which may be good for readibility Perhaps, but would you still allow instanc attributes to be assigned outside of the class definition, for that too is possible: class D: pass d = D() d.foo = 42 # add an attribute to the instance print d.foo allowing to clearly show for instance objects fields, which presently are randomly created here and there inside methods. Or as above, outside methods. Object instances are just data structures like any other, so we can add to them at any time once created. programmers use __init__ as field list declaration by doing false initialisations: def __init__(self, arg1): self.arg1 = arg1 # real init self.arg2 = 0# false init 'showing' arg2 Yes, that's a matter of taste, and to a large extent background. Personally I like it but many don't do that. Remember that class methods, and indeed class attributes, are used so rarely that this is simply not an issue for most programmers. If you come from another OOP language it can seem, a bit odd in Python initially but it does have an elegant simplicity that exposes the underlying implementation while retaining ease of use. When you read Python code it's very easy to see how the underlying dictionary upon which classes and objects are built are being used. HTH Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List of lists help
Mark Tolonen [EMAIL PROTECTED] wrote L = [[0,0,0] *3] I think you meant: [[0,0,0]]*3 [[0, 0, 0], [0, 0, 0], [0, 0, 0]] Yes indeed, to much haste and not enough testing! Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Decimal fixed point representation
I'm trying to get my head around the Decimal module to understand how to represent a decimal floating point number as an integer (or integers). Am I barking mad or is this possible? Dinesh ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Decimal fixed point representation
Dinesh B Vadhia wrote: I'm trying to get my head around the Decimal module to understand how to represent a decimal floating point number as an integer (or integers). Huh? That makes no sense to me! Examples please. -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Decimal fixed point representation
Dinesh B Vadhia [EMAIL PROTECTED] wrote I'm trying to get my head around the Decimal module to understand how to represent a decimal floating point number as an integer (or integers). I'm not sure what you mean by that. Is it the use of the Decimal module you are querying? Is it how to represent a ecimal fraction as an integer - ie how to lose the numbers after the point? Is it how to represent it as a common/vulgar fraction eg 1.234 = 1234/1000 Or something else? Am I barking mad or is this possible? It is possible that you are barking mad I suppose. As to whether what you are asking about decimals is possible, that depends on what you are actually asking :-) Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor