Re: [Tutor] Multiple file open
Thank You Very Much :) Walter. It WOrked I did the "except" closing. Thanks Nitin On Sat, Aug 21, 2010 at 2:17 AM, Walter Prins wrote: > > Hello Nitin, > > On 20/08/10 16:21, nitin chandra wrote: >> >> import sys,os, fileinput >> > > [...] >> >> while True: >> try: >> line1 = fp1.readline().split(",") >> line2 = fp2.readline().split(",") >> > > [...] >> >> fp3.write(str3) >> > > You're missing the completion for the try/finally block. Try adding an > exception handler or comment out the "try" statement for the time being. > > Walter > ___ > Tutor maillist - tu...@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] design of Point class
On Sat, 21 Aug 2010 11:50:40 am Steven D'Aprano wrote: > On Sat, 21 Aug 2010 08:08:56 am Alan Gauld wrote: > > Every time you change the interface of inherited methods you > > create for yourself extra work in converting types to match the > > superclass. But that is often easier than rewriting the methods > > from scratch. > > Every time you change the interface of inherited methods, you > probably shouldn't. Oops, that's a generic "you", not Alan. After all, he went on to mention Liskov in the very next paragraph. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehension for dicts?
On Sat, 21 Aug 2010 01:47:12 am bob gailer wrote: > > Well yes, but I pointed out that you *can* bail out early of > > for-loops, but not list comprehensions. The whole point is with a > > list comp, you're forced to iterate over the entire sequence, even > > if you know that you're done and would like to exit. > > Take a look at itertools.takewhile! > > result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] Which is an excellent solution to the problem, and I had forgotten about it, but takewhile doesn't magically cause the list comprehension to exit. The list comp still runs over the entire input list, it's just that it sees a smaller input list. takewhile replaces the input sequence with a new sequence that stops at a certain point, so you could write: result = [] for i in itertools.takewhile(lambda x:i<10, seq): result.append(i) as well. Next time some Perl hacker accuses Python of being "Only one way to do it", you can just laugh at them :) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
On Sat, 21 Aug 2010 08:08:56 am Alan Gauld wrote: > Every time you change the interface of inherited methods you > create for yourself extra work in converting types to match the > superclass. But that is often easier than rewriting the methods > from scratch. Every time you change the interface of inherited methods, you probably shouldn't. Firstly, it probably breaks the Liskov Substitution Principle. The LSP says, essentially, if you subclass A to make B, you should be able to use a B anywhere you can use an A. (After all, instances of B are also instances of A.) Here's an example of what not to do: class Vehicle: def start(self, key): ignition.insert(key) ignition.turn() # raises exception if out of fuel def go(self, key): self.start(key) self.handbrake = 'off' self.gear = 'drive' self.accelerate() class Truck(Vehicle): # add other truck-like methods class KeylessTruck(Truck): # Some military vehicles are designed to not require keys. # When on a battlefield, there's nothing worse than being # unable to find the car keys! def go(self): self.start() self.handbrake = 'off' self.gear = 'drive' self.accelerate() def start(self): ignition.turn() # Actually a push button, but nevermind. Can you see the problem? If the caller is expecting a Truck, and pass a key to the truck.go() method, they will get an exception if you give them a KeylessTruck instead of a Truck. This is a Bad Thing. Secondly, changing method interfaces is not compatible with multiple inheritance and super(). You can probably get away with it if you stick to single inheritance, but it's still a bad thing to do. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
On Sat, 21 Aug 2010 01:45:18 am Gregory, Matthew wrote: > Hi all, > > I often struggle with object design and inheritance. I'd like > opinions on how best to design a Point class to be used in multiple > circumstances. > > I typically deal with geographic (either 2D or 3D) data, yet there > are occasions when I need n-dimensional points as well. My thought > was to create a superclass which was an n-dimensional point and then > subclass that to 2- and 3-dimensional cases. The rub to this is that > in the n-dimensional case, it probably makes most sense to store the > actual coordinates as a list whereas with the 2- and 3-D cases, I > would want 'named' variables, such as x, y, z. It would surprise me greatly if numpy didn't already have such a class. Other than using numpy, probably the simplest solution is to just subclass tuple and give it named properties and whatever other methods you want. Here's a simple version: class Point(tuple): def __new__(cls, *args): if len(args) == 1 and isinstance(args, tuple): args = args[0] for a in args: try: a+0 except TypeError: raise TypeError('ordinate %s is not a number' % a) return super(Point, cls).__new__(cls, args) @property def x(self): return self[0] @property def y(self): return self[1] @property def z(self): return self[2] def dist(self, other): if isinstance(other, Point): if len(self) == len(other): sq_diffs = sum((a-b)**2 for (a,b) in zip(self, other)) return math.sqrt(sq_diffs) else: raise ValueError('incompatible dimensions') raise TypeError('not a Point') def __repr__(self): return "%s(%r)" % (self.__class__.__name__, tuple(self)) class Point2D(Point): def __init__(self, *args): if len(self) != 2: raise ValueError('need exactly two ordinates') class Point3D(Point): def __init__(self, *args): if len(self) != 3: raise ValueError('need exactly three ordinates') These classes gives you: * immutability; * the first three ordinates are named x, y and z; * any ordinate can be accessed by index with pt[3]; * distance is only defined if the dimensions are the same; * nice string form; * input validation. What it doesn't give you (yet!) is: * distance between Points with different dimensions could easily be defined just by removing the len() comparison. zip() will automatically terminate at the shortest input, thus projecting the higher-dimension point down to the lower-dimension point; * other distance methods, such as Manhattan distance; * a nice exception when you as for (say) pt.z from a 2-D point, instead of raising IndexError; * point arithmetic (say, adding two points to get a third). But you can't expect me to do all your work :) An alternative would be to have the named ordinates return 0 rather than raise an error. Something like this would work: @property def y(self): try: return self[1] except IndexError: return 0 -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
"Gregory, Matthew" wrote I typically deal with geographic (either 2D or 3D) data, yet there are occasions when I need n-dimensional points as well. Thats OK. The rub to this is that in the n-dimensional case, it probably makes most sense to store the actual coordinates as a list whereas with the 2- and 3-D cases, I would want 'named' variables, such as x, y, z. Thats OK too but adds some overhead. Remember that inheritance should be based on behaviour not data so determine the common methods of a Point. Write the ND version of those methods. Then create subclasses for 2D and 3D which convert the named args to a list equivalent then call the superclass ND versions. Every time you change the interface of inherited methods you create for yourself extra work in converting types to match the superclass. But that is often easier than rewriting the methods from scratch. Just remember that to get the best out of polymorphism - the primary reason for inheritance - you should be able to mix n match instances of the subclasses with instances of the superclass - the Liskov Substitution Principle(LSP) - and if you break that you lose for yourself much of the power of inheritance. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ Here's a (very rough) first cut at the constructor and a generic distance function for the n-dimensional case: class PointND(object): def __init__(self, a_list): self.a_list = a_list[:] def distance(self, right): assert(len(self.coord) == len(right)) squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] return math.sqrt(sum(squared_diffs)) But how can I subclass this in such a way to be able to: 1) Have named variables in the 2- and 3-D cases 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, 5.0)' rather than passing in a list Or am I totally off on thinking this is a good place for inheritance? Thanks for any help, matt ___ 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] design of Point class
On 8/20/2010 1:55 PM, Gregory, Matthew wrote: Wayne Werner wrote: class Point2D(PointND): def __init__(self, x = 0, y = 0): super(Point2D, self).__init__([x,y]) self.x = 0 self.y = 0 though you wouldn't be able to directly modify the values, or you'll lose the distance function. You'd have to create setter functions, and as such should rename x and y to _x and _y, to indicate that sure you *can* touch these, but really you shouldn't. For the 3d, you'd just add a z param, although to really generalize your ND class you could do this instead: class PointND(object): def __init__(self, x=0, y=0, z=0, a_list=None): if a_list is not None: self.a_list = a_list[:] self.x = x self.y = y self.z = z def coords(self): return [self.x, self.y, self.z] + self.a_list ... Then your subclass takes less effort: class Point2D(PointND): def __init__(self, x=0, y=0): super(Point2D, self).__init__(x,y) and this allows you to access point.x, point.y, and point.z directly. Of course you could also subclass list with ND and just use descriptors for self[0], self[1], and self[2]: http://users.rcn.com/python/download/Descriptor.htm Thanks all for good suggestions. I'm intrigued by the idea of subclassing list (suggested by both Bob and Wayne) and using x, y and z as descriptors to the elements in the list. Obviously, it's important that the descriptors (x,y,z) stay in sync with the list itself so that: >>> p = PointND(1,2,3) >>> p.x = 10 >>> p [10,2,3] > From what I understood of the link Wayne sent, I should be able to use __set__ to create this relationship between the labels and the list, but I'm totally lost on how to do this. It seems like x,y,z need to be instances of descriptor objects who have values that are associated with the list. In the mean time, I've overridden __setattr__ to enforce this, but it looks a bit crufty. Any further suggestions are most welcome. class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) if len(self)<= 3: self.x = self[0] if len(self)>= 2 and len(self)<= 3: self.y = self[1] if len(self) == 3: self.z = self[2] def __setattr__(self, attr, value): if attr in ('x', 'y', 'z'): self.__dict__[attr] = value if attr == 'x': self[0] = value elif attr == 'y': self[1] = value else: self[2] = value After more thought it gets even better: class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) def get(ix): def g(self): if len(self) >= ix + 1: return self[ix] else: raise AttributeError return g def set(ix): def s(self, value): if len(self) >= ix + 1: self[ix] = value else: raise AttributeError return s x = property(get(0), set(0)) y = property(get(1), set(1)) z = property(get(2), set(2)) -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
On 8/20/2010 1:55 PM, Gregory, Matthew wrote: Wayne Werner wrote: class Point2D(PointND): def __init__(self, x = 0, y = 0): super(Point2D, self).__init__([x,y]) self.x = 0 self.y = 0 though you wouldn't be able to directly modify the values, or you'll lose the distance function. You'd have to create setter functions, and as such should rename x and y to _x and _y, to indicate that sure you *can* touch these, but really you shouldn't. For the 3d, you'd just add a z param, although to really generalize your ND class you could do this instead: class PointND(object): def __init__(self, x=0, y=0, z=0, a_list=None): if a_list is not None: self.a_list = a_list[:] self.x = x self.y = y self.z = z def coords(self): return [self.x, self.y, self.z] + self.a_list ... Then your subclass takes less effort: class Point2D(PointND): def __init__(self, x=0, y=0): super(Point2D, self).__init__(x,y) and this allows you to access point.x, point.y, and point.z directly. Of course you could also subclass list with ND and just use descriptors for self[0], self[1], and self[2]: http://users.rcn.com/python/download/Descriptor.htm Thanks all for good suggestions. I'm intrigued by the idea of subclassing list (suggested by both Bob and Wayne) and using x, y and z as descriptors to the elements in the list. Obviously, it's important that the descriptors (x,y,z) stay in sync with the list itself so that: >>> p = PointND(1,2,3) >>> p.x = 10 >>> p [10,2,3] > From what I understood of the link Wayne sent, I should be able to use __set__ to create this relationship between the labels and the list, but I'm totally lost on how to do this. It seems like x,y,z need to be instances of descriptor objects who have values that are associated with the list. In the mean time, I've overridden __setattr__ to enforce this, but it looks a bit crufty. Any further suggestions are most welcome. class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) if len(self)<= 3: self.x = self[0] if len(self)>= 2 and len(self)<= 3: self.y = self[1] if len(self) == 3: self.z = self[2] def __setattr__(self, attr, value): if attr in ('x', 'y', 'z'): self.__dict__[attr] = value if attr == 'x': self[0] = value elif attr == 'y': self[1] = value else: self[2] = value class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) def get(self, ix): if len(self)>= ix + 1: return self[ix] else: raise AttributeError def set(self, ix, value): if len(self)>= ix + 1: self[ix] = value else: raise AttributeError def getx(self): return self.get(0) def setx(self, value): self.set(0, value) x = property(getx, setx) def gety(self): return self.get(1) def sety(self, value): self.set(1, value) y = property(gety, sety) # repeat for z -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Overloaded Brackets
Hi All, I just had reason the write the following: itemCodes = [UPCxref['0'+xx[:10]][0] for xx in itemUPCs] ... and it occurred to me exactly how overloaded square brackets are. This is certainly not something you want to see as a beginning python programmer, but I thought it might be an interesting example to parse. Regards, Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flow problem with a exercise
Please use ReplyAll when responding to posts from the tutor list. > I don''t understand it complety. > return not arg%2 >> >> Why use not here ? >> >> I think that arg%2 is True not makes it false. > >For an even number arg % 2 will be 0 which Python considers to be False. So for a True result when arg%2 is zero, you must negate the logic Another question. > >How can I round outcome of a calculation. > >round ( ( t-32)/1.8) does not work because I get a message that there are two >arguments. > >Check your code because thre is only one arg here. Therefore the actual code giving the error must be different in some way. Outcome = (t-32)/1.8 >outcome2 = round (outcome) does not work because the argument must be a string >or a number > > > Assuming t is a number the outcome will be a number so it should work. It helps if you cut n paste the real code and the real error message, do not just summarise. Python error messages are extremely helpful, but only if we can see them. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
On Fri, Aug 20, 2010 at 12:55 PM, Gregory, Matthew wrote: > Wayne Werner wrote: >> class Point2D(PointND): >> def __init__(self, x = 0, y = 0): >> super(Point2D, self).__init__([x,y]) >> self.x = 0 >> self.y = 0 >> >> though you wouldn't be able to directly modify the values, or you'll >> lose the distance function. You'd have to create setter functions, and as >> such should rename x and y to _x and _y, to indicate that sure you *can* >> touch >> these, but really you shouldn't. >> >> For the 3d, you'd just add a z param, although to really generalize your >> ND class you could do this instead: >> >> class PointND(object): >> def __init__(self, x=0, y=0, z=0, a_list=None): >> if a_list is not None: >> self.a_list = a_list[:] >> self.x = x >> self.y = y >> self.z = z >> >> def coords(self): >> return [self.x, self.y, self.z] + self.a_list >> ... >> >> Then your subclass takes less effort: >> >> class Point2D(PointND): >> def __init__(self, x=0, y=0): >> super(Point2D, self).__init__(x,y) >> >> and this allows you to access point.x, point.y, and point.z directly. >> >> Of course you could also subclass list with ND and just use descriptors >> for self[0], self[1], and self[2]: >> http://users.rcn.com/python/download/Descriptor.htm > > Thanks all for good suggestions. I'm intrigued by the idea of subclassing > list (suggested by both Bob and Wayne) and using x, y and z as descriptors to > the elements in the list. Obviously, it's important that the descriptors > (x,y,z) stay in sync with the list itself so that: > > >>> p = PointND(1,2,3) > >>> p.x = 10 > >>> p > [10,2,3] > > >From what I understood of the link Wayne sent, I should be able to use > >__set__ to create this relationship between the labels and the list, but I'm > >totally lost on how to do this. It seems like x,y,z need to be instances of > >descriptor objects who have values that are associated with the list. > > In the mean time, I've overridden __setattr__ to enforce this, but it looks a > bit crufty. Any further suggestions are most welcome. > > class PointND(list): > def __init__(self, *a_list): > super(PointND, self).__init__(a_list) > if len(self) <= 3: > self.x = self[0] > if len(self) >= 2 and len(self) <= 3: > self.y = self[1] > if len(self) == 3: > self.z = self[2] > > def __setattr__(self, attr, value): > if attr in ('x', 'y', 'z'): > self.__dict__[attr] = value > if attr == 'x': > self[0] = value > elif attr == 'y': > self[1] = value > else: > self[2] = value perhaps properties could be of some use? from operator import itemgetter, setitem def named_index(index): getter = itemgetter(index) setter = lambda self, val: setitem(self, index, val) return property(getter, setter) class NPoint(list): x = named_index(0) y = named_index(1) z = named_index(2) p = NPoint([3, 4, 50]) print p.x, p.y, p.z p.x = p.y + 13 print p Note that trying to access z when there are not enough items in the list will raise an IndexError, not an AttributeError. You might want to adjust the getter/setter functions a little. Alternatively, I'm not sure if you can add properties in __init__ or __new__, but if not that, you can probably write a metaclass that adds in the right properties based on list length. Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multiple file open
Hello Nitin, On 20/08/10 16:21, nitin chandra wrote: import sys,os, fileinput [...] while True: try: line1 = fp1.readline().split(",") line2 = fp2.readline().split(",") [...] fp3.write(str3) You're missing the completion for the try/finally block. Try adding an exception handler or comment out the "try" statement for the time being. Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flow problem with a exercise
On Fri, Aug 20, 2010 at 2:48 PM, Roelof Wobben wrote: > Oke, > > I don''t understand it complety. > > return not arg%2 > > Why use not here ? > > I think that arg%2 is True not makes it false. > What happens when you replace arg with a value? % is modulo division, so it just returns the remainder. 2 % 2 = ? 4 % 2 = ? 7 % 2 = ? 11 % 2 = ? What is the truth value of 0 and 1? print 'True' if 0 else 'False' print 'True' if 1 else 'False' So what is the outcome of the following? result = 2 % 2 print result, not result if not result: print 'Even' if result: print 'odd' > > Another question. > > How can I round outcome of a calculation. > > round ( ( t-32)/1.8) does not work because I get a message that there are > two arguments. > > Outcome = (t-32)/1.8 > outcome2 = round (outcome) does not work because the argument must be a > string or a number > What is the type of t? In [39]: t = 3 In [40]: round((t-32)/1.8) Out[40]: -16.0 In [41]: t = 3.0 In [42]: round((t-32)/1.8) Out[42]: -16.0 Works fine for me. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flow problem with a exercise
Oke, I don''t understand it complety. return not arg%2 Why use not here ? I think that arg%2 is True not makes it false. Another question. How can I round outcome of a calculation. round ( ( t-32)/1.8) does not work because I get a message that there are two arguments. Outcome = (t-32)/1.8 outcome2 = round (outcome) does not work because the argument must be a string or a number Roelof ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
Wayne Werner wrote: > class Point2D(PointND): > def __init__(self, x = 0, y = 0): > super(Point2D, self).__init__([x,y]) > self.x = 0 > self.y = 0 > > though you wouldn't be able to directly modify the values, or you'll > lose the distance function. You'd have to create setter functions, and as > such should rename x and y to _x and _y, to indicate that sure you *can* > touch > these, but really you shouldn't. > > For the 3d, you'd just add a z param, although to really generalize your > ND class you could do this instead: > > class PointND(object): > def __init__(self, x=0, y=0, z=0, a_list=None): > if a_list is not None: > self.a_list = a_list[:] > self.x = x > self.y = y > self.z = z > > def coords(self): > return [self.x, self.y, self.z] + self.a_list > ... > > Then your subclass takes less effort: > > class Point2D(PointND): > def __init__(self, x=0, y=0): > super(Point2D, self).__init__(x,y) > > and this allows you to access point.x, point.y, and point.z directly. > > Of course you could also subclass list with ND and just use descriptors > for self[0], self[1], and self[2]: > http://users.rcn.com/python/download/Descriptor.htm Thanks all for good suggestions. I'm intrigued by the idea of subclassing list (suggested by both Bob and Wayne) and using x, y and z as descriptors to the elements in the list. Obviously, it's important that the descriptors (x,y,z) stay in sync with the list itself so that: >>> p = PointND(1,2,3) >>> p.x = 10 >>> p [10,2,3] >From what I understood of the link Wayne sent, I should be able to use __set__ >to create this relationship between the labels and the list, but I'm totally >lost on how to do this. It seems like x,y,z need to be instances of >descriptor objects who have values that are associated with the list. In the mean time, I've overridden __setattr__ to enforce this, but it looks a bit crufty. Any further suggestions are most welcome. class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) if len(self) <= 3: self.x = self[0] if len(self) >= 2 and len(self) <= 3: self.y = self[1] if len(self) == 3: self.z = self[2] def __setattr__(self, attr, value): if attr in ('x', 'y', 'z'): self.__dict__[attr] = value if attr == 'x': self[0] = value elif attr == 'y': self[1] = value else: self[2] = value ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehension for dicts?
result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] is a good approach but it is taking little more time than the for loop over iterator. def takewhile(predicate, iterable): # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4 for x in iterable: if predicate(x): yield x else: break I don't know why? As it seems that this for loop and the other for loop doing the same thing. --nitin On Fri, Aug 20, 2010 at 9:17 PM, bob gailer wrote: > On 8/20/2010 5:44 AM, Steven D'Aprano wrote: > >> On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote: >> >>> "Steven D'Aprano" wrote >>> >>> the purpose). No matter how fast you can perform a loop, it's always faster to avoid it altogether, so this: seq = xrange(1000) result = [] for i in seq: if i>= 10: break result.append(i%2) will be much faster than this: seq = xrange(1000) result = [i%2 for i in seq if i< 10] >>> Although it should be pointed out that these are doing very different >>> things. >>> >> Well yes, but I pointed out that you *can* bail out early of for-loops, >> but not list comprehensions. The whole point is with a list comp, >> you're forced to iterate over the entire sequence, even if you know >> that you're done and would like to exit. >> >> Take a look at itertools.takewhile! > > result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] > > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > ___ > 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] design of Point class
On Fri, Aug 20, 2010 at 10:45 AM, Gregory, Matthew < matt.greg...@oregonstate.edu> wrote: > Hi all, > > I often struggle with object design and inheritance. I'd like opinions on > how best to design a Point class to be used in multiple circumstances. > > I typically deal with geographic (either 2D or 3D) data, yet there are > occasions when I need n-dimensional points as well. My thought was to > create a superclass which was an n-dimensional point and then subclass that > to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional > case, it probably makes most sense to store the actual coordinates as a list > whereas with the 2- and 3-D cases, I would want 'named' variables, such as > x, y, z. > > Here's a (very rough) first cut at the constructor and a generic distance > function for the n-dimensional case: > > class PointND(object): >def __init__(self, a_list): >self.a_list = a_list[:] > >def distance(self, right): >assert(len(self.coord) == len(right)) >squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] >return math.sqrt(sum(squared_diffs)) > > But how can I subclass this in such a way to be able to: > > 1) Have named variables in the 2- and 3-D cases > 2) Be able to initialize with separate passed values, e.g. 'p = > Point2D(3.0, 5.0)' > rather than passing in a list > class Point2D(PointND): def __init__(self, x = 0, y = 0): super(Point2D, self).__init__([x,y]) self.x = 0 self.y = 0 though you wouldn't be able to directly modify the values, or you'll lose the distance function. You'd have to create setter functions, and as such should rename x and y to _x and _y, to indicate that sure you *can* touch these, but really you shouldn't. For the 3d, you'd just add a z param, although to really generalize your ND class you could do this instead: class PointND(object): def __init__(self, x=0, y=0, z=0, a_list=None): if a_list is not None: self.a_list = a_list[:] self.x = x self.y = y self.z = z def coords(self): return [self.x, self.y, self.z] + self.a_list ... Then your subclass takes less effort: class Point2D(PointND): def __init__(self, x=0, y=0): super(Point2D, self).__init__(x,y) and this allows you to access point.x, point.y, and point.z directly. Of course you could also subclass list with ND and just use descriptors for self[0], self[1], and self[2]: http://users.rcn.com/python/download/Descriptor.htm HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
On 8/20/2010 11:45 AM, Gregory, Matthew wrote: Hi all, I often struggle with object design and inheritance. I'd like opinions on how best to design a Point class to be used in multiple circumstances. I typically deal with geographic (either 2D or 3D) data, yet there are occasions when I need n-dimensional points as well. My thought was to create a superclass which was an n-dimensional point and then subclass that to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional case, it probably makes most sense to store the actual coordinates as a list whereas with the 2- and 3-D cases, I would want 'named' variables, such as x, y, z. Here's a (very rough) first cut at the constructor and a generic distance function for the n-dimensional case: class PointND(object): def __init__(self, a_list): self.a_list = a_list[:] def distance(self, right): assert(len(self.coord) == len(right)) squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] return math.sqrt(sum(squared_diffs)) But how can I subclass this in such a way to be able to: 1) Have named variables in the 2- and 3-D cases 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, 5.0)' rather than passing in a list One class fits all: class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) if len(self)<= 2: self.x = self[0] if len(self) == 2: self.y = self[1] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] design of Point class
On 8/20/10, Gregory, Matthew wrote: > Hi all, > > I often struggle with object design and inheritance. I'd like opinions on > how best to design a Point class to be used in multiple circumstances. > > I typically deal with geographic (either 2D or 3D) data, yet there are > occasions when I need n-dimensional points as well. My thought was to > create a superclass which was an n-dimensional point and then subclass that > to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional > case, it probably makes most sense to store the actual coordinates as a list > whereas with the 2- and 3-D cases, I would want 'named' variables, such as > x, y, z. > > Here's a (very rough) first cut at the constructor and a generic distance > function for the n-dimensional case: > > class PointND(object): > def __init__(self, a_list): > self.a_list = a_list[:] > > def distance(self, right): > assert(len(self.coord) == len(right)) > squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] > return math.sqrt(sum(squared_diffs)) > > But how can I subclass this in such a way to be able to: > > 1) Have named variables in the 2- and 3-D cases I assume you will have separate subclasses for both 2d and 3d, so just set up each subclass's __init__ to accept the proper amount and order of arguments. > 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, > 5.0)' >rather than passing in a list class 2dPoint(point): def __init__(self, x, y): self.x=x self.y=y self.points=[x,y] > > Or am I totally off on thinking this is a good place for inheritance? I would use subclassing. Designed right, this gives you access to common functions like distance but also lets you customize each subclass with specific methods unique to that subclass. Just my 2 cents, though, and I am not too experienced here. > > Thanks for any help, > matt > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehension for dicts?
On 8/20/2010 5:44 AM, Steven D'Aprano wrote: On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote: "Steven D'Aprano" wrote the purpose). No matter how fast you can perform a loop, it's always faster to avoid it altogether, so this: seq = xrange(1000) result = [] for i in seq: if i>= 10: break result.append(i%2) will be much faster than this: seq = xrange(1000) result = [i%2 for i in seq if i< 10] Although it should be pointed out that these are doing very different things. Well yes, but I pointed out that you *can* bail out early of for-loops, but not list comprehensions. The whole point is with a list comp, you're forced to iterate over the entire sequence, even if you know that you're done and would like to exit. Take a look at itertools.takewhile! result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] design of Point class
Hi all, I often struggle with object design and inheritance. I'd like opinions on how best to design a Point class to be used in multiple circumstances. I typically deal with geographic (either 2D or 3D) data, yet there are occasions when I need n-dimensional points as well. My thought was to create a superclass which was an n-dimensional point and then subclass that to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional case, it probably makes most sense to store the actual coordinates as a list whereas with the 2- and 3-D cases, I would want 'named' variables, such as x, y, z. Here's a (very rough) first cut at the constructor and a generic distance function for the n-dimensional case: class PointND(object): def __init__(self, a_list): self.a_list = a_list[:] def distance(self, right): assert(len(self.coord) == len(right)) squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] return math.sqrt(sum(squared_diffs)) But how can I subclass this in such a way to be able to: 1) Have named variables in the 2- and 3-D cases 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, 5.0)' rather than passing in a list Or am I totally off on thinking this is a good place for inheritance? Thanks for any help, matt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multiple file open
import sys,os, fileinput FileA = raw_input('Enter CSV file with lists of Files:') try: fp6 = open(FileA,'r') except IOError: sys.exit('Could not open file: %s' % FileA) while True: lines = fp6.readline().split(",") file11 = lines[0] file12 = lines[1] file3 = lines[2] #file11 = raw_input('Enter PR1 File name :') #fp1 = open(file11,'r') try: fp1 = open(file11, 'r') except IOError: sys.exit('Could not open file: %s' % file11) #file12 = raw_input('Enter PR3 File Name :') #fp2 = open(file12,'r') try: fp2 = open(file12, 'r') except IOError: sys.exit('Could not open file: %s' % file12) #file3 = raw_input('Enter PR2 OUTPUT File Name :') try: fp3 = open(file3, 'w') except IOError: sys.exit('Could not open file %s to Write' % file3) while True: try: line1 = fp1.readline().split(",") line2 = fp2.readline().split(",") #line1 = line1A.split(",") col1 = line1[0] col2 = line1[1] col3 = line1[2] col4 = line1[3] col5 = line1[20] col6 = line1[21] col7 = line1[22] #line2 = line1B.split(",") col8 = line2[1] col9 = line2[2] col10 = line2[3] col11 = line2[20] col12 = line2[21] col13 = line2[22] #def __FormulaPR2(): #claculation of PR2 as per formula #(A+B)/2 , ie. Mean of the two values col14 = (((float(col2)) + (float(col8))) / 2) col15 = (((float(col3)) + (float(col9))) / 2) col16 = (((float(col4)) + (float(col10))) / 2) col17 = (((float(col5)) + (float(col11))) / 2) col18 = (((float(col6)) + (float(col12))) / 2) col19 = (((float(col7)) + (float(col13))) / 2) print col1,col14,col15,col16,col17,col18,col19 str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col14,col15,col16,col17,col18,col19) fp3.write(str3) On Fri, Aug 20, 2010 at 4:48 PM, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 06:27:01 pm nitin chandra wrote: >> Thank you, Alan and Steven. >> >> Now i am facing some thing 'different' >> >> This is even when i have not done a carriage return to create line >> "66". This is after i have done >> fp1.close() >> fp2.close() >> fp3.close() >> ** >> >> File "mer5Pr2.py", line 66 >> >> ^ >> IndentationError: unexpected unindent > > > Without seeing the actual code, it's hard to say. But you need to learn > to read the error message: it says you have unexpectedly unindented > (outdented). My guess is you've done something like this: > > if something: > line indented with 4 spaces > line indented with 2 spaces > > > You need to indent consistently. Set your editor to always use 4 spaces > for indents. If you can't do that, then get a better editor, or use a > single tab instead of four spaces. > > Some people will say don't use tabs. I say phooey to them. It's better > to use tabs than to have inconsistent indentation. > > > > -- > Steven D'Aprano > ___ > Tutor maillist - tu...@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] Multiple file open
On Fri, 20 Aug 2010 06:27:01 pm nitin chandra wrote: > Thank you, Alan and Steven. > > Now i am facing some thing 'different' > > This is even when i have not done a carriage return to create line > "66". This is after i have done > fp1.close() > fp2.close() > fp3.close() > ** > > File "mer5Pr2.py", line 66 > > ^ > IndentationError: unexpected unindent Without seeing the actual code, it's hard to say. But you need to learn to read the error message: it says you have unexpectedly unindented (outdented). My guess is you've done something like this: if something: line indented with 4 spaces line indented with 2 spaces You need to indent consistently. Set your editor to always use 4 spaces for indents. If you can't do that, then get a better editor, or use a single tab instead of four spaces. Some people will say don't use tabs. I say phooey to them. It's better to use tabs than to have inconsistent indentation. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehension for dicts?
On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote: > "Steven D'Aprano" wrote > > > the purpose). No matter how fast you can perform a loop, it's > > always faster to avoid it altogether, so this: > > > > seq = xrange(1000) > > result = [] > > for i in seq: > >if i >= 10: break > >result.append(i%2) > > > > > > will be much faster than this: > > > > seq = xrange(1000) > > result = [i%2 for i in seq if i < 10] > > Although it should be pointed out that these are doing very different > things. Well yes, but I pointed out that you *can* bail out early of for-loops, but not list comprehensions. The whole point is with a list comp, you're forced to iterate over the entire sequence, even if you know that you're done and would like to exit. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Done -- Elementtree and pretty printing in Python 2.7
Hi guys, just found "hidden" in the "Schema change in Etree"-Thread the answer to my formatting question: Quotation: " ElementTree doesn't have a way of formatting (pretty printing) XML files, so there can't be that many newline characters in the structure (they may be in the occur, though!). There's a pretty printing recipe on the effbot site that you can easily adapt to inject the newline characters you need. " The recipe works fine. Cheers, Jan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multiple file open
Thank you, Alan and Steven. Now i am facing some thing 'different' This is even when i have not done a carriage return to create line "66". This is after i have done fp1.close() fp2.close() fp3.close() ** File "mer5Pr2.py", line 66 ^ IndentationError: unexpected unindent Thank you Nitin On Fri, Aug 20, 2010 at 1:28 PM, Alan Gauld wrote: > > "nitin chandra" wrote >> >> FileA = raw_input('Enter CSV file with lists of Files:') >> try: >> fp6 = open(FileA,'r') >> except IOError: >> >> ## I am getting the following error at this line:- >> ## >> ## File "mer5Pr2.py", line 7 >> ## except IOError: >> ## ^ >> ## SyntaxError: invalid syntax > > > The except needs to align with the try. > > > try: > #code here > except: > > HTH > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ___ > Tutor maillist - tu...@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] flow problem with a exercise
"Roelof Wobben" wrote Others have pointed out the lack of indentation. I'll point out some shortcuts you can use... def is_even(argument): remainder= argument%2 if remainder == 0 : return True else : return False You can abbreviate this to just def is_even(arg): return not arg%2 def is_odd(argument): uitkomst=is_even(argument) return uitkomst and this to: def is_odd(arg): return not is_even(arg) 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] List comprehension for dicts?
"Steven D'Aprano" wrote the purpose). No matter how fast you can perform a loop, it's always faster to avoid it altogether, so this: seq = xrange(1000) result = [] for i in seq: if i >= 10: break result.append(i%2) will be much faster than this: seq = xrange(1000) result = [i%2 for i in seq if i < 10] Although it should be pointed out that these are doing very different things. The equivalent loop would use continue rather than break, in which case the LC might be faster. But where you do only want to partially process a list the explicit loop is the best solution for now. I've always wanted an until clause in the LC structure: result = [i%2 for i in seq until i>10] -- 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] Multiple file open
"nitin chandra" wrote FileA = raw_input('Enter CSV file with lists of Files:') try: fp6 = open(FileA,'r') except IOError: ## I am getting the following error at this line:- ## ##File "mer5Pr2.py", line 7 ##except IOError: ##^ ##SyntaxError: invalid syntax The except needs to align with the try. try: #code here except: 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] Multiple file open
On Fri, 20 Aug 2010 05:28:42 pm nitin chandra wrote: > try: >fp6 = open(FileA,'r') >except IOError: You need to outdent the except line: try: fp6 = open(FileA,'r') except IOError: sys.exit('Could not open file: %s' % FileA) -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Elementtree and pretty printing in Python 2.7
Hi guys, I'm using Python 2.7 and the ElementTree standard-lib to write some xml. My output xml has no line breaks! So, it looks like that: instead of something like this: I'm aware of lxml which seems to have a pretty print option, but I would prefer to use the standard-lib ElementTree which seems not to have a feature like this. Do I miss something using the ElementTree-lib or is it bug? Cheers, Jan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multiple file open
Hello All, I am getting the "Invalid Syntax" error. I am on Python 2.6. Thanks In Advance Nitin import sys,os, fileinput FileA = raw_input('Enter CSV file with lists of Files:') try: fp6 = open(FileA,'r') except IOError: ## I am getting the following error at this line:- ## ##File "mer5Pr2.py", line 7 ##except IOError: ##^ ##SyntaxError: invalid syntax sys.exit('Could not open file: %s' % FileA) while True: lines = fp6.readline().split(",") file11 = lines[0] file12 = lines[1] file3 = lines[2] #file11 = raw_input('Enter PR1 File name :') #fp1 = open(file11,'r') try: fp1 = open(file11, 'r') except IOError: sys.exit('Could not open file: %s' % file11) #file12 = raw_input('Enter PR3 File Name :') #fp2 = open(file12,'r') try: fp2 = open(file12, 'r') except IOError: sys.exit('Could not open file: %s' % file12) #file3 = raw_input('Enter PR2 OUTPUT File Name :') try: fp3 = open(file3,'w') except IOError: sys.exit('Could not open file %s to Write' % file3) while True: try: line1 = fp1.readline().split(",") line2 = fp2.readline().split(",") #line1 = line1A.split(",") col1 = line1[0] col2 = line1[1] col3 = line1[2] col4 = line1[3] col5 = line1[20] col6 = line1[21] col7 = line1[22] #line2 = line1B.split(",") col8 = line2[1] col9 = line2[2] col10 = line2[3] col11 = line2[20] col12 = line2[21] col13 = line2[22] #def __FormulaPR2(): #claculation of PR2 as per formula #(A+B)/2 , ie. Mean of the two values col14 = (((float(col2)) + (float(col8))) / 2) col15 = (((float(col3)) + (float(col9))) / 2) col16 = (((float(col4)) + (float(col10))) / 2) col17 = (((float(col5)) + (float(col11))) / 2) col18 = (((float(col6)) + (float(col12))) / 2) col19 = (((float(col7)) + (float(col13))) / 2) print col1,col14,col15,col16,col17,col18,col19 str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col14,col15,col16,col17,col18,col19) fp3.write(str3) #def __FormulaPR4(): #calculation of PR4 as per formula #(B-C)+3 , ie. Extrapolation of the values fp1.close() fp2.close() fp3.close() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor