[Tutor] Implementing sets of user-defined objects
Dear Tutors, I am tring to deal with some repeated data, and hence repeated objects (I construct objects from the data). I had hoped to use a set to uniquify the objects. However, I am having problems with defining uniqueness. I have googled/ looked at the Python docs/ read DITP and Alan's website, but I'm still not clear how the set() determines object uniqueness. There seem to be some references to __cmp__() and __eq__(), but I'm not clear what I should be using. Any pointers very welcome. Matt Sent from my BlackBerry® wireless device ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Implementing sets of user-defined objects
On Fri, 23 Jul 2010 09:22:55 pm m...@doctors.net.uk wrote: > Dear Tutors, > > I am tring to deal with some repeated data, and hence repeated > objects (I construct objects from the data). > > I had hoped to use a set to uniquify the objects. However, I am > having problems with defining uniqueness. The objects need to define __eq__ and __hash__, and they must be immutable. The easy way to do so is to inherit from something which is already immutable, say strings, ints, tuples or floats: class MyObject(int): """Just like an int, but coloured purple.""" def __init__(self, *args): self.colour = 'purple' Otherwise, something like this recipe should do the job: class MyObject(object): def __init__(self, a, b): self._value = (a, b) # Private attribute, don't touch this. @property def value(self): return self._value def __eq__(self, other): if isinstance(other, MyObject): return self.value == other.value return NotImplemented # Let the other object try. def __ne__(self, other): return not self == other def __hash__(self): return hash(self.value) If x and y are instances of your class, and x equals y, then hash(x) *must* equal hash(y). (The opposite doesn't apply though... if x and y hash equal, they don't necessarily have to equal.) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] position of an element in list:
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
Re: [Tutor] position of an element in list:
You can do it with any iterator Astr.index('o') I'm not sure what happens when there are multiple instances of 'o' though, check the docs on index. Sent from my iPhone On Jul 23, 2010, at 8:22 AM, 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 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how i can change two lists into one directory
On 07/23/2010 08:01 AM, Robert wrote: looks like this guy figured out how to send email in a loop User-Agent: Mutt/1.5.20 (2009-06-14) Or just discovered Mutt but hasn't figured out the keybindings yet. -- random spiel: http://lonetwin.net/ what i'm stumbling into: http://lonetwin.stumbleupon.com/ ___ 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] position of an element in list:
On Fri, 23 Jul 2010 11:22:54 pm 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? str1.find("o") will return the index of the first "o", or -1 if not found. str1.rfind("o") does the same, but searches from the right instead of the left. str1.index("o") is like find, but it raises an exception instead of returning -1. Naturally there is a rindex as well. -- Steven D'Aprano ___ 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 16:43, Steven D'Aprano wrote: On Fri, 23 Jul 2010 11:22:54 pm 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? str1.find("o") will return the index of the first "o", or -1 if not found. str1.rfind("o") does the same, but searches from the right instead of the left. str1.index("o") is like find, but it raises an exception instead of returning -1. Naturally there is a rindex as well. For the OP and possibly others, all of these methods have optional start and end arguments. Help for find shows:- 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. Mark Lawrence ___ 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:
"Vineeth Rakesh" wrote 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? Others have answered but don't forget Python's help() facility. help(str) Would have probably got your answer a lot faster than posting a question and waiting for replies. We don't mind helping but for these kinds of question its usually quicker to try a help(), dir() or even a Google search first. It saves your time and ours. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Difficulty Understanding Example Code for Blender Script
Oh ok. So orientation is an optional parameter. That makes sense. Alright well thanks for the help And yeah next time it would probably be better to try the blender forums. thanks though On Thu, Jul 22, 2010 at 3:06 AM, David Hutto wrote: > On Thu, Jul 22, 2010 at 2:47 AM, Marc Tompkins > wrote: > > On Wed, Jul 21, 2010 at 9:48 PM, Andrew Martin > > wrote: > >> > >> This code was part of a Blender script to build a 3d bar graph, so I > don't > >> know if understanding Blender is a prereq for understanding this code. > The > >> function is for the axis labels. > >> > >> def label(text,position,orientation='z'): > >> txt=Text3d.New('label') > >> txt.setText(text) > >> ob=Scene.GetCurrent().objects.new(txt) > >> ob.setLocation(*position) > >> if orientation=='x': > >> ob.setEuler(-pi/2.0,0,0) > >> elif orientation=='z': > >> ob.setEuler(0,0,pi/2.0) > >> print 'label %s at %s along %s' %(text,position,orientation) > >> > >> I understand it for the most part except for the orientation part. I > >> assume orientation is for the 3d text object, but how is it determined > >> whether it is x or z? > > > > I don't use Blender myself, so this will be a more generic, high-level > > answer... > >> > >> def label(text,position,orientation='z'): > > > > This definition specifies that label() takes two mandatory parameters - > text > > and position - and one optional parameter, orientation. What makes > > "orientation" optional is the fact that a default value is supplied: > > "orientation='z'". In other words, "orientation" is equal to "z" unless > you > > specify otherwise in your call to label(). > > Seeing as how blender is 3d graphics, have you tried the 'newbie > fidget with it', and typed in w(quaternion),x, or y to see what > occurs. Also, have you looked into the hierarchy to see if z, which > looks as though it's contained in a string, is an input variable > declared elsewhere as an integer, or represents something else in it's > usage. Z can mean global, or object orientation in blender from what I > see. > > > > > Take a look at this section of the Python docs: > > > http://docs.python.org/tutorial/controlflow.html#more-on-defining-functions > > > > Hope that helps... > > > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] decorators
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 comments are getting included in the list that is getting returned. I was thinking I could do a candidate_line.find(".com") to set the email addresses apart, but how do I tell the computer to not include the lines it finds with ".com" in them in the list? The part of my code that I'm hoping to include this in looks like this: #parse out the names of the decorators from those lines return_decorators= [] for ele in subset_lines: candidate_line, line_number = ele candidate_line = candidate_line.strip() i = candidate_line.find("(") j = candidate_line.find("#") #if () is in the last spot if i == -1: #if () is in the last spot and the decorator is in a comment if j == 0: #get rid of ( and # candidate_line = candidate_line[2:i] #if () is in the last spot and the decorator is not in a comment elif j != 0: candidate_line = candidate_line[1:i] #if there are not ()'s in the last spot elif i != -1: #if there are not ()'s, but the decorator is in a comment if j == 0: candidate_line = candidate_line[2:] #if there are not ()'s and the decorator isn't in a comment elif j != 0: candidate_line = candidate_line[1:] elif candidate_line.find(".com"): candidate_line != candidate_line return_decorators.append((line_number, candidate_line)) return return_decorators ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators
On Friday 23 July 2010 11:53 PM, 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("@") How about using something like candidate_line.strip.startswith('@') and calculate_line.find('.') == -1 There are few more cases where above may fail. In that case you may want to use re module instead. e.g. @test_decorator # this is test comment. because all of our decorators start with the @ symbol. The problem I'm having is that the email addresses that are included in the comments are getting included in the list that is getting returned. I was thinking I could do a candidate_line.find(".com") to set the email addresses apart, but how do I tell the computer to not include the lines it finds with ".com" in them in the list? The part of my code that I'm hoping to include this in looks like this: #parse out the names of the decorators from those lines return_decorators= [] for ele in subset_lines: candidate_line, line_number = ele candidate_line = candidate_line.strip() i = candidate_line.find("(") j = candidate_line.find("#") #if () is in the last spot if i == -1: #if () is in the last spot and the decorator is in a comment if j == 0: #get rid of ( and # candidate_line = candidate_line[2:i] #if () is in the last spot and the decorator is not in a comment elif j != 0: candidate_line = candidate_line[1:i] #if there are not ()'s in the last spot elif i != -1: #if there are not ()'s, but the decorator is in a comment if j == 0: candidate_line = candidate_line[2:] #if there are not ()'s and the decorator isn't in a comment elif j != 0: candidate_line = candidate_line[1:] elif candidate_line.find(".com"): candidate_line != candidate_line return_decorators.append((line_number, candidate_line)) return return_decorators ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators
On Sat, 24 Jul 2010 04:23:41 am 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 > comments are getting included in the list that is getting returned. First of all, to solve this problem *properly* you will need a proper parser to walk over the code and look for decorators, ignoring comments, skipping over strings, and similar. But that's hard, or at least I have no idea how to do it, so the alternative is a basic filter like you are doing. If you're using Linux, Mac or some other Unix, the fastest solution would be to use grep. But ignoring that, think about what a decorator line is. You suggest above that a candidate line is a decorator if it has a @ sign in it. But that's incorrect. This is not a decorator: # send an email to st...@something.net or geo...@example.gov.au But this might be: @decorator So let's start with a simple little generator to return lines as a candidate decorator only if it *starts* with an ampersand: def find_decorators(lines): """Return likely decorators from lines of text.""" for line in lines: line = line.lstrip() # ignore leading spaces if line.startswith('@'): yield line That's still not fool-proof, only a proper Python parser will be fool-proof. This will be fooled by the *second* line in something like: instructions = """If you have a problem with this, please call Fred @ accounts and tell him to reset the modem, then try again. If it still doesn't work blah blah blah """ So, not fool-proof, but it does the job. You use find_decorators like this: # Process them one at a time. for decorator_line in find_decorators(open("source.py")): print decorator_line To get them all at once, use: list_of_decorators = list(find_decorators(open("source.py"))) How can we improve this? At the moment, find_decorators happily returns a line like this: @decorator # This is a comment but you probably don't care about the comment. So let's make a second filter to throw it away: def remove_comments(lines): for line in lines: p = line.find('#') if p > -1: # Keep characters up to but not including p, # ignoring trailing spaces yield line[:p].rstrip() else: yield line And now apply this filter only to decorator lines: f = open("source.py") for decorator in remove_comments(find_decorators(f)): print decorator To get them all at once: f = open("source.py") results = list(remove_comments(find_decorators(f))) Again, this is not foolproof. If you have a decorator like this: @decorator("this takes a string argument with a # inside it") the filter will return: @decorator("this takes a string argument with a But, and I repeat myself like a broken record, if you want fool-proof, you need a proper parser, and that's hard. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] decorators
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 comments are > getting included in the list that is getting returned. > I was thinking I could do a candidate_line.find(".com") to set the email > addresses apart, but how do I tell the computer to not include the lines > it finds with ".com" in them in the list? You can use the tokenize module to do the heavy lifting, see http://docs.python.org/library/tokenize.html Here's an example: $ cat find_decos.py import tokenize from collections import defaultdict class Token: def __init__(self, token): self.string = token[1] self.lineno = token[2][0] def find_decos(instream, filename, decos): tokens = (Token(token) for token in tokenize.generate_tokens(instream.readline)) for token in tokens: if token.string == "@": lineno = token.lineno qname = [next(tokens).string] for token in tokens: if token.string == ".": qname.append(next(tokens).string) else: break decos[".".join(qname)].append((lineno, filename)) def main(): import sys files = sys.argv[1:] if not files: # read filenames from stdin files = (line.strip() for line in sys.stdin) decorators = defaultdict(list) for filename in files: with open(filename) as instream: find_decos(instream, filename, decorators) for name in sorted(decorators): print name for location in decorators[name]: print "%8d %s" % location if __name__ == "__main__": main() if False: def f(): """ @not_a_decorator """ return g # @not_a_decorator @alpha def first(x): return "u...@example.com" @beta @gamma . one def second(): pass @delta.two.three.four(*args) @epsilon(42) def third(): pass The if False:... suite is of course not a necessary part of the script, it's just a trick to cram in a few decorators for the script to find when you run it over itself: $ python find_decos.py find_decos.py alpha 50 find_decos.py beta 54 find_decos.py delta.two.three.four 59 find_decos.py epsilon 60 find_decos.py gamma.one 55 find_decos.py Alternatively you can feed filenames via stdin: $ find /usr/lib/python2.6 -name \*.py | python find_decos.py | tail 429 /usr/lib/python2.6/dist- packages/usbcreator/frontends/kde/frontend.py 434 /usr/lib/python2.6/dist- packages/usbcreator/frontends/kde/frontend.py 446 /usr/lib/python2.6/dist- packages/usbcreator/frontends/kde/frontend.py threaded 166 /usr/lib/python2.6/dist- packages/softwareproperties/kde/DialogMirror.py withResolverLog 572 /usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeCache.py 858 /usr/lib/python2.6/dist-packages/DistUpgrade/DistUpgradeCache.py wraps 81 /usr/lib/python2.6/contextlib.py $ Peter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] can i run the last saved input again
hey this is a crazy question but i want to know it.. suppose i have this code a=raw_input("enter the string :") print a then i type python prog.py output: enter the string:hello hello now i want to ask is there's any way that python remembers the input i gave it to last time and it just give me the output when i again run python prog.py?? i mean i dont need to give input again. I just need to give input only first time and when i run the prog again it will pick up the previous one output is it possible??? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can i run the last saved input again
On Sat, Jul 24, 2010 at 11:16 AM, ANKUR AGGARWAL wrote: > hey this is a crazy question but i want to know it.. > suppose i have this code > > a=raw_input("enter the string :") > print a > > then i type python prog.py > > output: > enter the string:hello > hello > > > now i want to ask is there's any way that python remembers the input i gave > it to last time and it just give me the output when i again run python > prog.py?? i mean i dont need to give input again. I just need to give > input only first time and when i run the prog again it will pick up the > previous one output > is it possible??? > you need to serialize the input as everything goes out of memory once program exits. > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vishwajeet Singh +91-9657702154 | dextrou...@gmail.com | http://bootstraptoday.com Twitter: http://twitter.com/vishwajeets | LinkedIn: http://www.linkedin.com/in/singhvishwajeet ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can i run the last saved input again
On Sat, 24 Jul 2010 03:46:15 pm ANKUR AGGARWAL wrote: [...] > now i want to ask is there's any way that python remembers the input > i gave it to last time and it just give me the output when i again > run python prog.py?? i mean i dont need to give input again. I > just need to give input only first time and when i run the prog again > it will pick up the previous one output > is it possible??? Of course it is possible, many programs do it. You need to save the information you want to remember to a file, then later read it from disk. Here's a skeleton of the idea: look for the config file if it exists: then read the answer from the file if it doesn't exist, or you can't read from it: then ask the question try to save the answer in the config file do whatever work you want with the answer The ConfigParser module will be useful for writing the config file. Something like this should do the job: import ConfigParser ini = ConfigParser.ConfigParser() if ini.read('mysettings.ini'): # File exists, so use it. answer = ini.get('main', 'answer') else: # No config file. Get the answer from the user, and try to save it. answer = raw_input("Answer this question! ") answer = answer.strip() ini.add_section('main') ini.set('main', 'answer', answer) f = open('mysettings.ini', 'w') ini.write(f) f.close() print "Your answer is", answer although this needs better error checking, particularly where it tries to write the config file. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] can i run the last saved input again
On Sat, Jul 24, 2010 at 11:16 AM, ANKUR AGGARWAL wrote: > hey this is a crazy question but i want to know it.. > suppose i have this code > > a=raw_input("enter the string :") > print a > > then i type python prog.py > > output: > enter the string:hello > hello > > > now i want to ask is there's any way that python remembers the input i gave > it to last time and it just give me the output when i again run python > prog.py?? i mean i dont need to give input again. I just need to give > input only first time and when i run the prog again it will pick up the > previous one output > is it possible??? > Think about the consequences when python will start remembering the input. > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- ~l0nwlf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor