Re: [Tutor] clearing a text document
max baseman wrote: > right it's for a quick math "game" the rules are simple you start > with any number to get the next number you, a. if it's odd multiply > by 3 than add 1 or b. if it's even divide by two, the point of this > is to see how long it takes to get to one are it starts to repeat > 4,2,1,4,2,1... > now im looking for a a number with a very high amount of numbers > till you get to 1 so every time it's finds a new one i would like it > to write that to a file and clear the last entry, If your goal is to find long sequences why not write your program to try every number up to some limit and find the longest? It's a nice use of generators, for those who know what they are... These sequences are known as hailstone numbers. The (unproven) conjecture that the sequence will always terminate is called Collatz' Conjecture. Some interesting info and pictures here: http://sprott.physics.wisc.edu/pickover/hailstone.html http://mathworld.wolfram.com/CollatzProblem.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clearing a text document
cool thank you :) On Aug 29, 2007, at 11:02 PM, Luke Paireepinart wrote: > max baseman wrote: >> right it's for a quick math "game" the rules are simple you start >> with any number to get the next number you, a. if it's odd >> multiply by 3 than add 1 or b. if it's even divide by two, the >> point of this is to see how long it takes to get to one are it >> starts to repeat 4,2,1,4,2,1... >> now im looking for a a number with a very high amount of numbers >> till you get to 1 so every time it's finds a new one i would like >> it to write that to a file and clear the last entry, > Just open the file for writing and it will erase all previous > contents and create the file if it doesn't already exist. > -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] clearing a text document
thats what it does but in order to just be able to let it sit and work for as long as it can i made it a endless loop of just trying every number, for now it just displays the highest on the screen but it would be nice to get it in a text document thanks On Aug 30, 2007, at 4:53 AM, Kent Johnson wrote: > max baseman wrote: >> right it's for a quick math "game" the rules are simple you start >> with any number to get the next number you, a. if it's odd >> multiply by 3 than add 1 or b. if it's even divide by two, the >> point of this is to see how long it takes to get to one are it >> starts to repeat 4,2,1,4,2,1... >> now im looking for a a number with a very high amount of numbers >> till you get to 1 so every time it's finds a new one i would like >> it to write that to a file and clear the last entry, > > If your goal is to find long sequences why not write your program > to try every number up to some limit and find the longest? > > It's a nice use of generators, for those who know what they are... > > These sequences are known as hailstone numbers. The (unproven) > conjecture that the sequence will always terminate is called > Collatz' Conjecture. Some interesting info and pictures here: > http://sprott.physics.wisc.edu/pickover/hailstone.html > http://mathworld.wolfram.com/CollatzProblem.html > > Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Triangle structure for triangulation
Dear All, I have written a Delaunay triangulation 10 years ago in C based on triangle structure. It was 400 lines, so it seems to be a fine task to turn into python. My problem is the translation of the C structure and the OO thinking. I tried to draft it so. /* The triangle, its neighbours, sides and rotations. 0 VTOP /\ / t r \ LEFT/ oo \RIGHT 1 / r t \ / act\ 1 VLEFTVRIGHT 2 BOTTOM 0 */ typedef struct{ TRIINDEXneighbour[3]; // triangles: bottom, right, left POINTINDEX vertex[3]; // vertex: top, left, right float height;// elevation } TRIANGLE; Each triangle has three vertices and three neighbours. To calculate the elvation on the triangulation at a given point, it is important to find the coresponding triangle as fast as possible, so the triangles had directions. But it was important in the update process too. So I had an array with the triangles, but the neighbours were directed triangles not simple triangle (TRIINDEX). There were C macros to get the neighbours of the triangles. To get the left triangle tleft = LEFT(t), tright = RIGHT(t), tbottom = BOTTOM(t) ROT(t) was the same triangle as t, but rotated ccw. so t = ROT(ROT(ROT(t))) TOR(t) was the same triangle as t, but rotated cw. t = TOR(TOR(TOR(t))) In C, I have used typedef unsigned intTRIINDEX; to identify a triangle, where the last two bites were used to handle the directions. ## I can translate it into python in this way class Triangle: def __init__(self, points, neighbours): self.points = points self.neighbours = neighbours def TOR(self, direction): return (self, (direction+1)%3) def ROT(self, direction): return (self, (direction+2)%3) def RIGHT(self, direction): return (self.neighbours[(direction+2)%3]) I would ask your opinions to encapsulate a triangle into a directed triangle. I made my first trial on the way to keep a directed triangle as a tuple (triangle, direction) and register it in that way. I would like to use directed triangles, but wouldn't like to use too much memory. Yours sincerely, Janos Juhasz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Triangle structure for triangulation
"János Juhász" <[EMAIL PROTECTED]> wrote > ## I can translate it into python in this way > class Triangle: >def __init__(self, points, neighbours): >self.points = points >self.neighbours = neighbours > > def TOR(self, direction): >return (self, (direction+1)%3) > > def ROT(self, direction): >return (self, (direction+2)%3) > > def RIGHT(self, direction): >return (self.neighbours[(direction+2)%3]) > > I would ask your opinions to encapsulate a triangle into a directed > triangle. I'm not totally sure what you are looking for but my first guess would be to add a direction argument to the init and store it as an attribute. But it sounds like you need to add some methods too. What do you do with these triangles? From your descriptionI'd expect to see some methods taking other triangles as arguments? For example you store the points but never use them. Attributes in a class shjould be thee to support the metjods. If the atrributes are not used by any method that implies that they are not needed or that you are accessing them from some function outside the class, which is probably an indication of bad OO design. > I made my first trial on the way to keep a directed triangle as a > tuple > (triangle, direction) and register it in that way. > I would like to use directed triangles, but wouldn't like to use too > much > memory. How much memory would be too much? If you don't know, then go with the best design and optimise the memory only when you know that there is a need. Prematurely optimising memory is just as bad as prematurely optimising speed. It usually leads to bad code when there is no need. -- 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] A replacement for a "for" loop
Terry Carroll wrote: > On Wed, 29 Aug 2007, Scott Oertel wrote: > > >> Why even have the keys variable at all.. >> >> for key in attrs: >> print 'Attribute %s has value %s' % (key, attrs[key]) >> > > In a prior email thread, the OP indicated that he needed to process the > keys in that particular order; and it's not really amenable to any sort. > > Yup, I didn't see that the first time, sorry. -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Formatting output into columns
Someone asked me this question the other day, and I couldn't think of any easy way of printing the output besides what I came up with pasted below. So what you have is a file with words in it as such: apple john bean joke ample python nice and you want to sort and output the text into columns as such: a p j b n apple python john bean nice ample joke and this is what works, but I would also like to know how to wrap the columns, plus any ideas on a better way to accomplish this. #!/usr/bin/env python data = {} lrgColumn = 0 for line in open("test.txt","r").read().splitlines(): char = line[0].lower() if not char in data: data[char] = [line] else: data[char].append(line) for item in data: print item.ljust(10), if len(data[item]) > lrgColumn: lrgColumn = len(data[item]) print for item in range(lrgColumn): for i in data.iteritems(): try: print i[1][item].ljust(10), except IndexError: print "".ljust(10), print ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Triangle structure for triangulation
Dear Allan, thanks for your coments. > > ## I can translate it into python in this way > > class Triangle: > >def __init__(self, points, neighbours): > >self.points = points > >self.neighbours = neighbours > > > > def TOR(self, direction): > >return (self, (direction+1)%3) > > > > def ROT(self, direction): > >return (self, (direction+2)%3) > > > > def RIGHT(self, direction): > >return (self.neighbours[(direction+2)%3]) > > > > I would ask your opinions to encapsulate a triangle into a directed > > triangle. > > I'm not totally sure what you are looking for but my first > guess would be to add a direction argument to the init > and store it as an attribute. But it sounds like you need > to add some methods too. What do you do with these > triangles? From your descriptionI'd expect to see some > methods taking other triangles as arguments? The triangulation would be used for surface modelling. The most important function is CalcZ(point(x, y)), that interpolates the elevation on the surface of a triangle. For this interpolation I have to find the corresponding triangle of the point, that can be made the fastest by walking from triangle to triangle. This is the first reason I need the neighbours. I also need to extend and update the triangulation, when a new point inserted into it. > For example you store the points but never use them. > Attributes in a class shjould be thee to support the metjods. > If the atrributes are not used by any method that implies > that they are not needed or that you are accessing them > from some function outside the class, which is probably > an indication of bad OO design. I feel that, the best would be to strore 3 separate triangles for A,B,C points, Triangulation.Append(Triangle(A,B,C)) Triangulation.Append(Triangle(B,C,A)) Triangulation.Append(Triangle(C,A,B)) And register the topological relations after it. It could be OO, and simple. As I wrote, I made it in C with structures, so it wasn't OO, but fast. I can translate a C iteration over C structures into python, to iterate over class objects, and usually I don't miss the pointers. Except now, when the algorithm based strongly on pointers and indeces :( Yours sincerely, Janos Juhasz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting output into columns
"Scott Oertel" <[EMAIL PROTECTED]> wrote > and you want to sort and output the text into columns as such: > > a p j b n > apple python john bean nice > ample joke > > and this is what works, but I would also like to know how to wrap > the > columns, plus any ideas on a better way to accomplish this. Use format strings. You can calculate the column widths by analyzing the data then create a format string for the required number of columns. Finally insert the data on each row from a tuple. 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] Formatting output into columns
Alan Gauld wrote: > "Scott Oertel" <[EMAIL PROTECTED]> wrote > > >> and you want to sort and output the text into columns as such: >> >> a p j b n >> apple python john bean nice >> ample joke >> >> and this is what works, but I would also like to know how to wrap >> the >> columns, plus any ideas on a better way to accomplish this. >> > > Use format strings. You can calculate the column widths by analyzing > the data then create a format string for the required number of > columns. > Finally insert the data on each row from a tuple. > > > HTH, > > > Do you have any good documentation that could shed some more light on exactly how to use format strings in such a way? -Scott Oertel ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting output into columns
Scott Oertel wrote: > #!/usr/bin/env python > > data = {} > lrgColumn = 0 > > for line in open("test.txt","r").read().splitlines(): > char = line[0].lower() > if not char in data: > data[char] = [line] > else: > data[char].append(line) I like data.setdefault(char, []).append(line) instead of the four lines above. > > for item in data: > print item.ljust(10), > if len(data[item]) > lrgColumn: > lrgColumn = len(data[item]) > print > > for item in range(lrgColumn): > for i in data.iteritems(): > try: > print i[1][item].ljust(10), If you used data.itervalues() then it would be just print i[item].ljust(10), > except IndexError: > print "".ljust(10), > print To get the data in row order you can use map(None, *data.values()) This will give a list of rows with None in the blank spots. You might like one of these recipes for the actual table output: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519618 Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Triangle structure for triangulation
"János Juhász" <[EMAIL PROTECTED]> wrote >> > ## I can translate it into python in this way >> > class Triangle: >> > def __init__(self, points, neighbours): >> > def TOR(self, direction): >> > def ROT(self, direction): >> > def RIGHT(self, direction): >> and store it as an attribute. But it sounds like you need >> to add some methods too. What do you do with these >> triangles? > The most important function is CalcZ(point(x, y)), that interpolates > the > elevation on the surface of a triangle. > For this interpolation I have to find the corresponding triangle of > the > point, that can be made the fastest by walking from triangle to > triangle. > This is the first reason I need the neighbours. OK, That suggests to me that your triangle should have a predicate method contains(aPoint) where aPoint is a tuple of x,y coords and it returns a boolean. The iteration could then become a list comprehension: candidates = [t for t in triangles if t.contains(myPoint)] candidates will be a list of all triangles containing the point (hopefully a very short list!!) And the calcZ function could be a method of the collection of triangles if the collection were made into a class - a TriangualtedSurface maybe? > I also need to extend and update the triangulation, when a new point > inserted into it. OK That sounds like a job for the Surface class too, but with a fairt bit of help from, the triangles within it. A lot of the adoption of OOP is about rethinking how procedural style functionscan be split up with the various responsibilities parceled out between the various objects. The end result tends to be a lot of small methods within the various classes. And the top level method either simply orchestrates the execution of the helper methods in the component classes or starts a cascade of method calls as each component does something then delegates to its components (this is usually how GUIs work). I suspect your surface model would be a candidate for the orchestration technique. > I feel that, the best would be to strore 3 separate triangles for > A,B,C > points, > > Triangulation.Append(Triangle(A,B,C)) > Triangulation.Append(Triangle(B,C,A)) > Triangulation.Append(Triangle(C,A,B)) > And register the topological relations after it. It could be OO, and > simple. OO is usually simpler that traditiona;l procedural once you get the knack. Its because you delegate the functions to where the data is so all processing tends to be simplified. The big down side is that you can end up with very deep call stacks, but in practice this is rarely as big a problem as traditionalists expected when OOP was introduced. > As I wrote, I made it in C with structures, so it wasn't OO, but > fast. OO doesn't need to be slow, especially in C++ where some OOP programs have been shown to be faster than their non OOP equiva;lents. But in Python speed of execution is almost never the primary aim, "fast enough" and easy to build and maintain are the usual goals. > Except now, when the algorithm based strongly on pointers and > indeces :( Real low level pointer arithmetic can be tricky to convert pythonically but normal array indexing is nt usually an issue. Either a while loop or a for loop will do the job. But an OOP approach can often render both unnecessary, or at least greatly simplify things. 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] Formatting output into columns
"Scott Oertel" <[EMAIL PROTECTED]> wrote >> Use format strings. You can calculate the column widths by >> analyzing >> the data then create a format string for the required number of >> columns. >> Finally insert the data on each row from a tuple. >> > Do you have any good documentation that could shed some more light > on > exactly how to use format strings in such a way? The docs contain the basic documentation, here is a short example: data = ['one','fifteen',''four'] max_width = max([len(w) for w in data)]) # there's a slightly better way to do this which I can't recall right now! # %% -> literal %, # %s = insert string # so %%%ss -> %Xs where X is the inserted data fmtStr = "%%%ss\t%%%ss%%%ss" % (max_width, max_width, max_width) print fmtStr % tuple(data) That should produce a format string where each column is the max width of any of the data items You can use the string center() method to pad the headings if required. You can either put left/right justification into the format string (using +/-) or use the string methods (rjust,ljust) to do it for you. If its not clear how to extend that to a multi dimensional set of data then feel free to ask for more detail with some sample data and the specific requirements 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
[Tutor] Variable scope for class?
I'm trying to follow the example listed in the wiki at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject regarding the use of a metaclass. What I don't understand is how the metaclass (EntitySingleton) has access to the variable ctx which is instantinated outside the scope of the class definition. Could anyone point me in the right direction please? Thanks, Orest ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting output into columns
Alan Gauld wrote: > "Scott Oertel" <[EMAIL PROTECTED]> wrote >> Do you have any good documentation that could shed some more light >> on >> exactly how to use format strings in such a way? > > The docs contain the basic documentation http://docs.python.org/lib/typesseq-strings.html > # there's a slightly better way to do this which I can't recall right > now! > # %% -> literal %, > # %s = insert string > # so %%%ss -> %Xs where X is the inserted data > fmtStr = "%%%ss\t%%%ss%%%ss" % (max_width, max_width, max_width) > > print fmtStr % tuple(data) I think you are looking for * as a width specifier which takes the width from the argument list though it might be a bit awkward in this case where the length of the argument list varies. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable scope for class?
Orest Kozyar wrote: > I'm trying to follow the example listed in the wiki at > http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject regarding the > use of a metaclass. > > What I don't understand is how the metaclass (EntitySingleton) has access to > the variable ctx which is instantinated outside the scope of the class > definition. Could anyone point me in the right direction please? This is just basic name lookup rules. Names are looked up, in order, - in the scope of the current function - in the scope of any lexically enclosing functions - in the scope of the module containing the function (the 'global' scope) - in the built-in scope. ctx is defined at module level so the third step of the name lookup finds it. Not finding any great references but here are a few that might help: http://diveintopython.org/html_processing/locals_and_globals.html http://swaroopch.info/text/Special:Search?search=namespace&go=Go http://docs.python.org/ref/naming.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable scope for class?
On Thu, Aug 30, 2007 at 06:02:12PM -0400, Orest Kozyar wrote: > I'm trying to follow the example listed in the wiki at > http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject regarding the > use of a metaclass. > > What I don't understand is how the metaclass (EntitySingleton) has access to > the variable ctx which is instantinated outside the scope of the class > definition. Could anyone point me in the right direction please? Alan's book has a chapter on this (chapter 16 "Namespaces", in "Learn to Program using Python"). And, "Learning Python", by Mark Lutz also covers it. You will need to pay attention to the LEGB rule, which basically says that Python searches for a name in namespaces in the following order: 1. Local 2. Enclosing (specifically enclosing functions if this is a nested function) 3. Global 4. Built-ins So, in your specific example, Python looks: 1. In the Local namespace, but can't find ctx. 2. The enclosing namespace, but there is none, since this function/method is not nested in another one. 3. The Global namespace, where it finds "ctx" and quits. One thing to keep in mind, is that Python looks for names (variables) in the namespaces where a class or method or function is defined, *not* in the namespaces where those objects are used or called. So far so good. But, here is the one I do not understand. G1 = 111 class A(object): G1 = 222 def show(self): print G1 def test(): a = A() a.show() test() But, when I run this I see "111", not "222". Why is that? "G1 = 222" is in the enclosing scope, right? Well, I guess that is wrong. Apparently in Python, a class does not create an enclosing scope. Actually, the particular edition of Alan's book that I have is old enough so that it does not discuss the Enclosing namespace, which came later to Python. The enclosing namespace not make a difference in your example, but does in mine. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable scope for class?
Dave Kuhlman wrote: > So far so good. But, here is the one I do not understand. > > G1 = 111 > class A(object): > G1 = 222 > def show(self): > print G1 > > def test(): > a = A() > a.show() > > test() > > But, when I run this I see "111", not "222". > > Why is that? "G1 = 222" is in the enclosing scope, right? > > Well, I guess that is wrong. Apparently in Python, a class does > not create an enclosing scope. Right. The class statement creates a temporary local namespace that is used to initialize the __dict__ of the class. Names in this namespace can be accessed directly while the class statement is executing; after that they have to be accessed as attributes of the class or an instance. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable scope for class?
"Dave Kuhlman" <[EMAIL PROTECTED]> wrote > Actually, the particular edition of Alan's book that I have is old > enough so that it does not discuss the Enclosing namespace, which > came later to Python. The enclosing namespace not make a > difference in your example, but does in mine. The paper book is based on Python 1.5.1 The web page is based on Python 2.2 and mentions enclosing scope (although I call it "nested" and avoid discussing it in detail! :-) I intended adding sections in the functional programming and OOP topics but it doesn't look like I ever really got round to it! oops! :-( Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Formatting output into columns
Scott Oertel wrote: > Someone asked me this question the other day, and I couldn't think of > any easy way of printing the output besides what I came up with pasted > below. > > So what you have is a file with words in it as such: > > apple > john > bean > joke > ample > python > nice > > and you want to sort and output the text into columns as such: > > a p j b n > apple python john bean nice > ample joke > > and this is what works, but I would also like to know how to wrap the > columns, plus any ideas on a better way to accomplish this. > > #!/usr/bin/env python > > data = {} > lrgColumn = 0 > > for line in open("test.txt","r").read().splitlines(): > you can just directly do for line in open('test.txt'): depending on your Python version. I believe it's 2.3+. I have 2.4 and it works there, at least. If using an older version of Python, you can use .readlines() instead of .read().splitlines() I believe Kent and Alan already helped you with your original question. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor