Re: Suggested coding style

2011-09-26 Thread DevPlayer
On Sep 25, 11:41 pm, Chris Angelico  wrote:
> On Mon, Sep 26, 2011 at 12:59 PM, Tim Johnson  wrote:
> > BTW: If you like ranting as a spectator sport, I have found the
> >  Common Lisp newsgroup to be among the most spectacular. But that's
> >  just me.
>
> I do, actually, but I don't need to add another newsgroup. Rick
> provides plenty of material here, and I can easily sate myself in just
> a few other places that I frequent. It's quite amusing to watch those
> holy wars erupt...
>
> And every once in a while, they actually prove quite educative. I'm
> not sure how it happens, nor how to trigger it - hmm, perhaps this
> should be the subject of a scientific paper. "On ranting newsgroups
> and how to make them productive".
>
> ChrisA

I think intellectual growth from rants works like this:

Ranter: Bla bla, bad logic, poor facts, some point.
Others: Bla bla you rant Mr Ranter, some logic, few facts, same point.
Ranter: bad mouthing
Others: bad mouthing back
Ranter: Bla Bla, I don't rant, better logic counter facts, lots of
opinion (to not get called a ranter)
Others: Bla bla, You do rant Ranter, good counter logic and facts,
same point (some reason needs to put Ranter "in his place")
Ranter: Super Bla, long winded logic with some strong points, random
but accurate facts out the wazzu (tries to save face)
Others: Acknowleges Ranters point are accurate but claims they don't
apply
Ranter: makes case his points do.
Others: agrees to disagree, silently picks mute Ranter,
Ranter: picks a new topic and starts over.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-26 Thread DevPlayer
By the way OP Passiday the title of the topic is "Suggested coding
style".

Are you suggesting a coding style or asking for a Python coding style
or are you asking what IS the Python coding style.

If you are asking what is the Python coding style. Google The Zen of
Python. It's pretty much the dictum of coding style and referred to
alot by many Pythoneers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread DevPlayer
On Sep 27, 10:25 pm, alex23  wrote:
> rantingrick  wrote:
> > Since, like the bible
> > the zen is self contradicting, any argument utilizing the zen can be
> > defeated utilizing the zen.
>
> And like the Bible, the Zen was created by humans as a joke. If you're
> taking it too seriously, that's your problem.
>
> > If however you want to learn about the accepted rules for formatting
> > code then you need to read "PEP-8"! PEP 8 is our style guide.
>
Contradiction is only seen by narrow perspectve.

Calling the Bible a joke is used to hurt people, not enlighten them.
Those words show bitter arrogance, not constructive critism as it
ignores how others feel about that book. What benefit to others is
gained by calling someones belief a joke? To put the "believers" minds
straight? I think not. I think the unsensitive person who attackes
others beliefs, even if illogical or unrealistic, is after some kind
of self grandizement or to illude themself into thinking "they know
the truth of the universe" and should attack others to prove they do.

Although this is not the place to defend about such things it is also
not the place to attack those same things (that being someone's
faith). There is no real forum to defend a faith or religion, or words
in a book about that, other then where such faiths are in fact
attacked.

However I did laugh at the ironic use of using any-kind of zen to
seriously, even Python's, as that is very unzen-like. That is a
contradiction by it's very own definitions!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread DevPlayer
Oh I was just testing my intellecual-enlightenment-from-ranter-
conversation algorithm found in a previous post. I think my OOP model
failed as I'm just too tired to finished that pattern test. He had
some good points which fit the process I layed out. But the original
topic is just so much better:

Suggested coding style Options



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-09-30 Thread DevPlayer
from attitude import humour

Funny. url link to gif. Funny. Youtube video. Funny.

True Pythonees do not speak in English they speak in Python.

Shame, this discussion will be sent to the Pearly gates or the Flaming
Iron Bars in 5 days. Well, not so much a shame.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-09-30 Thread DevPlayer
I still assert that contradiction is caused by narrow perspective.

By that I mean: just because an objects scope may not see a certain
condition, doesn't mean that condition is non-existant.

I also propose that just because something seems to contradict doesn't
mean it is false. Take for instance:

Look out your window. Is it daylight or night time? You may say it is
daylight or you may say it is night time. I would disagree that only
one of those conditions are true. Both conditions are true. Always. It
is only day (or night) for YOU. But the opposite DOES in fact exist on
the other side of the world at the same time.

I call this Duality of Nature (and I believe there was some religion
somewhere in some time that has the same notion, Budism I think but I
could be mistaken). I see such "contradictions" in what appears to be
most truths.

If I am correct; not sure here; but I think that is part of the new
math Choas theory. (The notion that not all variables are known and
the results of well defined functions may result in completely
different actual outcomes) [Missing variables in such data sets and
functions, to me is basically a narrow(er) perspective of the all the
revelent factors for such computations.]

You could think of this in terms of classes and attributes if you
want. Just because an object does not see an attribute, like "has_
connection", doesn't mean the app doesn't have a connection to the
server, just that that object doesn't have access to the existance of
that attribute, because it is not in scope (ie narrow perspective).

I propose that if something seems to contradict itself, that that
doesnt' invalidate its value outright. It -could- invalidate its
value, but doesn't guarentee no value.

How this matters to coding style? No connection visible. It's just a
proposed notion.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can I search a list for a range of values?

2011-10-15 Thread DevPlayer
On Oct 14, 7:46 pm, Ian Kelly  wrote:
> On Fri, Oct 14, 2011 at 5:36 PM, Troy S  wrote:
> (Python 3)
> date_range = {d:v for d, v in source_dict.items() if '20110809' <= d
> <= '20110911'}
> Ian- Hide quoted text -
> - Show quoted text -

(Python 2.7) supports dictionary comprehensions. I prehaps as early as
2.5.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I am a newbie for python and try to understand class Inheritance.

2011-10-15 Thread DevPlayer
On Oct 15, 2:20 am, aaabb...@hotmail.com wrote:
> Test.py
> ---
> #!/usr/bin/python
>
> from my_lib import my_function
>
> class MyClass(my_function): # usually class names start capital
>
> """We know you're not forgetting to document."""
>
>     def __init__(self, name):
> super(MyClass, self).__init__(name)
>         # self.name = name automatically added from base class
>
>     def test(self):
>         print "this is a test", self.name
>
> def __call__(self, name):
>
># if you are subclassing something named my_function
># then other Python coders -might- expect the subclass
># to behave like a function.
>
>print "Now this class acts like a function %s" % name
>print "because it has a def __call__(self,...)."
>return True   # not needed but because functions do stuff
>
> If __name__ == '__main__':
>     myclass_instance = MyClass('David') # confusing isn't it to subclass 
> something called my_function

> 
> my_lib.py
> -
> class my_function(object):
>
> """This class acts like a function."""
>
> def __init__(self, name):
> self.name = SpamSpamAndEggs(name)
>
> def __call__(self):
> # do stuff
> return self.name.upper()
> ...
>
> -david

I editted your code to something closer to what is expected.
Not a law but just a recommendation.
Also defining a class my_function(..): --might-- be confusing to
others as in Python there are things called functions that look like
this:

def my_function(name):
print "Hi %s" % name

note the use of "def" and not "class"

Of course if you are making classes that represent custom application
"functions" verse Python "functions" then yeah, calling your class:

class MyFunction(object): ... makes sense

I included the __doc__ "You are documenting" stuff because you seem so
new. Otherwise when posting here they're not expected to be in these
posts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Usefulness of the "not in" operator

2011-10-15 Thread DevPlayer
On Oct 8, 8:41 am, Alain Ketterlin 
wrote:
> candide  writes:
> > Python provides
>
> >     -- the not operator, meaning logical negation
> >     -- the in operator, meaning membership
>
> > On the other hand, Python provides the not in operator meaning
> > non-membership. However, it seems we can reformulate any "not in"
> > expression using only "not" and "in" operation.
>
> Sure, but note that you can also reformulate != using not and ==, <
> using not and >=, etc. Operators like "not in" and "is not" should
> really be considered single tokens, even though they seem to use "not".
> And I think they are really convenient.
>
> -- Alain.

1. I thought "x not in y" was later added as syntax sugar for "not x
in y"
meaning they used the same set of tokens. (Too lazy to check the
actual tokens)

2. "x not in y" ==>> (True if y.__call__(x) else False)
class Y(object):
def __contains__(self, x):
for item in y:
if x == y:
return True
return False

And if you wanted "x not in y" to be a different token you'd have to
ADD

class Y(object):
def __not_contained__(self, x):
for item in self:
if x == y:
return False
return True

AND with __not_contained__() you'd always have to iterate the entire
sequence to make sure even the last item doesn't match.

SO with one token "x not in y" you DON'T have to itterate through the
entire sequence thus it is more effiecient.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-10-17 Thread DevPlayer
> DevPlayer  wrote:
> >I still assert that contradiction is caused by narrow perspective.
> >By that I mean: just because an objects scope may not see a certain
> >condition, doesn't mean that condition is non-existant.

> Groetjes Albert wrote:
> This is a far cry from the bible stating that someone is his
> own grand father. Or going to great length to prove that Jezus
> (through Jozef) is a descendant of David. Then declaring it
> a dogma that Jozef has nothing to do with it.

Do you not see? For ...
One man's garbage is another man's treasure.
One man's delusion is another man's epiphany.
One man's untruth is another man's belief.
One man's thing to attack is another mans thing to shield and defend.
One man's logical undenighable truth is another man's small part of a
bigger picture.

As has been said for example does 1+1 = 2. Only in one small
persepective. Whaa? what wack job says stuff like that?
1+1 = 10. In the bigger picture there is more then one numberic base
besides decimal, such as binary. Or then one might say there are only
10 integer numbers from 0 to 9 or from 1 to 10 if you like. Again in
the limited view, true, but in the larger view no. The Elucid
numbering scale is not the only numbering scale ever invented, or
needed for that matter.

http://en.wikipedia.org/wiki/Euclidean_geometry
"Euclid's axioms seemed so intuitively obvious that any theorem proved
from them was deemed true in an absolute, often metaphysical, sense.
Today, however, many other self-consistent non-Euclidean geometries
are known, the first ones having been discovered in the early 19th
century. An implication of Einstein's theory of general relativity is
that Euclidean space is a good approximation to the properties of
physical space ..."



> Groetjes Albert wrote:
> (It being ... well ... you know ...)
Um... Huh? sorry didn't know what you meant. You got me on that one.
Ellipses just put my brain into recursive mode.


> Groetjes Albert wrote:
> (I have this book, it is called "the amusing bible" with all
> flippant and contradictory stuff pointed out by a French
> 1930 communist. Cartoons too. )
I likely would find it very funny.


> Economic growth -- being exponential -- ultimately falters.
How true indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Benefit and belief

2011-10-17 Thread DevPlayer
On Oct 17, 10:34 am, Steven D'Aprano  wrote:
> On Mon, 17 Oct 2011 05:59:04 -0700, DevPlayer wrote:
> > As has been said for example does 1+1 = 2. Only in one small
> > persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the
> > bigger picture there is more then one numberic base besides decimal,
> > such as binary.
>
> That is no more deep and meaningful than the fact that while some people
> say "one plus one equals two", others say "eins und eins gleich zwei",
> some say "un et un fait deux" and some say "один и один дает два".
> Regardless of whether you write two, zwei, два, δυο, 2 (in decimal), 10
> (in binary), II (in Roman numerals) or even {0,1} using set theory
> notation, the number remains the same, only the symbol we use to label it
> is different.
>
> Do not confuse the map for the territory.
> Steven
Good point. But I disagree:

The symbol is not only used to label it. The symbol is used to put it
in context in reference to something else. "2" is a quantity in
decimal, but in binary, "2" is not a quantity nor is 01+01==10 equal
to "2" from withIN the binary perspective. Those symantics are
symbolic of concepts which are being equated to quantities OUTSIDE of
the binary perspective. True binary states, True + True does not equal
two True, correct?

Programmers use binary "math" to -represent- quantity. Here you are
arranging syntax to change meaning -out of scope-. The original
machine language notation inventors could have said in binary there is
no 1+1  they could have said "1 Jumps 1 means "A"", or "On repowers On
equals 5th gate in nand circuit".

To reitterate, I agree with you that it doesn't matter what symbology
you use if that symobology represents "same-stateness" -FROM a broader
perspective (i.e. scope). BUT in binary, in the narrow scope of binary
logic there is no "2". The available states are restrained to the
scope you place them, when WITHIN that scope. (using caps to try to be
clear and I don't intend to say you are wrong and I am right but to
say, I disagree because of this logic. Said differently I intend to
explain, not to demoralize or offend).

"1+1=10" is being viewed as 2 because of a larger world view is being
used, a broader perspective. Using broader concepts of numbers and
math which is a superset of a strictly binary system and is also a
superset of a decimal only view. Remember a computer does not function
with concepts of "2" or "a" or "15". Computers function in ons and
offs and "indeterminate" states. The binary representation of "10" to
a computer does not mean "2". That quantity representation is
something the human applies to that state.

Perhaps a differant analogy made by someone else. Many years ago, I've
studied the "The Fourth Dimension" a book based mostly on math by
Rudy Rucker. There are a few books with that name but this one is
algra based. It attempts to teach the reader to be able to view 4
dimensional objects using 3 dimensional and even 2 dimensional
translations of "mapped" objects - with a 4 dimensional view.

There are two popular schools of thought on this attempt. 1. It's
impossible or us to concieve of a 4 dimentional space objects within
our 3 dimentional senses and perceptions. and 2. We can conceive  with
our mind-s eye 4 dimensional objects much like we concieve of 2
dimentional objects (the plane) and even harder one dimensional
objects.

The author attempts to teach by first using an analogy. First he
clarifies that for his purposes of 4 dimensional space, that no
dimension axis in his math singularly represents time or anything
ephemeral like the supernatural or energy or such. Each fo the 4
dimensions represent an axis in a physical vector. He then creates a 3
dimensional man who lives in a 3 dimensional world. This 3d man sees
up, down, north, south, east, west. And he can see a plane or even a
line. But the 3d man does not see the 4th axis because he is not made
of that vector and does not therefore have sensory to perceive that
axis.  The author then goes on to show a 2d man does not see the 3rd
axis and then better explains how the 1d man can only "see" in left or
right directions. Following that story further, keeping to certain
assumptions about 1d space, puts the man in a binary world view, where
there is no "2", much like a computer. there is not "2" there is only
10, which TO YOU is a 2. but to the 1d man and the computer is a 10.

Of course when you try to limit someone's view to make a point about a
limited view it sounds rediculas. Supposition is often that way after
all.

> That is no more deep and meaningful than the fact that while some people
> say "on

Re: Dynamically creating properties?

2011-10-27 Thread DevPlayer
On Oct 27, 3:59 pm, Andy Dingley  wrote:
> I have some XML, with a variable and somewhat unknown structure. I'd
> like to encapsulate this in a Python class and expose the text of the
> elements within as properties.
>
> How can I dynamically generate properties (or methods) and add them to
> my class?  I can easily produce a dictionary of the required element
> names and their text values, but how do I create new properties at run
> time?
>
> Thanks,

class MyX(object):
pass
myx = myx()

xml_tag = parse( file.readline() )

# should be a valid python named-reference syntax,
# although any object that can be a valid dict key is allowed.
# generally valid python named reference would be the answer to
your question
attribute = validate( xml_tag )

# dynamicly named property
setattr( myx, attribute, property(get_func, set_func, del_func,
attr_doc) )

# "dynamicly named method"
# really should be a valid python named-reference syntax
myfunc_name = validate(myfunc_name)

def somefunc(x):
return x+x
# or
somefunc = lambda x: x + x

setattr( myx, myfunc_name, somefunc )


So beaware of:
# \
setattr(myx, '1', 'one')

myx.1
File "", line 1
x.1
  ^
SyntaxError: invalid syntax

# \
x.'1'
  File "", line 1
x.'1'
^
SyntaxError: invalid syntax

# \
x.__dict__['1']   # returns
'one'

x.__dict__# returns
{'1': 'one'}

So you should validate your variable names if you are getting them
from somewhere.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically creating properties?

2011-10-27 Thread DevPlayer
Personally I like to use this function instead of a "try: except:"
because try-except will allow names like __metaclass__.

Remember, setattr(obj, attr_name, value) allows attr_name to be any
valid str().
For example: '!@kdafk11', or '1_1', '1e-20', '0.0', '*one', '\n%%',
etc.

def isvalid_named_reference( astring ):
# "varible name" is really a named_reference
# import string   # would be cleaner

valid_first_char =
'_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
valid_rest =
'_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

# I think it's ok here for the rare type-check
# as unicode named-references are not allowed
if type(astring) is not str: return False

if len(astring) == 0: return False

if astring[0] not in valid_first_char: return False

for c in astring[1:]:
if c not in valid_rest: return False

# Python keywords not allowed as named references (variable names)
for astr in ['and', 'assert', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'exec',
'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'not', 'or',
'pass', 'print', 'raise', 'return', 'try',
'while', 'yield',]:
if astring == astr: return False

# valid names but bad idea
if astring == '__builtins__': return None
if astring == '__metaclass__': return None
for astr in dir(__builtins__):
if astring == astr: return None # use None as a warning

# there might be more like __slots__, and other
# module level effecting special names like '__metaclass__'

return True

Also when using dynamically created "varible names" to check if your
objects have an attribute with that name already.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically creating properties?

2011-10-27 Thread DevPlayer

At least one error:
change:
> for astr in dir(__builtins__):
to:
for astr in __builtins__.__dict__:
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically creating properties?

2011-10-27 Thread DevPlayer
Second error

def isvalid_named_reference( astring ):
# "varible name" is really a named_reference
import __builtin__# add line


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamically creating properties?

2011-10-30 Thread DevPlayer
To be honest, I was hoping someone would have posted a link to a well
known and tested recipe. You'd think this function would be in the
standard library or a specific Exception tied directly with setattr()
and getattr() (and possibly __getattr__(), __getattribute__(),
__setattr__())

The main thing I wanted to point out though is when you start using
dynamically named references, there's more to it then just letting a
dynamic file define it.

If there's a way to reference a set of data, it really shouldn't be
with a "dynamically named reference" too often.

Databases are a good example. Perhaps this is a better way for
example: If you have a bunch of tables in your DB -is- it better to
get the table def and create a Python class with dynamically named
"fields"?

Or is it better to create a Table class with name attribute and a
Field class with a name attribute (named "name")

SO instead of :
field_name = xml_parse.get_next_field_name(xml_table_definition)
my_table = Table()
setattr(my_table, field_name,
empty_list_to_later_contain_field_data)

Perhaps:
field_name = xml_parse.get_next_field_name(xml_table_definition)
my_table = Table()
my_table.fields[field_name] =
empty_list_to_later_contain_field_data
# or
my_table.add_field( Field(field_name) )

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: locate executables for different platforms

2011-10-31 Thread DevPlayer
On Oct 31, 10:00 am, Andrea Crotti  wrote:
> Suppose that I have a project which (should be)/is multiplatform in python,
> which, however, uses some executables as black-boxes.
>
> These executables are platform-dependent and at the moment they're just
> thrown inside the same egg, and using pkg_resources to get the path.
>
> I would like to rewrite this thing being able to:
> - detect the OS
> - find the right executable version
> - get the path and run it
>
> It would be nice to still be able to use pkg_resources, but at that
> point I think
> I would need to store all the executables in another egg, is that correct?
> Is there already something available to manage external multi-platform
> executables?
>
> Thanks,
> Andrea

While this doesn't answer your question fully, here is a beta snippet
I wrote in Python, that returns a list of full pathnames, for a set of
specified filenames, found in paths specified by PATH environment
variable. Only tested on WIN32. Note on WIN32 systems the snippet
tries to find filenames with extensions specified by the environment
varible PATHEXT. On Unix it will also try with no extension, of cource
(not tested). Enjoy.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Review Python site with useful code snippets

2011-10-31 Thread DevPlayer

When visitors visit your site to post their code; often such posts ask
for username and email address; consider adding additional fields to
generate some Python documenting feature like Sphinx or epydoc.

and let your site inject the docstring (module string) into the
snippet; primarily, author, url=YOUR url if not provided by them,
date, python version, os, etc... See reStructuRE for possible fields
to inject.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to mix-in __getattr__ after the fact?

2011-11-01 Thread DevPlayer
On Oct 31, 8:01 am, dhyams  wrote:
> Thanks for all of the responses; everyone was exactly correct, and
> obeying the binding rules for special methods did work in the example
> above.  Unfortunately, I only have read-only access to the class
> itself (it was a VTK class wrapped with SWIG), so I had to find
> another way to accomplish what I was after.
>
Please share what you found as the other way.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Usefulness of the "not in" operator

2011-11-06 Thread DevPlayer
On Oct 16, 12:05 am, Steven D'Aprano  wrote:
> On Sat, 15 Oct 2011 15:04:24 -0700, DevPlayer wrote:
> > I thought "x not in y" was later added as syntax sugar for "not x in y"
> > meaning they used the same set of tokens. (Too lazy to check the actual
> > tokens)
Stated in response to OP wanting a seperate token for "not in" verse
"is not".

> Whether the compiler has a special token for "not in" is irrelevant.
I don't know.

> Perhaps it uses one token, or two, or none at all because a
> pre-processor changes "x not in y" to "not x in y". That's
> an implementation detail.
I agree.

> What's important is whether it is valid syntax or not, and how it is
> implemented.
I agree.

> As it turns out, the Python compiler does not distinguish the two forms:
>
> >>> from dis import dis
> >>> dis(compile('x not in y', '', 'single'))
>
>   1           0 LOAD_NAME                0 (x)
>               3 LOAD_NAME                1 (y)
>               6 COMPARE_OP               7 (not in)
>               9 PRINT_EXPR
>              10 LOAD_CONST               0 (None)
>              13 RETURN_VALUE        >>> dis(compile('not x in y', '', 
> 'single'))
>
>   1           0 LOAD_NAME                0 (x)
>               3 LOAD_NAME                1 (y)
>               6 COMPARE_OP               7 (not in)
>               9 PRINT_EXPR
>              10 LOAD_CONST               0 (None)
>              13 RETURN_VALUE

So cool! Thanks for showing how to do that.

I tried to say implementing a seperate method was not efficient.

> Also for what it is worth, "x not in y" goes back to at least Python 1.5,
> and possibly even older. (I don't have any older versions available to
> test.)
So "not in" was added as an alternative (just a long time ago).
I too am glad they added it.

> (2) Instead of writing "True if blah else False", write "bool(blah)".
Good tip! I like.

>
> > class Y(object):
> >     def __contains__(self, x):
> >         for item in y:
> >         if x == y:
> >             return True
> >         return False
>
> You don't have to define a __contains__ method if you just want to test
> each item sequentially. All you need is to obey the sequence protocol and
> define a __getitem__ that works in the conventional way:

Didn't intend to show how to implement __contains__ using "==" and
__not_contains__ "<>" in python but to show that python didn't benefit
from the not_in loop as much as for example assembly language does
it's loop (x86 LOOPE/LOOPZ vs LOOPNZ/LOOPNE).

>
> >>> class Test:
>
> ...     def __init__(self, args):
> ...             self._data = list(args)
> ...     def __getitem__(self, i):
> ...             return self._data[i]
> ...>>> t = Test("abcde")
> >>> "c" in t
> True
> >>> "x" in t
> False
Another new thing for me.

>
> Defining a specialist __contains__ method is only necessary for non-
> sequences, or if you have some fast method for testing whether an item is
> in the object quickly. If all you do is test each element one at a time,
> in numeric order, don't bother writing __contains__.
>
> > And if you wanted "x not in y" to be a different token you'd have to ADD
>
> Tokens are irrelevant. "x not in y" is defined to be the same as "not x
> in y" no matter what.
> You can't define "not in" to do something completely different.
I agree they are not implemented differently.
I agree that they shouldn't be implemented differently.
I disagree they can not be implemented differently. I think they can.
But I see no reason too.

> > class Y(object):
> >     def __not_contained__(self, x):
> >         for item in self:
> >             if x == y:
> >                 return False
> >         return True
>
> > AND with __not_contained__() you'd always have to iterate the entire
> > sequence to make sure even the last item doesn't match.
> > SO with one token "x not in y" you DON'T have to itterate through the
> > entire sequence thus it is more effiecient.
> That's not correct.
> Steven
I tried to prove my point and failded and instead proved (to myself)
you are correct. It is not more efficient. Also I should have used if
<> y: continue to have better tried to make the point but it wouldn't
have mattered. I still would have been wrong.

But I did walk away from this topic with some goodie tips. Thanks
Steven.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Opportunity missed by Python ?

2011-11-14 Thread DevPlayer
What I don't get is, having seen Python's syntax with indentation
instead of open and closing puncuation and other -readability-
structures in Python's syntax, is if someone is going to invent any
new language, how could they NOT take Python's visual structures (read
as readability) and copy it, whether it be a compiled language,
explicidly typed checked or whatever underlying mechanism they want to
make that code executable.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple import hook

2011-11-14 Thread DevPlayer
An alternative approach:
http://pastebin.com/z6pNqFYE

or:

# devpla...@gmail.com
# 2011-Nov-15

# recordimports.py

# my Import Hook Hack in response to:
# 
http://groups.google.com/group/comp.lang.python/browse_thread/thread/5a5d5c724f142eb5?hl=en
# as an initial learning exercise

# This code needs to come before any imports you want recorded
# usually just once in the initial (main) module
# Of course you can excluding the if __name__ == '__main__': demo code

# barely tested:
#only tested with modules that had no errors on import
#did not need/use/expect/try  reload()
#ran with Python 2.7 on Win32
# create two fake modules moda.py and modb.py and stick some imports
in them

'''
Exerpt from PEP 302 -- New Import Hooks
...
Motivation:
- __import__ gets called even for modules that are already in
  sys.modules, which is almost never what you want, unless you're
  writing some sort of monitoring tool.

Note the last two words.'''


#
===
# place to save Collected imports
imported = []

# save old __builtins__.__import__()
__builtins__.__dict__['__old_import__'] =
__builtins__.__dict__['__import__']

# match __builtins__.__import__() function signature
def __myimport(name, globals={}, locals={}, fromlist=[], level=-1):
global imported

# I don't know why this works.
__name__ = locals['__name__']
__file__ = locals['__file__']
__package__ = locals['__package__']
__doc__ = locals['__doc__']

# call original __import__
module = __builtins__.__old_import__(name, globals, locals,
fromlist, level)

# save import module name into namespace
__builtins__.__dict__[name] = module

tag = (name, __name__, __file__, __package__, module)

# do not append duplicates
if tag not in imported:
imported.append( tag )

return module

# store the new __import__ into __builtins__
__builtins__.__dict__['__import__'] = __myimport

# erase unneed func name
del __myimport
#
===


# demo
if __name__ == '__main__':
# import some random packages/modules
import sys
import moda# a test module that does some other imports
import modb# a test module that does some imports
from pprint import pprint

# imported has name, __name__, __file__, __package__
# show each import
for n, __n, __f, __p, m in imported:
print n
print '   ', __n
print '   ', __f
print '   ', __p
print
del n, __n, __f, __p, m

print 'recordimports.py'
pprint(dir(), None, 4, 1)
print

print 'moda.py'
pprint(dir(moda), None, 4, 1)
print

print 'modb.py'
pprint(dir(modb), None, 4, 1)

# print imported
print
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to unimport a library

2011-11-21 Thread DevPlayer
On Nov 20, 12:21 pm, Gelonida N  wrote:
> I forgot to mention, that this is at the moment more a thought
> experiment, than a real need.
>
> At the moment I will do exactly what you suggested. I will make sure,
> that always the first import fails.
>
> But I wanted to learn more what is possible and which potential can of
> worms I would open if I wanted to unimport a library of which I'm sure
> that nobody is currently referencing (or refering? Not sure about my
> English here) to.

Get how many references to an object:
sys.getrefcount(sys)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to unimport a library

2011-11-23 Thread DevPlayer
Seems so far the common way to fully unload any import is to exit the
Python session.
Only if this is true do I offer this hackish idea:

Therefore you might wish to run an os script instead of a python
script right off.
Here is my hack at it... Something like this:

file myapp.bat
--
python get_availble_imports.py available_imports.log
python myapp.py available_imports.log


file get_availble_imports.py

find_module_names = """
os sys time
sqlite lib1_verA lib2_verA
sqlite3 lib1_verB lib2_verB
"""

# other code i'm leaving out of this forum post

def find_module_names_using_pydoc( block_string ):

'''Searchs for module names, provided in a block string,
against the resultant module names list returned from pydoc. \n
Returns a list of strings, being the intersection of module names
from both lists.'''

all_wanted_modules = parse_block_for_module_names( block_string )
# use split and drop empties

module_names_found = []

# walk_packages actually imports libraries;
# so you know the import should work.
# i call em modules; but they could be packages too

# following line can take many seconds to run
package_generator = pydoc.pkgutil.walk_packages(path=None,
prefix='', onerror=error_handler)

for package_name in package_generator:
module_loader, module_name, ispkg = package_name
if module_name in all_wanted_modules:
module_names_found.append( module_name )
print repr( module_name )

return module_names_found

found = find_module_names_using_pydoc( find_module_names )

#Then with a switch statement (if/elif) create a string with to be
#saved to the log file with what module names are in usable_mods

if 'sqlite' in found and 'lib1_verA' in found and 'lib2_verA' in
found:
save('import sqlite, lib1_verA, lib2_verA')
elif 'sqlite' in found and 'lib1_verB' in found and 'lib2_verB' in
found:
save('import sqlite3, lib1_verB, lib2_verB')
else:
raise ImportError('Necessary packages not found')


file myapp.py
-
with open('available_imports.log','r') as f:
text = f.read()
exec(text)
# DONE
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there any way to unimport a library

2011-11-23 Thread DevPlayer
btw if you like processing text outside of python (say using grep or
something)

python -c "help('modules')" > all_imports.log

which you might note on windows get's processed to:
python -c "help('modules')" 1> all_imports.log
on windows from within a batch file

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String splitting by spaces question

2011-11-23 Thread DevPlayer
This is an 'example string'

Don't for get to watch for things like:

Don't, Can't, Won't, I'll, He'll, Hor'davors, Mc'Kinly
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python shell that saves history of typed in commands that will persist between reboots

2011-11-27 Thread DevPlayer
On Nov 15, 10:38 pm, goldtech  wrote:
> Hi,
>
> Using Windows. Is there a python shell that has a history of typed in
> commands?
>
> I don't need output of commands just what I typed it. I need it to
> save between sessions - something that no shell seems to do. If I
> reboot there will still be a command history somewhere.
>
> Like bash history in Linux.
>
> Thanks

Something that might be of interest is wxPython's pyslicesshell.py
it's not commandline in console window but the interpreter in a
window. And you can save it.

I haven't used it lately by there's also PythonWin
http://python.net/crew/skippy/win32/PythonwinPreview.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using the Python Interpreter as a Reference

2011-11-28 Thread DevPlayer
On Nov 27, 6:55 pm, Steven D'Aprano  wrote:
> On Sun, 27 Nov 2011 14:21:01 -0800, Travis Parks wrote:
> > Personally, I find a lot of good things in Python. I thinking tabs are
> > out-of-date. Even the MAKE community wishes that the need for tabs would
> > go away and many implementations have done just that.
>
> Tabs have every theoretical advantage and only one practical
> disadvantage: the common toolsets used by Unix programmers are crap in
> their handling of tabs, and instead of fixing the toolsets, they blame
> the tabs.
>
> The use of spaces as indentation is a clear case of a technically worse
> solution winning over a better solution.
>
> > I have been
> > seriously debating about whether to force a specific number of spaces,
> > such as the classic 4, but I am not sure yet. Some times, 2 or even 8
> > spaces is appropriate (although I'm not sure when).
>
> Why on earth should your language dictate the width of an indentation? I
> can understand that you might care that indents are consistent within a
> single source code unit (a file?), but anything more than that is just
> obnoxious.
>

I do not understand why the interpreter preprocesses each logical line
of source code using something as simple as this:

def reindent( line, spaces_per_tab=os.spaces_per_tab):

index = 0  # index into line of text
indent = 0 # increase 1 when in next tab column
spaces = 0 # index into current column

for c in line:
if c == ' ':
spaces +=1
if spaces >= spaces_per_tab:
indent += 1
spaces = 0
if c == '\t':   # jump to next tab column
indent += 1
spaces = 0
if c <> ' ' and c <> '\t':
break
index += 1
rest_of_line = line[index:]
new_indent = ' ' * indent * spaces_per_tab + ' ' * spaces
newline = new_indent + rest_of_line

return newline

or even some regex equivelent.

That function would need to be run on each line of source code, after
processing the line continuation character and single/double/triple
quote pairs are processed but before the code block tokenizer (INDENT/
DEDENT) if possible. Unless some of you expert parser/compiler writers
know fancier tricks.

To me, I would think the interpreter finding the coder's intended
indent wouldn't be that hard. And just make the need for consistant
spaces or tabs irrevelent simply by reformatting the indent as
expected. Pretty much all my text editors can.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using the Python Interpreter as a Reference

2011-11-28 Thread DevPlayer
> I do not understand why the interpreter preprocesses each logical line
> of source code using something as simple as this:


correction:

I do not understand why the interpreter - does not- preprocess each
logical line
of source code using something as simple as this:
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using the Python Interpreter as a Reference

2011-12-01 Thread DevPlayer
On Nov 29, 3:04 am, Steven D'Aprano  wrote:
> On Tue, 29 Nov 2011 12:49:49 +1100, Chris Angelico wrote:
> > On Tue, Nov 29, 2011 at 11:54 AM, DevPlayer  wrote:
> >> To me, I would think the interpreter finding the coder's intended
> >> indent wouldn't be that hard. And just make the need for consistant
> >> spaces or tabs irrevelent simply by reformatting the indent as
> >> expected. Pretty much all my text editors can.
>
> > The trouble with having a language declaration that "a tab is equivalent
> > to X spaces" is that there's no consensus as to what X should be.
> > Historically X has always been 8, and quite a few programs still assume
> > this. I personally like 4. Some keep things narrow with 2. You can even
> > go 1 - a strict substitution of \t with \x20. Once you declare it in
> > your language, you immediately break everyone who uses anything
> > different.
>
> Why should we enforce how many spaces a tab is set to? That is literally
> only visible to the editor, not the compiler. (Unless the parser is
> particularly stupid and merely substitutes X spaces for a tab every time
> it sees one.)
>
> Mixed spaces and tabs in an indent are ambiguous, and so raises
> SyntaxError (or at least it *should* raise SyntaxError). But separate
> code blocks can use different absolute indent levels without ambiguity,
> so long as the relative indentation is consistent:
>
> def ham(): # tab stops at 4 and 8
>     do(a)
>     do(b)
>     if c:
>         do(c)
>     else:
>         do(d)
>
> def spam(): # tab stops at 8 and 12
>         do(a)
>         do(b)
>         if c:
>             do(c)
>         else:
>             do(d)
>
> There is no meaningful difference in indentation between ham and spam
> above. In either case, I could replace spaces with tabs to get the same
> relative indents regardless of the absolute indentation.
>
> I can appreciate the aesthetic argument that *within a single file*,
> indentation should be consistent. But it's not logically necessary for
> the parser: it need only be consistent within a single code unit
> (function or class usually). In other words: syntax should only care
> about relative indentation, absolute indentation belongs as a coding
> standard.
>
> --
> Steven

Great point. Your point is why I started writting my own little Python
parser/scanner (as an pet project/lesson project) and is in part, why
I wrote my little reindent() in the first place. I am/was trying to
figure out the algorithim for how Python's indent/dedents made logical
"code blocks" or "closures" or whatever they are called. That and see
if there was a way to interpret docstrings in various formats.

I often get indentation syntax errors when I cut and paste
stackflow.com, devprogrammer.com, daniweb.com, etc. code snippets into
my various IDEs/ editors and I wanted to make a little tabnanny of my
own. Some of the IDEs and editors (Editra) allow plugins. So I wanted
to get a baseline for the various plugins.

So I call the reindent() after I call the blocker(), which determines
a block by -releative- indent/dedent as +1 or, 0 or -1 whether that be
+4 spaces, +2 spaces, +1 tab or -3 spaces, whatever...; as you, Steve,
mentioned indent is not fixed but relative.

(btw I'v posted this in this topic because I thought it could
contribute to how Unit's choice of how indents are handled my benefit
from this discussion).

My thoughts on tab verse space chars;, for most old and even current
commandline interfaces, text editors, and historically line printers,
tabs simply acted like a macro to move x number of fixed spaces. It
wasn't until varible width fonts, kerning, and other advanced printing
techniques became mainstream<- did space chars differ in meaning from
tab chars, exception perhaps being file storage space (way back in the
day). I only say this because I can't stand hitting the right and left
arrow keys or using multiple fingers to move left and right 3 more
times then I have to while editing my text. I -feel- I move faster
around my text files with tabs then I do with 4 spaces.

They only annoyance I've had with Python's flexiblity with indent
using tab and or spaces is the docstrings.
\t = tab
def myfunc():
\t"""here is my docstring that bla bla bla's
\t\tand indented do da days...
\t"""

verse (s = space)
def myfunc():
"""here is my docstring that bla bla bla's
and indented do da days...
"""

verse space = tab or space
def myfunc():
"here is my docstring that bla bla bla's"\
"and indented do da days..."\
"\n"

verse the legal and sometimes seen form:
def myfunc(

Re: python 2.5 and ast

2011-12-02 Thread DevPlayer
On Nov 30, 1:03 pm, Andrea Crotti  wrote:
> Another thing about the AST, I am having fun trying to for example list
> out all
> the unused imports.
>
> I have already a visitor which works quite nicely I think, but now I
> would like
> to get a way to find all the unused imports, so I need more visitors that
> find out all the used names.
>
> I didn't find too much documentation about these kind of things, so any
> suggestions on how to approach?
>
> Pylint and snakefood have similar code, but they use the old "compiler"
> module,
> so it's not really helpful.

There was another topic in these forums recently about "un-importing"
modules (and how you can not do that reliably without restarting
python). There was various ways mentioned of keeping track of what was
imported. And there was mentioned reasonable ways of finding all
possible imports on a computer.

By "unused imports" I assume you mean "all unused imports in the
application's source code" as opposed to meaning "all unused modules/
packages/libraries on that computer."

Personally I'd love to see more tutorials on the AST module; An AST
for Dummies. Pretty much the tutorials talk about parsing an
expression like "1+2=3". But I'd like to see how blocks are compiled/
managed by the indent/dedent tokens and how the complete algorithm for
finding qouted strings is implimented (using really simple
explanations).

Some google buzzwords to help with your search for your question:  sys
import cache, import hook, pydoc walkpackages().

And I just found this little tool; never knew about it: C:\PythonXX
\Tools\Scripts\pydocui.pyw

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie Question: Obtain element from list of tuples

2011-12-19 Thread DevPlayer
On Dec 19, 1:46 am, "Frank Millman"  wrote:
> "Steven D'Aprano"  wrote in message
>
> news:4eeea8eb$0$11091$c3e8...@news.astraweb.com...
>
> > On Sun, 18 Dec 2011 18:35:47 -0800, alex23 wrote:
>
> >> Pre-namedtuple, I used to like using named slices for this:
>
> >>     cPID = slice(19)
> >>     pid = recs[cPID]
>
> > You know, that is an incredibly simple thing and yet it never dawned on
> > me before now. Thank you for sharing that.
>
> I also like it, but it does not work quite so simply for me.
>
> >>> row = tuple(range(20))
> >>> cPID = slice(15)
> >>> pid = row[cPID]
> >>> pid
>
> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14)
>
>
>
> This works -
>
>
>
> >>> row = tuple(range(20))
> >>> cPID = slice(15, 16)
> >>> pid, = row[cPID]  # note the trailing comma
> >>> pid
> 15
>
> Still nice, but not quite so elegant.
>
> Am I missing something?
>
> Frank Millman

if you're going to do:
> >>> cPID = slice(15, 16)
> >>> pid, = row[cPID]  # note the trailing comma

Why not just:
>>>row = tuple(range(20))
>>>cPID = 15 # a proposed constant
>>>pid = row[cPID]
>>>pid
15

It might be better for other's to debug if you use
>>> pid, _ = row[cPID]
as a little tiny comma like that is easy to miss in some text editors.
Not everyone has large LCD screens. Not that I like the "_" for this
purpose.

Personally I'd love to see the "_" used instead of "self" as a common
practice (useful when you use lots of "self" on a line).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing globals in exec by custom class

2010-12-08 Thread DevPlayer
Couple of things:

I don't think this is what you want:

   def __getitem__(self, key):
import __builtin__
if key == 'xx':
return 'xx'
I won't return a KeyError for any string you give g[]
It will return 'xx' only if you supply key='xx' and ignore every other
key=???
With the above code you can do g['yyy'] and you would get None

For your example code to work, line 14 in your example needs to be:
elif key in self.__dict__: # (change else to elif)

for your dict (or globalscl) to act like other dicts() add
an else:
raise KeyError( 'Key not found: %s' % (key,))

__dict__ of a dict I believe is not the namespace of dict. I thought
dict[key] and dict.__dict__[key] where not the same place

__dict__ of dict in Python 2.5 and prior was rumored to be buggy and
unused. Don't know about Python 2.6 +

I thought __getitem__() did not look in __dict__ of dict().

If I copy your code into a module globalcl.py
and comment out "print xx" in the string,
and in PyCrust I "import globalcl"
I too get the results and errors you claim.

If I then do:

>>>globalcl.g.keys()
I get: ['__builtins__']

>>>globalcl.g['__builtins__']
I get: nothing (or None)

>>>globalcl.g['__builtin__']
I get: nothing (or None)

# -
# interesting part

>>>globalcl.g['xx']
I get: 'xx'

>>>if 'xx' in globalcl.g:
...print True
...else:
...print False

I get: False
# -

>>>globalcl.g.__builtins__
AttributeError: 'Global' object has no attribute  __builtins__'

>>>globalcl.g.__builtins__
AttributeError: 'Global' object has no attribute '__builtin__'

>>>globalcl.g.__dict__
{'q': }



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing globals in exec by custom class

2010-12-08 Thread DevPlayer
Shouldn't
return 'xx'
be
return self['xx']
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing globals in exec by custom class

2010-12-08 Thread DevPlayer
Shouldn't
return 'xx'
be
return self['xx'


I don't know why precisely you're using a class as a global namespace,
not that I personally find fault with it. But here are some other
things you can do.

Idea one:
==
class NS(object): """place to put junk"""

ns = NS()

ns.global_var1 = "SPAM and eggs"
ns.global_var2 = "use as you like just prefix with ns."
del ns.global_var  # because I'm fickle
dir(ns)

Idea two:
==
Instead of a class as a global namespace, use a module

ns.py
--
"""My global namespace"""
# do not import anything or make
# classes or run functions here, just a place to have varibles

ns_var = "var defined in ns.py"

ignore = ['__builtins__', '__class__', '__delattr__', '__dict__',
'__doc__', '__file__', '__format__', '__getattribute__', '__hash__',
'__init__', '__name__', '__new__', '__package__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__',
'__subclasshook__']

main.py

import ns
import mod1
import mod2
import mod3

ns.main_var = "this is main var"

ns.mod3_var = mod3.mod3_var
ns.mod3_somefunc_var = mod3.somefunc.somefunc_var

mod3.show( "ns.ns_var", ns.ns_var)
mod3.show( "ns.main_var", ns.main_var)
mod3.show( "ns.mod1_var", ns.mod1_var)
mod3.show( "ns.mod2_var", ns.mod2_var)
mod3.show( "ns.somefunc_var", ns.somefunc_var)
mod3.show( "ns.mod3_var", ns.mod3_var)
mod3.show( "ns.mod3_somefunc_var", ns.mod3_somefunc_var)
mod3.show( "dir(ns)", dir(ns))
mod3.list_globals()


mod1.py
---
import ns

# good usage; var not in mod1 global namespace and value is not copied
# from one namespace to another but just put in it.

ns.mod1_var = "this is text in mod1"

# therefore by doing this your code in mod1 is likely to use
# ns.mod1_var and not just mod1_var -is- not ns.mod1_var


mod2.py
---
import ns

ns.mod2_var = "text in mod2"


def somefunc():
# good app globals
ns.somefunc_var = "make a var not in the global namespace of the
mod2"
ns.renamed_var = "rename this"

somefunc()



mod3.py
---
# mod3_var is misleading; because you might use it but mod3.mod3_var
# would not be the same value as the ns.mod3_var
mod3_var = "not assigned to ns from in mod3.py but from main.py"


def somefunc():
# bad globals
somefunc.somefunc_var = "make a var not in the global namespace of
the mod3"
somefunc.renamed_var = "rename this"

somefunc()  # instinate somefunc_var

def show(astring, avalue):
print astring
print '   ', str(avalue)

def list_globals():
print 'ns variable list'
import ns
print '   [',
for item in dir(ns):
if not item in ns.ignore:
print "'" + item.strip() + "', ",
print ']'
-- 
http://mail.python.org/mailman/listinfo/python-list


Python on wikipedia

2010-12-12 Thread DevPlayer
Snapshot in time, hey look at that; someone used Python as THE example
of what a programming language is on Wikipedia.
http://en.wikipedia.org/wiki/Programming_language
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can a function find the function that called it?

2010-12-25 Thread DevPlayer
> Original Poster
> I thought I'd implement it as a subclass of collections.OrderedDict
> that prohibits all modifications to the dictionary after it has
> been initialized.

I thought the __new__() method was for customizing how objects where
instantated. Where in __new__() you would get an object instance and
then usually initialize the public data attributes in __init__().
Although I like Mark Wooding's solution as it's clean and easy to
understand.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Partition Recursive

2010-12-27 Thread DevPlayer

# parse_url11.py

# devpla...@gmail.com
# 2010-12 (Dec)-27
# A brute force ugly hack from a novice programmer.

# You're welcome to use the code, clean it up, make positive
suggestions
# for improvement.

"""
Parse a url string into a list using a generator.
"""

#special_itemMeaning = ";?:@=&#."
#"//",
#"/",
special_item = [";", "?", ":", "@", "=", "&", "#", ".", "/", "//"]

# drop urls with obviously bad formatting - NOTIMPLEMENTED
drop_item = ["|", "localhost", "..", "///"]
ignore_urls_containing = ["php", "cgi"]

def url_parser_generator(url):
len_text = len(url)
index = 0
start1 = 0# required here if url contains ONLY specials
start2 = 0# required here if url contains ONLY non specials
while index < len_text:

# LOOP1 == Get and item in the special_item list; can be any
length
if url[index] in special_item:
start1 = index
inloop1 = True
while inloop1:
if inloop1:
if url[start1:index+1] in special_item:
#print "[",start1, ":", index+1, "] = ",
url[start1:index+1]
inloop1 = True
else:# not in ANYMORE, but was in special_item
#print "[",start1, ":", index, "] = ",
url[start1:index]
yield url[start1:index]
start1 = index
inloop1 = False

if inloop1:
if index < len_text-1:
index = index + 1
else:
#yield url[start1:index]  # NEW
inloop1 = False

elif url[index] in drop_item:
# not properly implemeted at all
raise NotImplemented(
"Processing items in the drop_item list is not "\
"implemented.", url[index])

elif url[index] in ignore_urls_containing:
# not properly implemeted at all
raise NotImplemented(
"Processing items in the ignore_urls_containing list
"\
"is not implemented.", url[index])

# LOOP2 == Get any item not in the special_item list; can be
any length
elif not url[index] in special_item:
start2 = index
inloop2 = True
while inloop2:
if inloop2:
#if not url[start2:index+1] in special_item:  #<-
doesn"t work
if not url[index] in special_item:
#print "[",start2, ":", index+1, "] = ",
url[start2:index+1]
inloop2 = True
else:# not in ANYMORE, but item was not in
special_item before
#print "[",start2, ":", index, "] = ",
url[start2:index]
yield url[start2:index]
start2 = index
inloop2 = False

if inloop2:
if index < len_text-1:
index = index + 1
else:
#yield url[start2:index]  # NEW
inloop2 = False

else:
print url[index], "Not Implemented" # should not get here
index = index + 1

if index >= len_text-1:
break

# Process any remaining part of URL and yield it to caller.
# Don't know if last item in url is a special or non special.
# Used start1 and start2 instead of start and
# used inloop1 and inloop2 instead of inloop
# to help debug, as using just "start" and "inloop" can get be
# harder to track in a generator.
if start1 >= start2:
start = start1
else:
start = start2
yield url[start: index+1]

def parse(url):
mylist = []
words = url_parser_generator(url)
for word in words:
mylist.append(word)
#print word
return mylist

def test():
urls = {
0: (True,"http://docs.python.org/dev/library/stdtypes.html?
highlight=partition#str.partition"),

1: (True,"/http:///docs.python.org/dev/library/stdtypes.html?
highlight=partition#str.partition"),
2: (True,"//http:///docs.python.org/dev/library/stdtypes.html?
highlight=partition#str.partition"),
3: (True,"///http:///docs.python.org/dev/library/stdtypes.html?
highlight=partition#str.partition"),

4: (True,"/http:///docs.python.org/dev/library/stdtypes.html?
highlight=partition#str.partition/"),
5: (True,"//http:///docs.python.org/dev/library/stdtypes.html?
highlight=partition#str.partition//"),
6: (True,"///http:///docs.python.org/dev/library/stdtypes.html?
highlight=partition#str.partition///"),

7: (True,"/#/http:///#docs.python..org/dev//library/
stdtypes./html??highlight=p=partition#str.partition///"),

8:
(True,"httpdocspythonorgdevlibrarystdtypeshtmlhighlightpartitionstrpartition"),
9:
(True,"httpdocs.python

Re: Dynamic list name from a string

2010-12-28 Thread DevPlayer

# dynamic_named_obj.py
# comp.lang.python
# 2010-12 Dec-28
# Topic: Dynamic list name from a string Options
# attempts to answer OP's question
# DevPlayer  - not a solution I'd use


# TO Original Poster OP:

# Start from the bottom OPTION, the one you requested.
# Work your way up and see how it gets simpler and
# simpler to do what you want. Dynamically named
# references start to look pointless.

# I hope I addressed your question and hopefully shown
# you the right direction and right reasons to avoid
# using dynamically made named references.
# But I could be wrong in your case.


import time

class DataStore(object):
"""A namespace similar to a module global scope."""

#def concatenate( one, two):
#"""Function to concatonate two lists."""
#return list( one + two)

# =
class Animal(object):
"""A base class for no real reason."""
def __init__(self, name):
self.name = name
self.date = time.clock()

# -
class Bear(Animal):
def __init__(self, name):
super(Bear, self).__init__(name)

class BearCub(Bear):
def __init__(self, name):
super(BearCub, self).__init__(name)

# -
class Doe(Animal):
def __init__(self, name):
super(Doe, self).__init__(name)

class Fawn(Doe):
def __init__(self, name):
super(Fawn, self).__init__(name)


# An alternate namespace instead of module global
ns = DataStore()

OPTION = "BETTER YET"

if OPTION == "BETTER YET":
# don't name your lists, just make the global_list and use it
# no intermediary lists needed really.

ns.Animals = [
# -- 1st set of classes
Bear("bob"),
Bear("bill"),
BearCub("obo"),
BearCub("Bill jr."),

# -- 2nd set of classes
Doe("DoeADear"),
Doe("AFemaleDear"),
Fawn("Ray"),
Fawn("Adropof"),
]

for animal in ns.Animals:
kind = animal.__class__.__name__
name = animal.name
date = animal.date
print kind, name, date

# make a sorted, by date, list of bears
old_bears = [obj for obj in ns.Animals if type(obj) is Bear]
old_bears.sort(None, key=lambda animal: animal.date)
ns.bears = old_bears

# or sort all animals by date
animals = [obj for obj in ns.Animals]
animals.sort(None, key=lambda animal: animal.date)

# then get just bears
bears = [obj for obj in animals if type(obj) is Bear]


elif OPTION == "BETTER":
# don't name your lists, trust in checking if objects have
attributes
# that matter

ns.Animals = {
# -- 1st set of classes
"bob": Bear("bob"),
"Bill": Bear("bill"),
"obo": BearCub("obo"),
"Bill jr.": BearCub("Bill jr."),

# -- 2nd set of classes
"DoeADear": Doe("DoeADear"),
"AFemaleDear": Doe("AFemaleDear"),
"Ray": Fawn("Ray"),
"Adropof": Fawn("Adropof"),
}

print ns.Animals['bob'].date

# make a sorted list of objects based on an attribute -like date
# sort by date for just bears
# http://wiki.python.org/moin/HowTo/Sorting
# look at Operator Module Functions too

# make a sorted, by date, list of bears
old_bears = [obj for obj in ns.Animals.values() if type(obj) is
Bear]
old_bears.sort(None, key=lambda animal: animal.date)
ns.bears = old_bears

# or sort all animals by date
animals = [obj for obj in ns.Animals.values()]
animals.sort(None, key=lambda animal: animal.date)

# then get just bears
bears = [obj for obj in animals if type(obj) is Bear]


elif OPTION == "SOSO1":
# alternative to dynamically named references (object attributes)
# Each item in global_dict is a sub dict

ns.Animals = {}
# -- 1st set of classes
ns.Animals[ Bear ] =  {"bob": Bear("bob"), "Bill": Bear("Bill")}
ns.Animals[ BearCub ] = {"obo": BearCub("obo"), "Bill jr.":
Bearcub("Bill jr.")}
# -- 2nd set of classes
ns.Animals[ Doe ] = {"DoeADear": Doe("DoeADear"), "AFemaleDear":
Doe("AFemaleDear")}
ns.Animals[ Fawn ] = {"Ray": Fawn("Ray"), "Adropof":
Fawn("Adropof")}

print ns.Animals[Bear]["bob"].date
print ns.Animals[BearCub]["Bill jr."].date

elif OPTION == "SOSO2":
# alternative to dynamically named references (object attributes)
# don't use names at all -
# Ea

Re: default argument in method

2010-12-30 Thread DevPlayer
There's some_object.some_method.func_defaults and
some_function.func_defaults both are a settable attribute. How to set
the methods func_defaults? You'd have to have code in
_getattribute__(yourmethod) if not __getattr__(yourmethod)

def __getattribute__(self, attr):
if attr == self.my_method:
# something like this, but i'm probably a little off
# you might need to use super or something to prevent
recursive __getattribute__ calls here
self.my_method.func_defaults = self.foo

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: default argument in method

2010-12-31 Thread DevPlayer
I agree with you Steven that the OP should avoid __getattribute__ and
the like for many a thing. I also agree with your last statement. I
try to answer the OP's question without much "You shouldn't do this's
and don't do that's". I trust them to make thier own decisions. I'd
say "A much better solution..." is the way I like to say it.

The last solution you offered I find I use more often now as I like to
set my function with default values for which I call set-and-forget
function parms/args where using None is what allows my functions to
know what is changing (or not).
# for example
def logger(parm1, parm2=None):
if not hasattr(myfunc.parm2_default):
if parm2:
myfunc.parm2_default = parm2
else:
myfunc.parm2_default = CONSOLE
if not parm2:
parmTwo = myfunc.parm2_default
else:
parmTwo = parm2

# do something
print(parmTwo)

log = logger(gui_frame, GUI)  # an inaccurate example
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple instances and wrong parental links

2011-01-03 Thread DevPlayer

Mere are my ramblings of a novice (bad) Hobbyst programmer.

You mentioned that your having a hard time coming up with a solution
to your complex problem. Complex means you are doing lots of different
things to different things all over the place where timing is an
issue.

First it seems you are trying to simplify your problem by creating a
generic class you might call Element which is held in an ElementList
class. Right?

Or is it you would like you to create a new class for each unique
element? If this is the case it would be because each unique element -
behaves- differently. Is this the case? Or do all XML elements
basically behave the same? If they behave the same you're confusing
your design. A class  represents a unique behavior. Remember instances
can have unique attributes like "code" or "title". But I'm digressing.

For example in your other discussion you posted at:
https://groups.google.com/forum/#!topic/comp.lang.python/K9PinAbuCJk/discussion
you say:

So, an element like:


Writers of the Future


Or is the element structure?:


"some value"


Or is it like this?


value


Or like this?


value
value
...


Or this, typical XML?


value
value
...

value
value
...




And is  nested or only one "sub" deep?

Ask yourself why do you need to have a different class for each unique
element type? Or in other words, why do you need a new class for each
XML tag pair?

If your elements are nested to some unknown depth, perhaps broaden
your idea of your ElementList into an ElementTree.

Take a look at the section "Basic Usage" midway down at url:
http://effbot.org/zone/element-index.htm


Or change you Market Class stucture(in your other discussion) to make
it more dimensional by adding a tag attribute which would
mark it as if it were a certain "class".

class ElementNode(objec):
def__init__(self, parent, elem)
self.parent = parent# another elementNode object or None
self.elem = elem # entire text block or just do offsets
(i.e. file line numbers)
self.tag = self.get_tag(elem)   # market  tag==class
self.token = self.get_token(self) # "code" or whatever if
variable
self.sub_elems= self.get_subs(elem) # recursive ElementNodes;
return a list or dict

self.root = self.get_root(parent)   # optional but handy
# I like to use the root as the XML source; sometimes an
XML file
self.next = None   # because I love double link lists
# probably useful for that ObjectListView wxPython widget


If in your case each Element does behave differently (ie has unique
methods) then perhaps you should be looking at some other solution.
Perhaps class factories or meta classes. I can't help you there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list 2 dict?

2011-01-03 Thread DevPlayer
An adaptation to Hrvoje Niksic's recipe

Use a dictionary comprehention instead of a list comprehension or
function call:

lyst = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b']

it = iter( lyst )
dyct = {i:it.next() for i in it}  # I'm using {} and not [] for those
with tiny fonts.

#print dyct
{8: 'b', 1: 2, 3: 4, 5: 6, 7: 'a'}

Of course check for an "even" number of elements to the original list
to avoid exceptions or dropping the last element on traps.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list 2 dict?

2011-01-04 Thread DevPlayer
or only convert the item when you need it leaving the lists as the
source

lyst = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b']

func = lambda alist, index: dict([(lyst[index*2],
lyst[(index*2)+1]),])

func(lyst, 0)
{1: 2}

func(lyst, 2)
{5: 6}

##
or as a function
def func(lyst, index):
return dict(((lyst[index], lyst[index+1]),))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python comparison matrix

2011-01-04 Thread DevPlayer
Awesome, thanks so much for you efforts and sharing.

Idea:
It would be great if we put this table into a python program where I
can run a script against this table and a Python source code module
(file) so that it would spit out a list of strings showing what python
versions work with said source code file.

python.exe  get_versions.py  myPythonSourceFile.py  -insertMetaInfo

Would prepend a text line to myPythonSourceFile.py in some format
like:
# __requires_python__ = ["Python 2.5-2.7"]
or
# __requires_python__ = ["Python", "2.5.x", "2.6.x", "2.7.x"]
or
# __requires_python__ = {"1.0.x":False, ..., "2.5.x":True,
"2.6.x":True, "2.7.x":True]
where key format is comparable agains on of the following:
sys.version, sys.version_info, sys.winver, sys.api_version,
sys.subversion


Idea:
Perhaps add the table you made a list of which libraries/packages are
included in the distro to the different releases.
Comparable against sys.builtin_module_names


Anyone ambisous enough to play with those idea, be my guest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matrix multiplication

2011-01-04 Thread DevPlayer
I would be very suprised if you achieve faster results threading this
problem. There's been much discussed on benefits or lack thereof to
threading in Python (or in general).

Threading is best used in situations where you are doing different
kinds of tasks. For example if you want to do your matrix
multiplication WHILE you were doing other things on your computer
where matrix multiplication was a background process chugging away
when you are not taxing the computer doing other stuff.

Threading adds efficiency when you would have lots of "blocking"
operations like reading in lots of big files from a comparable slow
hard drive (compared to how fast a CPU processes data) or waiting on
netword data (super slow compared to CPU processing).

When you are doing mass numeric processing, you want to minimize the
jumping from one function to another which uses overhead, recursion
adds a small amount of uneccessary overhead, you want to minimize the
need for the cpu to switch between threads or processes.

If you still feel the need to use threads for some reason, for numeric
processing I'd recommend using a "lighter" thread object, like a tiny
thread or green thread or a threadlet or whatever they are calling
them now.

Another thing to note is it seems you might be expecting threads to
run on different CPU cores expecting improvment. Be careful with this
assumption. This is not always true. It is up to the CPU and OS to
determine how threads are handled and perhaps the GIL to some extent.
Beaware that Python has a GIL (some distributions). Google it if you
don't know of it.

To encourage better use of multi-core cpus you might consider the
multiprocessing library included in Python 2.7 (I think) and above.

I'm assuming that speed is an issue because you where timing your
code. If you are doing actual serious number crunching there's lots of
advice on this. The python Numpy package as well as Stackless Python
(for microthreads or whatever thier called) comes to mind.

Another thought. Ask yourself if you need a large in-memory or live
set of processed numbers, in your case a fully and processed
multiplied matrix. Usually a large set of in-memory numbers is
something your going to use to simulate a model or to process and
crunch further.

Or is your actual usage going to be picking out a processed number
here or there from the matrix. If this is true look at iterators or
generators. Which would be a snapshot in time of your matrix
multiplication. I like to think of Python generators like integral
calculus  (definition at: http://en.wikipedia.org/wiki/Integral_calculus)
where the specific integral of a generator is often just 1.

I'm loving generators a lot. For example there are generator
accelorators which if you think it through means you can make
generator deccelorators, useful for doing interpolation between
elements of your matrix elements for example. I always forget if
generators are thread safe though.

Some indicators that generators could help: You're doing lots of for
loops with range().

Also it's been measured that list comprehensions are slightly faster
then while loops are a slightly faster then for loops. You can Google
to confirm, enter something like "python fast iteration".

Also if your numbers in your matix are actually not really numbers but
objects with numbers, __slots__ is used to for large sets of objects
(10s of millions at the very least) to minimize memory usage and
perhaps with speed, if used properly. Just mentioning. I'd stay away
from this though.

Some of my informatation may be inaccurate (and even completely wrong;
like I always get when a thread is best switched during a blocking
verse a non-blocking operation) but there are some things to consider.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matrix multiplication

2011-01-04 Thread DevPlayer
BTW
http://www.python.org/dev/peps/pep-0211/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Matrix multiplication

2011-01-04 Thread DevPlayer
See section titled: "'array' or 'matrix'? Which should I use?"
at
http://www.scipy.org/NumPy_for_Matlab_Users

BTW
http://www.python.org/dev/peps/pep-0211/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list 2 dict?

2011-01-04 Thread DevPlayer
Here is something totally the opposite of a nice one liner:

A hackish module with a bloated generator. Feel free to comment, so I
can learn the errors of my ways. Try not to be too mean though. Try to
think of the attached file as a demonstration of ideas instead of good
coding practices.

Don't be afraid to mention the good points too.

I tried to send an email with an attachment (to hide my shame) but I
kept getting email rejections.



# ===
# list2dict.py


# list item to dict item generator
# I forget if generators are thread safe

# devpla...@gmail.com
# 2011-01 Jan-03
#


def check_slice_bounds(list_len, start, stop, step):
"""Incomplete slice checker."""

# -
# force step to be non-None
if step is None:
step = 1

# -
# force step to be non-zero
if step == 0:
step = 1

# -
# in iterating over list to be converted to dict
# where list == [key, value, key, value] or in case swap==True
# list = [value, key, value, key]
# actual stepping is one for key, and plus one more for value
step = step * 2


# -
# force step to be smaller then size of list or -size of list

if step > 0:
if step > list_len:
step = list_len
else:
if step < -list_len:
step = -list_len

# -
# force step to be even for key, value iteration
if step % 2 == 1:
if step > 0:
step = step - 1
else:
step = step + 1

# -
# set start to default; depending on step direction (+x vs -x)

if start is None:
if step > 0:
start = 0
elif step == 0:
start = 0
stop = start
else:
start = -1

# -
# set stop to default; depending on step direction (+x vs -x)

if stop is None:
if step > 0:
stop = list_len-1
elif step == 0:
stop = start
else:
stop = -list_len


# -
# convert "start" to equivelent positive index

if start < 0:
if start < -list_len:
raise IndexError("IndexError: list index out of range:",
start)
else:
start = list_len + 1 + start


# -
# convert "stop" to equivelent positive index

if stop < 0:
if stop < -list_len:
raise IndexError("IndexError: list index out of range:",
stop)
else:
stop = list_len + 1 + stop

return (start, stop, step)



def gen(lyst, dyct=None, start=None, stop=None, step=None,
swap=False):
"""
lyst == list to convert to dict
dyct == external dict to be updated
start == starting index
stop
step == amount to move index by; usually +1 or -1 (times 2)
could be a float if clever enough.
if step equals zero it is converted to 1 to prevent
an infinite loop.
step will be reset to be an index inbounds of a list len()
swap 2nd item with the first item in the yield
"""

# -
# Force into bool True or False from equivelent values

if swap == True: swap = True
else: swap = False


# -
# check and set lyst slice/index bounds of start, stop, step

start, stop, step = check_slice_bounds(len(lyst), start, stop,
step)


# -
index = start
# -
while 0 <= index < len(lyst):
next = index + 1

if next == len(lyst):
value = None
else:
value = lyst[next]
key = lyst[index]


# -
# update external dict if given

if dyct is not None:
dyct[key] = value


# -
# effectively sway key with value == index, index+1 to index
+1, index

if swap:
newindex = yield (value,key)
else:
newindex = yield (key,value)


# -
# process "newindex" variable if caller does a
# gen.send(some_list_index) externally

if newindex is None:
index = index + (step)
elif 0 <= newindex < len(lyst):
# fix this to allow for negative index for negative
stepping
# but don't forget to convert it to its corrosponding
# positive index
index = newindex
else:
# fix this so it doesn't error on index 0
#raise IndexError("Index is out of range:", index)
pass


# -
# Ungracefully coerce end of iteration
if step > 0:
if i

Re: list 2 dict?

2011-01-04 Thread DevPlayer
The shorter version:
This doesn't need any x = iter(list) line. perhaps more useful if you
have a bunch of lists to be converted through out your code.

def dictit(lyst):
i = 0
while i < len(lyst):
yield lyst[i], lyst[i+1]
i = i + 2

l = [1, 2, 3, 4, 5, 6, 7, 'a', 8, 'b']

{d[0]:d[1] for d in dictit(l)} 3 again a dict comprehension

func = lambda l: {k[0]:k[1] for k in dictit(l)}
d = func(l)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which coding style is better? public API or private method inside class definition

2011-01-12 Thread DevPlayer
On Jan 4, 11:46 pm, Inyeol  wrote:
> Which coding style do you prefer? I'm more toward public API way,
> since it requires less code change if I refactor private data
> structure later.
> Plz give pros and cons of these.

Great question. It gets at the heart of Python style.
It's a tricky question and can be answered so many ways. I'm not a pro-
programmer anymore so here's my hobbyst's take on it.

First, API is application programming interface. Follow me for a sec.
It's the interface that your programmers use to use your "package".
But WHICH programmers? For large apps like game developers or large
all encompassing apps for companys there are many different types of
programmers. That helps determine how heavy to lean towards private
verse public interfaces.

Funny thing is I end up using the private interfaces as much as the
public interaces for certain things. For example when coding in
wxPython I rarely use any private apis (ie. __dict__ or other "special
or magic named" attributes). But when coding outside of wxPython I'm
all over the place defining new classes with special named attributes
like __new__ or __metaclass__, and lots and lots of other magic named
methods and private attributes.

So one way to decide whether to be coding towards more public verse
private is where in your project you are. Building infrastructure and
framework verse building "application" and end-user interfaces.

Or similarly the interface TO the API interface is private (as far as
Python considers things private that is). The interface to all others
to use your "package" is public.

And if your code is not a package for other coders, then what is the
sense in having private anythings?

One thing that mungles one's mind into thinking it matters is your IDE
tools. When you run your scripts as an end user, who cares that
there's tons of objects cluttering your namespace - I'm implying that
using private API in that case is somewhat a waste. When in your IDE
coding like PyCrust and you type in the interface something like wx.
you'll get a popup of "attributes" and you think "ah, these attributes
and methods I can use". But in use of that program, there's no sense
in hidding stuff with underscored names.

On the otherhand. I like to think my namespaces are simple, clean,
uncluttered. There's less "What the heck is that thing" while looking
at dir() and debugging.

Personally I do not like the underscore. My hands don't like the
keystroke pattern. And the underscore is butt ugly to me. Ugly does
not equal "less readable". I find underscore easier to read then camel
case/Hungarian Notation (wx and .NET has a lot of that). Although name
mangling and camel case usage are different things, from a visual (of
source code), to me they are the same. Also when there is name
mangling, there is often an unmangled version of it in some usage
somewhere in your code.

Another thought. Although private interfaces are not intended to be
SEEN, you code your private interfaces (i.e. attributes and methods,
functions, etc) to denote themselves as private when you LOOK at them
by using underscores. I'd rather have my source code just color
private attributes differently. However editors are not at that level
yet (meaning they'd have to interpret the code to know what's
private).

Lastly. Shouldn't it be better to use APIs based on the docs instead
of analyzing the code for intended public interfaces verse private
ones?

Although not explicidly listing pros and cons to public verse private
APIs I hope I spark some useful insight.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested structures question

2011-01-12 Thread DevPlayer
looping = True
while looping:
guess = int(raw_input("Take a guess: "))
tries += 1
if guess > the_number:
print "Lower..."
elif guess < the_number:
print "Higher..."
else:
print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"
break

if  tries >= 7:
print "Wow you suck! It should only take at most 7 tries!"
looping = False


# Alternatively while learing while looping use the continue statement

looping = True
while looping:
guess = int(raw_input("Take a guess: "))
tries += 1

if guess > the_number:
print "Lower..."
elif guess < the_number:
print "Higher..."
else:
print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"
break

if  tries < 7:
continue

print "Wow you suck! It should only take at most 7 tries!"
looping = False




# In a while loop I recommend to NOT end loops using the
# conditional test of == but instead use >, <, >= or <= or !=.
# In a complex while loop the exit condition may be skipped
# by mistake and you'll loop forever.

# In while loops I get less bugs by putting the incrementor as
# the last statement in the while block;
# this helps follow precedence like range(7) is - zero to 6
# as well as index 0 in a list is the first item. However
# while index: where index == 0 will exit the loop before
# it even starts as 0 == False (0 is not False but equals False)

# Use the while loop for looping an undetermined number of
# iterations or conditional iterations.
# Use for loops for an explicid number of iterations.

for tries in range(7):
guess = int(raw_input("Take a guess: "))
if guess > the_number:
print "Lower..."
elif guess < the_number:
print "Higher..."
else:
print "You guessed it! The number was", the_number
print "And it only took you", tries, "tries!\n"
break
if  tries >= 7:
print "Wow you suck! It should only take at most 7 tries!"

# I'm guessing the chapter's test is to see if you remember the for
loop.

# start using print() to get into a good habit for Python 3.0+


# I haven't seen the book but often one part of while that is
# left off in tutorials is the "else" statement.
while condition:
"block"
else:
"block"

# you can use else for when the condition never happens.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to populate all possible hierarchical clusterings from a set of elements?

2011-01-13 Thread DevPlayer
lst = [1, 2, 3, 4, 5]

def maketup(lst):
cur_item = lst[-1]
lst = lst[:-1]
if len(lst):
return maketup(lst), cur_item
else:
return cur_item

print maketup(lst)

1, 2), 3), 4), 5)

But I'm confused as to what you mean by :
> Among them, I want to pair up terminals until there is only one left
> at the end.

One what? one pair?, one terminal meaning one number?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to populate all possible hierarchical clusterings from a set of elements?

2011-01-13 Thread DevPlayer

def maketup(lst):

if len(lst) == 1:
return lst[0]

elif len(lst) == 2:
return (lst[0],lst[1])

elif len(lst) > 2:
return ( (maketup(lst[:-2]), lst[-2]), lst[-1])

maketup(lst)

1, 2), 3), 4), 5)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to populate all possible hierarchical clusterings from a set of elements?

2011-01-13 Thread DevPlayer
tuple([ (tuple(lst[x-1:x+1]) if len(tuple(lst[x-1:x+1]))==2 else
lst[x-1]) for x in lst[::2]])

((1, 2), (3, 4), 5)


# or
x = ((tuple(lst[x-1:x+1]) if len(tuple(lst[x-1:x+1]))==2 else
lst[x-1]) for x in lst[::2])
x.next()
(1, 2)
x.next()
(3, 4)
x.next()
5
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to populate all possible hierarchical clusterings from a set of elements?

2011-01-13 Thread DevPlayer
Ah. out of my depth.
-- 
http://mail.python.org/mailman/listinfo/python-list