Timeit

2009-02-18 Thread cokofreedom
I've having an annoying problem at the moment. I'm writing code for
the travelling salesmen problem and comparing different techniques.
But I've having a problem using timeit.

I have a file called "testplatform.py" that contains 4 class:
Test() - which is called first to create the cities/routes to be
shared between the other classes
AutoClone() - which uses the variables from Test() (normally test =
Test())
Randomisation() - Ditto
BruteForce() - Ditto

if __name__ == '__main__':
test = Test(5, 1000, 100, 100, 100, 14)
example1 = AutoClone(test.citynames, test.cityroutes, test.seed,
test.generations, test.mutate)
example2 = Randomisation(test.citynames, test.cityroutes,
test.seed,
test.generations)
example3 = BruteForce(test.citynames, test.cityroutes)

I am really stuck trying to work out how to pass variables to timeit
to allow me to run any of the examples...

Any help would be great!
--
http://mail.python.org/mailman/listinfo/python-list


Re: def X(l=[]): weirdness. Python bug ?

2008-08-22 Thread cokofreedom
On Aug 22, 11:13 am, Bart van Deenen
<[EMAIL PROTECTED]> wrote:
> Hi all.
>
> I've stumbled onto a python behavior that I don't understand at all.
>
> Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
>
> # function
> def X(l=[]):
>    l.append(1)
>    print l
>
> # first call of X
> X()
> [1]
>
> #second call of X
> X()
> [1, 1]
>
> Where does the list parameter 'l' live between the two successive calls of 
> X().
> Why is it not recreated with an empty list?
> Is this correct behavior or is it a Python bug?
> Does anyone have any pointers to the language documentation where this 
> behavior is described?
>
> Thanks all
>
> Bart van Deenen

http://docs.python.org/ref/function.html

"Default parameter values are evaluated when the function definition
is executed."

Depending on your use the common way to handle this is to do

def x(lst = None):
if lst is None:
pass # lst has not been set to anything
else:
pass # lst has been set to something

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


Re: Weird expression result

2008-08-18 Thread cokofreedom
On Aug 18, 5:57 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> I'm probably missing something obvious but I can't put my finger on
> it:
>
> >>> (3 in [3]) == True
>
> True
>
> >>> 3 in ([3] == True)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: argument of type 'bool' is not iterable
>
> >>> 3 in [3] == True
>
> False
>
> How/why does the last one evaluate to False ?
>
> George

> >>> (3 in [3]) == True

The list holds an integer value of 3, you check if 3 is in that list,
that is true, you then check it your answer is true...

> >>> 3 in ([3] == True)

True and False are keywords now and do not correspond the way you
think. [3] == True or [3] == False will both answer False.

Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = list()
>>> a.append(3)
>>> 3 in a
True
>>> if a:
... print "yay"
...
yay
>>> if a == True:
... print "yay"
... else:
... print "nay"
...
nay

> >>> 3 in [3] == True

http://docs.python.org/ref[3/summary.html

>>> 3 in [3] == True
False
>>> 3 in [3] == False
False

However I come a bit stuck myself, since this should just tell you
that you cannot do a membership test on 3 being in a bool...but it
doesn't...It should be doing the [3] == True, returning false then
trying to see if 3 is in false...
--
http://mail.python.org/mailman/listinfo/python-list


Re: benchmark

2008-08-11 Thread cokofreedom
On Aug 11, 10:55 am, [EMAIL PROTECTED] wrote:
> On Aug 10, 10:10 pm, Kris Kennaway <[EMAIL PROTECTED]> wrote:
>
> > jlist wrote:
> > > I think what makes more sense is to compare the code one most
> > > typically writes. In my case, I always use range() and never use psyco.
> > > But I guess for most of my work with Python performance hasn't been
> > > a issue. I haven't got to write any large systems with Python yet, where
> > > performance starts to matter.
>
> > Hopefully when you do you will improve your programming practices to not
> > make poor choices - there are few excuses for not using xrange ;)
>
> > Kris
>
> And can you shed some light on how that relates with one of the zens
> of python ?
>
> There should be one-- and preferably only one --obvious way to do it.
>
> Dhananjay

And that is xrange, but if you need a list range is better :P
--
http://mail.python.org/mailman/listinfo/python-list


Re: benchmark

2008-08-08 Thread cokofreedom
On Aug 8, 9:08 am, alex23 <[EMAIL PROTECTED]> wrote:
> On Aug 8, 2:49 pm, Dhananjay <[EMAIL PROTECTED]> wrote:
>
> > Is it that a question of time and effort,
> > or is there something that doesn't make it appropriate to python ?
>
> I don't think I've ever seen anyone who has raised concerns about the
> speed of python actually offer to contribute to resolving it, so I'm
> guessing it's the former.

Contribute to resolve it? Part of me just wants to say that to "speed"
up python would be such a huge undertaking, the outcome would alter
the language beyond what people liked. Another part thinks, why speed
it up, it is pretty fast presently, and I've rarely seen real-world
applications that need that 80/20 rule applied heavily.

Benchmarks for showing what languages are good at is fine, but in
general most conform to a standard range of speed. I cannot find the
article but there was a good piece about how it takes most programmers
the same time to program in any language. Reading through the code is
another matter, I think Python is faster than most in that respect.

I'd look to increase the worst-case scenario's of Python before trying
to speed up everything. Hell the tim_sort is pretty damn fast.
--
http://mail.python.org/mailman/listinfo/python-list


Re: benchmark

2008-08-07 Thread cokofreedom
>
> Honestly, performance benchmarks seem to be the dick size comparison
> of programming languages.
>

But in the honour of dick size:

http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=all
http://shootout.alioth.debian.org/debian/benchmark.php?test=all&lang=all
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-25 Thread cokofreedom
>
> By that logic, C++ is not OO. By that logic, Ruby is not OO. By that
> logic, I know of only one OO language: Java :)
>
> The fact that a language doesn't force you to do object-oriented
> programming doesn't mean that it's not object-oriented. In other
> words, your words are nonsense.
>

No, what it means is that it might support OO but doesn't have to, it
isn't the only way to code.

Supporting and Being OO are very different.

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


Re: Attack a sacred Python Cow

2008-07-24 Thread cokofreedom
>
> My words aren't as clear as they should be. I mean that Python lets
> *you* do something without documenting, or rather stating to use a
> better term, that your intention is the non-obvious one. I'm not
> saying that Python itself lacks documentation for its own behaviour;
> I'm saying it should force you to make your intentions clear and
> visible to someone reading your code when you want to do something non-
> obvious.
>

I take it you are relating to the need for less comments within the
code as the idea is the Python code itself is readable? Or are you
saying that when someone does a clever trick it should be documented
better? I'm a little confused as what you mean by no-documenting? I
always add doc-strings to modules I will be using heavily as well as a
README with them. But that isn't different from programming in other
languages and using comments.

(Do you mean something like JavaDoc?)
--
http://mail.python.org/mailman/listinfo/python-list


Re: New to Python, familiar with Perl - Seeking info sources

2008-07-24 Thread cokofreedom
On Jul 24, 3:53 pm, Brett Ritter <[EMAIL PROTECTED]> wrote:
> After many years happily coding Perl, I'm looking to expand my
> horizons. [no flames please, I'm pretty aware of Perl's strengths and
> weaknesses and I'm just here to learn more, not to enter religious
> debates].
>
> I've gone through some of the online tutorials and I'll be browsing
> the reference before starting the "code a lot" phase.
>
> My question is: What are the best sources to learn best practices or
> get the answers to questions?  Are there any good sources to tell me
> what Perl habits are good/bad in the Python paradigm?  What about
> common packages that will change my life?  (I do a lot of web work,
> but also a lot of DB reporting)  I'm also working as a Java developer
> primarily, so I'm glad to see that Jython has been resurrected, but
> I'm focusing on vanilla Python for the moment.
>
> As examples: PerlMonks has been my info source.  The Perl Best
> Practices and Higher Order Perl books have been my tutors into better
> coding practices.  CPAN has my life easy, giving me access to the DBI,
> Class::DBI (and its successors), HTML::FillInForm,
> Data::FormValidator, CGI::Application, and Text::CSV::Simple modules
> that are staples of my coding.   The (occasionally complete) Perl
> Advent calendars have proven to be a good source to learn about
> helpful modules that I might not otherwise stumble across.
>
> (I've encountered Django, but I'm getting my fill of "frameworks" from
> Java for the moment, so I'm looking for lightweight pieces at the
> moment)
>
> My (admittedly brief) searches here and on google didn't lead me to
> any particular spots of concentrated Python info, and most of the Perl/
> Python stuff is either a smug attack by one camp on the other or a
> rant about the behavior of an obscure feature between the two.
>
> Any recommendations?  Thanks in advance.

Best start is a quick read of DiveIntoPython that provides a nice
account of how to work with Python, and relates to coming from a
programming background. I also keep this List on my bookmarks, as well
as the python library (http://docs.python.org//lib/).

The ActiveState Python Cookbook (http://aspn.activestate.com/ASPN/
Python/Cookbook/) generally has a lot of useful code snippets worth
using.

Zen of Python (http://www.python.org/dev/peps/pep-0020/) shows the
idea of Python and (http://www.python.org/dev/peps/pep-0008/) is the
Style Guidelines for Python code.

I haven't worked with the web and Python much yet so maybe someone
else can help you there. Welcome :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Attack a sacred Python Cow

2008-07-24 Thread cokofreedom
>
> Please understand that I'm not arguing about this particular design
> choice (and FWIW, I'd mostly agree on the point that having a != b
> different from not (a == b) is actually a wart). I'm just correcting
> your statement about the behaviour of __eq__ / __ne__ not being
> documented, which is obviously false.
>
> (snip)

What was the reasoning behind having both __eq__ / __ne__ anyway? To
fit in with the equality comparisons?  I do agree this one seems like
a wart, but not a serious one. I'd say it would make more sense for
the interpreter to provide a warning on classes that define one and
not that other, at least if set to a certain level, similar to -3 for
depreciated.

(Or does this exist? I think a "wart" catching level that outputs
potential warts and issues would be a useful addition!)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Written in C?

2008-07-22 Thread cokofreedom
On Jul 22, 5:59 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
> > On 2008-07-22, Larry Bates <[EMAIL PROTECTED]> wrote:
>
> >> You talk about "writing it in assembly language for each MPU
> >> chip".  Actually it is even better than that.  We now have
> >> these modern inventions, called compilers that do that type of
> >> work for us.  They translate high level instructions, not
> >> into assembler but into machine language.
>
> > Actually, all of the compilers I'm familiar with (gcc and a
> > handful of cross compilers for various microprocessors)
> > translate from high-level languages (e.g. C, C++) into
> > assembly, which is then assembled into relocatable object
> > files, which are then linked/loaded to produce machine
> > language.
>
> I just learned something I did not know.  I was under the impression that they
> translated directly to machine code without ever actually generating Assembler
> text files.  Seems like a waste to generate the text and turn around run that
> through the assembler, but what do I know.  I guess that way the compiler can
> have pluggable assembler back-ends.
>
> -Larry

I also I have just learned something new! Troll threads are useful.
Yay.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is the role of python2.6 and C++?

2008-07-21 Thread cokofreedom
On Jul 21, 10:17 am, "甜瓜" <[EMAIL PROTECTED]> wrote:
> Howdy,
>
> I'm confused about the motivation of releasing python2.6 and python3.0
> at the *same* time. IMO, 2.6 should be compatible with 2.5 while 3.0
> is new style python. Currenly, most python projects works fine in 2.5.
> When 3.0 becomes final release, those projects will be gradually moved
> to 3.0. But even without the intermediate version 2.6, project
> transformation with be smooth enough, and then 2.5, 2.6 will be
> replaced by 3.0. I will not spend any time on studying 2.6. So why
> does python development team put many efforts on 2.6? What is the role
> of 2.6?
>
> Best regards,
>
> --
> ShenLei

2.6 is meant to be a continuation of the 2.x line of Python, to
support a gradual move of larger projects over to the Python 3.x
series. The idea is that as Python 3.x will cause some major and minor
changes to the basics of Python as we currently know it, trying to
move everyone straight away will be problematic.

Therefore the point is there will be a 2.7, 2.8 and so forth until
there is almost no difference between
the 2.x and 3.x at which time most users will have moved to the 3.x
series and the 2.x can be discontinued.

I will program larger projects in 2.5 for a while and then perhaps
look to move it to 2.6 and 2.7, I won't touch the 3.x series until it
is the common choice, much as a lot of people still program in 2.3/4.
--
http://mail.python.org/mailman/listinfo/python-list

Re: Beginner Question : Iterators and zip

2008-07-14 Thread cokofreedom
>
> zip(*vec_list) will zip together all entries in vec_list
> Do be aware that zip stops on the shortest iterable.  So if vec[1] is
> shorter than vec[0] and matches otherwise, your output line will be
> truncated.  Or if vec[1] is longer and vec[0] matches as far as it goes,
> there will be no signal either.
>

Do note that from Python 3.0 there is another form of zip that will
read until all lists are exhausted, with the other being filled up
with a settable default value. Very useful!
--
http://mail.python.org/mailman/listinfo/python-list


Re: You, spare time and SyntaxError

2008-07-09 Thread cokofreedom
>
> just... great !-)
>

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


You, spare time and SyntaxError

2008-07-09 Thread cokofreedom
def ine(you):
yourself = "what?"
go = list("something"), list("anything")
be = "something"
please = be, yourself
yourself = "great"
for good in yourself:
if you is good:
good in you
please.add(more, good)
else:
def inition(lacks, clarity):
if clarity not in you:
please.remove(everything and go)
for bad in yourself:
list(bad) if bad else (ignore, yourself)
try:
(to, escape, your, fate, but)
except (Exception), son:
if bad in (you, son):
(you is bad, son), so
finally:
if bad in you:
lie, cheat, steal, be, bad
else:
print you, "is", yourself
you is good and yourself is not bad
please, go

ine("Everyone")
--
http://mail.python.org/mailman/listinfo/python-list


Re: a simple 'for' question

2008-07-09 Thread cokofreedom
On Jul 9, 2:08 am, Ben Keshet <[EMAIL PROTECTED]> wrote:
> Hi fans,
>
> I want to use a 'for' iteration to manipulate files in a set of folders,
> something like:
>
> folders= ['1A28','1A6W','56Y7']
> for x in folders:
> print x # print the current folder
> f = open('my/path/way/x/my_file.txt', 'r')
> ...
>
> where 'x' in the pathway should iterate over '1A28','1A6W','56Y7'.  How
> should I identify 'x' in the pathway line as the same x that is
> iterating over 'folders'?
>
> I am getting the following error:
>
> Traceback (most recent call last):
>   File
> "C:\Python25\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
> exec codeObject in __main__.__dict__
>   File "C:\Linux\Dock_method_validation\myscripts\test_for.py", line 5,
> in 
> f = open('c:/Linux/Dock_method_validation/x/receptor.mol2', 'r')
> IOError: [Errno 2] No such file or directory:
> 'c:/Linux/Dock_method_validation/x/receptor.mol2'
>
> I tired several variations: %x, 'x', "x", etc. all gave me similar errors.
>
> Thanks for your help,
> BK

>>> folders = ["a", "b", "c"]
>>> for item in folders:
print item
file = open("my/path/way/" + item + "/my_file.txt", "r")
--
http://mail.python.org/mailman/listinfo/python-list


Re: Impossible to change methods with special names of instances of new-style classes?

2008-07-09 Thread cokofreedom
>
> My question is: did something about the way the special method names are
> implemented change for new-style classes?
>

>>> class old:
pass

>>> class new(object):
pass

>>> testone = old()
>>> testone.__call__ = lambda : 33
>>> testone()
33
>>> testtwo = new()
>>> testtwo.__call__ = lambda : 33
>>> testtwo()

Traceback (most recent call last):
  File "", line 1, in 
testtwo()
TypeError: 'new' object is not callable
>>> old.__call__

Traceback (most recent call last):
  File "", line 1, in 
old.__call__
AttributeError: class old has no attribute '__call__'
>>> new.__call__

>>> testone.__call__
 at 0x00C35EB0>
>>> testtwo.__call__
 at 0x00C35B70>
>>> dir(testtwo)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
'__weakref__']
>>> dir(testone)
['__call__', '__doc__', '__module__']
>>> dir(new)
['__class__', '__delattr__', '__dict__', '__doc__',
'__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
'__weakref__']
>>> dir(old)
['__doc__', '__module__']

I don't see __call__ in either class structures, but for new style
classes it is a wrapper and for old it is nothing. Not sure if that
helps, but this is rather over my head.
--
http://mail.python.org/mailman/listinfo/python-list


Re: yo...

2008-07-07 Thread cokofreedom
On Jul 7, 3:47 pm, Bruno Desthuilliers  wrote:
> [EMAIL PROTECTED] a écrit :
> (snip)
>
> > However welcome to Python and this Google
> > Group.
>
> 
> This is *not* a google group. This is the usenet newsgroup
> comp.lang.python, made accessible TTW by google.
> 

Touche ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: yo...

2008-07-07 Thread cokofreedom
On Jul 7, 11:55 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> On 2008-07-07, abhishek <[EMAIL PROTECTED]> wrote:
>
> > hey guys...me nu 2 python yo...help me...by da way...jus joined
> > inthanks
>
> Ask a specific question and you may get an answer.
>
> If you want an answer from me, it helps *a lot* if you write full english
> sentences (starting with a capital letter and ending with a single '.') rather
> than the short-hand you seem to favor. (It costs me a lot of effort to
> decipher).
>
> Sincerely,
> Albert

Considering I speak English as a first language, it is still rather
difficult to understand you. However welcome to Python and this Google
Group. If you have questions in the future, feel free to ask them.
Though you might want to use less Text-style lingo as many of the
users here are not first-language English speakers.
--
http://mail.python.org/mailman/listinfo/python-list


Installing paramiko and pycrypto

2008-07-01 Thread cokofreedom
I am really stuck presently, trying to install these on my Windows XP.
I have downloaded easy_install and it is now in Python25\Scripts but
none of the commands I have read in either program folder have worked
to install them.

I was hoping someone could give me a step by step guide to installing
these so I can use paramiko to perform SSH. Or at least point me in
the right direction...

Thanks

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


Re: what is meaning of "@" in pyhon program.

2008-06-30 Thread cokofreedom
On Jun 28, 8:41 pm, Thierry <[EMAIL PROTECTED]> wrote:
> > ie:
> > @if os.exists(foo):
> >etc
> >etc
>
> > and
>
> > @for blah:
> >etc
> >etc
>
> This sounds more like PHP code, where a @ prefixing a function means
> that even if there are errors or warnings, you don't want to see them.

Could also by Doxygen, doesn't it use something similar to show
keywords in documents?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is recursion so slow?

2008-06-30 Thread cokofreedom
In case anyone is interested...

# Retrieved from: 
http://en.literateprograms.org/Fibonacci_numbers_(Python)?oldid=10746

# Recursion with memoization
memo = {0:0, 1:1}
def fib(n):
if not n in memo:
memo[n] = fib(n-1) + fib(n-2)
return memo[n]

# Quick exact computation of large individual Fibonacci numbers

def powLF(n):
if n == 1:return (1, 1)
L, F = powLF(n/2)
L, F = (L**2 + 5*F**2) >> 1, L*F
if n & 1:
return ((L + 5*F)>>1, (L + F) >>1)
else:
return (L, F)

def fib(n):
return powLF(n)[1]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Making code more efficient and effective

2008-06-26 Thread cokofreedom
On Jun 26, 5:42 pm, [EMAIL PROTECTED] wrote:
> Cédric Lucantis:
>
> > PAT = re.compile('^[ ]*(public|protected|private)[ ]+([a-zA-Z0-9_]+)
> > [ ]+([a-zA-Z0-9_]+)[ ]+\((.*)\).*$')
> > ...
> > It might be hard to read but will avoid a lot of obscure parsing code.
>
> You can use the VERBOSE mode, to add comments and split that RE into
> some lines.
>
> I think the RE module of Python 3.0 can be modified in some way to
> encourage people to write more readable REs, but I don't know how.
> Maybe the VERBOSE can be on by default...
>
> Bye,
> bearophile

Thank you to everyone that replied in the thread and privately, been
looking into the different techniques. Presently found the RE to be
readable once I put it into VERBOSE format. I had looked it at earlier
but struck a dead wall, till Cédric gave such clear code!

I've been doing Java code the last few weeks and it is hard to jump
between them sometimes, Java has to be so organised and checked over
and over, I forget Python doesn't need such defensive programming.

I currently have it finding functions, constructors and classes, and
looking for them within the code, which is exactly what I was hoping
for! It also reads a lot clearer, which was what I was aiming for. So
thanks to everyone that helped!
--
http://mail.python.org/mailman/listinfo/python-list


Making code more efficient and effective

2008-06-26 Thread cokofreedom
I've written up a little piece of code that isn't that foolproof to
scan through a file (java presently) to find functions and then look
for them throughout the document and output the name of the function,
followed by how many times it appears and the lines it appears on.

What I was looking for was ways to improve, simplfy and beautify the
code. More to aid my learning of Python than produce a perfect way to
scan for this (netbeans was annoying me...which is why I did this)

Anyway, the source code:

from __future__ import with_statement

functions = dict()
func_words = ("private", "public", "protected")
ignore_class = " class "

def get_func_name(line):
for word in func_words:
if word in line: break
else: return None
# set it to ignore the func_word and the space after
line = line[len(word) + 1:]
index = line.find("(")
if index != -1:
func_name = ""
for letter in reversed(line[:index]):
if letter == " ": break
func_name += letter
return ''.join(reversed(func_name))
else: return None

with open(r"C:\example.java", "r") as test_file:
for number, line in enumerate(test_file):
line = line.strip()
if line.startswith(func_words) and line.find(ignore_class ) ==
-1:
func_name = get_func_name(line);
if func_name is not None:
functions.setdefault(func_name, []).append(number)

test_file.seek(0)
for number, line in enumerate(test_file):
for key in functions.iterkeys():
if line.find(key) != -1:
functions[key].append(number)

print "\n".join("Function: %s, found on %d line(s); these being
%s"
% (k, len(v), v) for k, v in
functions.iteritems())
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDE on the level of Eclipse or DEVc++?

2008-06-25 Thread cokofreedom
On Jun 25, 12:38 pm, Jorge Godoy <[EMAIL PROTECTED]> wrote:
> Ben Finney wrote:
> > Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
>
> >> If you're into clickodroms, you may want to have a look at Eric too.
> >> As far as i'm concerned, I still wait for something that would be
> >> worth dropping emacs + python-mode + ecb.
>
> > I'm having the most success with this combination, yes. Though ecb is
> > rather non-Emacs-like in its configuration, and seems to strongly
> > expect to be run in graphical mode, it is still very powerful.
>
> Heh...  I'm another one that keeps trying new things but comes back to Emacs 
> all the time.
>
> Eclipse is too heavy, NetBeans has a poor support, Eric is too "mousy"...
>
> --
> Jorge Godoy  <[EMAIL PROTECTED]>

How is emacs on a windows platform?
--
http://mail.python.org/mailman/listinfo/python-list


Re: python -regular expression - list element

2008-06-25 Thread cokofreedom
On Jun 25, 11:55 am, antar2 <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am a beginner in Python and am not able to use a list element for
> regular expression, substitutions.
>
> list1 = [ 'a', 'o' ]
> list2 = ['star',  'day', 'work', 'hello']
>
> Suppose that I want to substitute the vowels from list2 that are in
> list1, into for example 'u'.
> In my substitution, I should use the elements in list1 as a variable.
> I thought about:
>
> for x in list1:
>re.compile(x)
> for y in list2:
>re.compile(y)
> if x in y:
> z = re.sub(x, 'u', y)
> but this does not work

I think you misunderstand the point of re.compile, it is for compiling
a regular expression.

>>> import re
>>> list1 = [ 'a', 'o' ]
>>> list2 = ['star',  'day', 'work', 'hello']
>>> for x in list1:
for y in list2:
if x in y:
print re.sub(x, 'u', y)
stur
duy
wurk
hellu
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary representation of an integer

2008-06-24 Thread cokofreedom
And:

# return as a string
def itob_string(integer, count = 8):
return "".join(str((integer >> i) & 1) for i in range(count - 1,
-1, -1))

# return as an iterator (i.e [0, 0, 0, 0, 1, 0, 1, 0])
def itob_list(integer, count = 8):
return [(integer >> i) & 1 for i in range(count - 1, -1, -1)]

# return as a generator
def itob_generator(integer, count = 8):
return ((integer >> i) & 1 for i in range(count - 1, -1, -1))
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary representation of an integer

2008-06-24 Thread cokofreedom
On Jun 24, 10:38 am, Mark Dickinson <[EMAIL PROTECTED]> wrote:
> On Jun 24, 9:03 am, eliben <[EMAIL PROTECTED]> wrote:
>
> > What would be the quickest way to do this ? I think that for dec2bin
> > conversion, using hex() and then looping with a hex->bin lookup table
> > would be probably much faster than the general baseconvert from the
> > recipe.
>
> I suspect you're right, but it would be easy to find out:  just
> code up the hex->bin method and use the timeit module to do some
> timings.  Don't forget to strip the trailing 'L' from hex(n) if n
> is a long.
>
> If you're prepared to wait for Python 2.6, or work with the beta
> version, then the conversion is already there:
>
> Macintosh-3:trunk dickinsm$ ./python.exe
> Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> bin(13)
>
> '0b1101'
>
> Interestingly, unlike hex and oct, bin doesn't add a trailing
> 'L' for longs:
>
> >>> bin(13L)
>
> '0b1101'
>
> I wonder whether this is a bug...
>
> Mark

Strange in 2.6, but I know at least in 3.0 that all integers are C
Long's now, so the L is no longer required.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread cokofreedom
On Jun 24, 10:36 am, "Corey G." <[EMAIL PROTECTED]> wrote:
> What I meant, in terms of dealing with accurate or non-accurate rumors
> is with speed, yes.  There are plenty of comparisons where Perl is
> 4-15x faster then Python for 'some' operations regarding regular
> expressions, etc.
>
> For me personally, this means absolutely nothing because if I spend
> 50x more time comprehending spaghetti, obfuscated Perl code it's
> irrelevant.  The main concern (my concern) is whether or not Perl 6 is
> more like Java with pre-compiled byte code (did I say that right) and
> whether or not individuals without the ability to see past the surface
> will begin to migrate towards Perl 6 for its seemingly faster
> capabilities.
>
> With Perl 6 taking 10+ years, if/when it actually gets released, will
> it be technically ahead of Python 3000?  Is Parrot worth the extra
> wait the Perl 6 project is enduring?  My own answer would be a
> resounding no, but I am curious as to what others think. :)
>
> -Thanks!
>

>From a quick read of the Parrot Wiki page it would appear they hope to
one day allow the compilation of BOTH Perl 6 and Python, which could
be interesting.

Towards the speed, 
http://shootout.alioth.debian.org/debian/benchmark.php?test=all&lang=all
puts Python ahead of perl, and Python Psyco ahead of Parrot PIR.
Though I haven't looked at each benchmark comparison so it is hard to
tell.

Towards what Perl 6 offers, the Wiki on it seems to indicate it will
be a clean up of Perl 5 as well as adding of many features from other
languages. It seems like Lary has gone for the TAKE IT ALL approach
which could work out well in providing practically any format for
creating Perl scripts. Or it could cause huge confusion as users ask
for help and received a 1001 different approaches...

Towards it being more advanced than Python 3k, time will tell. Both
are still active and getting updated. So while I personally will stay
with Python, others may move, or use both.
--
http://mail.python.org/mailman/listinfo/python-list


Re: String question

2008-06-24 Thread cokofreedom
On Jun 24, 5:38 am, "Mark Tolonen" <[EMAIL PROTECTED]> wrote:
> "Andreu" <[EMAIL PROTECTED]> wrote in messagenews:[EMAIL PROTECTED]
> > Yes, ... don't ask me why, but in fact  v1,v2,v3 = str1.split()
> > does not seem to work. My original problem was I forgot about
> > the parenthesis as Tim point out. So I ended up converting to a
> > list as in:  v = str1.split() and accessing the elements using
> > v[0] v[1] ect...it is working now. Thanks.
>
> > Andreu.
>
> v1,v2,v3 = str1.split() will only work if there are exactly three things in
> str1.
>
> >>> s = 'this is a test'
> >>> v1,v2,v3 = s.split()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: too many values to unpack>>> v1,v2,v3 = s.split(' ',2)# limit 
> to two splits maximum
> >>> v1
> 'this'
> >>> v2
> 'is'
> >>> v3
>
> 'a test'
>
> -Mark

In Python 3k I believe you can put a * next to one of the variables to
hold multiple arguments. That'll be aidful!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3000 vs Perl 6

2008-06-24 Thread cokofreedom
On Jun 24, 8:20 am, "Corey G." <[EMAIL PROTECTED]> wrote:
> If Perl 6 ever does get on its feet and get released, how does it
> compare to Python 3000?  Is Perl 6 more like Java now with Parrot?  I
> just want to make sure that Python is staying competitive.
>
> If this is the wrong mailing list, just let me know.  Thanks!

Do you mean in terms of speed (parrot is a JIT?). I believe Python 3k
will (when out of beta) will have a speed similar to what it has
currently in 2.5, possibly with speed ups in some locations. But
competitive-wise I think the point is Python 3k tries to remove warts
from the Python Language to make it even more friendly to readers and
writers alike. In that way it should/will stay competitive.

However towards overall usage, the general advice is to stay with the
2.x series for now, trying to ensure your code style is moving towards
the Py3k style, and then make the jump to the 3.x series when it is
finialised.

Another point, is Perl 6 ever going to get released :P
--
http://mail.python.org/mailman/listinfo/python-list


Re: String question

2008-06-23 Thread cokofreedom
On Jun 23, 4:45 pm, Andreu <[EMAIL PROTECTED]> wrote:
> I want to split a sentence and assign each word to a variable.
> In Ruby I can do it as:
>
> v1,v2,v3,v4,v5 = str1.split
>
> Which will be the Python equivalent ? Thanks.
>
> Andrew.

Well a straight copy would be...

>>> example = "Hello, how are you"
>>> v1, v2, v3, v4 = example.split()
>>> print v1, v2, v3, v4
Hello, how are you
>>> print v1
Hello,

However I would make a list of it.

>>> v_list = example.split()
>>> print v_list
['Hello,', 'how', 'are', 'you']
>>> for word in v_list:
print word
Hello,
how
are
you

That seems to me to be the more pythonic way to do it, since it is
dynamic.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple Python class questions

2008-06-20 Thread cokofreedom
>
> Yes I was wondering about that, but I wasn't clear about when 'body'
> code (ie not contained within a def block) in the module might run
> under Python. So it seemed to be safer to place the import statement
> inside the 'constructor' to get the earliest warning of non-visibility
> of pyserial. But you seem to be implying that the body code will run
> when the class is instantiated - have I understood that right? It
> surely doesn't run when the module containing the class is imported
> into the main module - does it?? It would certainly make life easier
> to place the import in the body of the module.

Without insulting your intelligence I would advise looking at a few
python tutorials, not so much for the programming technique, but
rather how to think pythonic. A good one for using when coming from a
previous programming language is
Dive Into Python. http://www.diveintopython.org/

It does not deal with Serial specifically, but shows good examples of
practises in Python. Might be of benefit to you, and is very easy and
quick to read. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict order

2008-06-18 Thread cokofreedom
On Jun 18, 4:45 pm, Kirk Strauser <[EMAIL PROTECTED]> wrote:
> At 2008-06-18T10:32:48Z, [EMAIL PROTECTED] writes:
> > # untested 2.5
> > for keys in dict_one.items():
> >   if keys in dict_two:
> > if dict_one[keys] != dict_two[keys]:
> >   # values are different
> >   else:
> > # key is not present
>
> That fails if there is an item in dict_two that's not in dict_one.
> --
> Kirk Strauser
> The Day Companies

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


Re: dict order

2008-06-18 Thread cokofreedom
On Jun 18, 12:32 pm, [EMAIL PROTECTED] wrote:
> On Jun 18, 11:22 am, Robert Bossy <[EMAIL PROTECTED]> wrote:
>
> > Hi,
>
> > I wish to know how two dict objects are compared. By browsing the
> > archives I gathered that the number of items are first compared, but if
> > the two dict objects have the same number of items, then the comparison
> > algorithm was not mentioned.
>
> > Note that I'm not trying to rely on this order. I'm building a
> > domain-specific language where there's a data structure similar to
> > python dict and I need an source of inspiration for implementing
> > comparisons.
>
> > Thanks
> > RB
>
> I'm a little confused as to what you want. Are you asking whether two
> dictionary objects have the same keys AND values, or just the Keys?
>
> As dictionaries are unordered the best technique is to go through one
> dictionary and take out a key, then see if that key exists in the
> other dictionary, and if so do they share the same values.
>
> # untested 2.5
> for keys in dict_one.items():
>   if keys in dict_two:
> if dict_one[keys] != dict_two[keys]:
>   # values are different
>   else:
> # key is not present
>
> This probably isn't the most efficient way, but can quickly find
> differences...

Whoops

for keys, values in dict_one.items():
  if keys in dict_two:
if values == dict_two[keys]:

should also work...
--
http://mail.python.org/mailman/listinfo/python-list


Re: dict order

2008-06-18 Thread cokofreedom
On Jun 18, 11:22 am, Robert Bossy <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I wish to know how two dict objects are compared. By browsing the
> archives I gathered that the number of items are first compared, but if
> the two dict objects have the same number of items, then the comparison
> algorithm was not mentioned.
>
> Note that I'm not trying to rely on this order. I'm building a
> domain-specific language where there's a data structure similar to
> python dict and I need an source of inspiration for implementing
> comparisons.
>
> Thanks
> RB

I'm a little confused as to what you want. Are you asking whether two
dictionary objects have the same keys AND values, or just the Keys?

As dictionaries are unordered the best technique is to go through one
dictionary and take out a key, then see if that key exists in the
other dictionary, and if so do they share the same values.

# untested 2.5
for keys in dict_one.items():
  if keys in dict_two:
if dict_one[keys] != dict_two[keys]:
  # values are different
  else:
# key is not present

This probably isn't the most efficient way, but can quickly find
differences...
--
http://mail.python.org/mailman/listinfo/python-list


Re: boolian logic

2008-06-13 Thread cokofreedom
>
> if var not in (A, B, C):
>do_something()
>

And this is why I love python.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does python not have a mechanism for data hiding?

2008-06-11 Thread cokofreedom
On Jun 11, 8:11 am, "Russ P." <[EMAIL PROTECTED]> wrote:
> On Jun 10, 11:58 am, Jonathan Gardner
>
> > Who cares what the type of an object is? Only the machine. Being able
> > to tell, in advance, what the type of a variable is is a premature
> > optimization. Tools like psyco prove that computers (really,
> > programmers) nowadays are smart enough to figure things out the right
> > way without any hints from the developer. Static typing is no longer
> > necessary in today's world.
>
> You couldn't be more wrong. Even Guido recognizes the potential value
> of static typing, which is why he is easing it into Python as on
> optional feature. He recognizes, correctly, that it can detect errors
> earlier and facilitate more efficient execution. But there's another,
> more significant potential benefit for safety-critical and mission-
> critical applications: static typing facilitates advanced static
> analysis of software.

Can you provide me with any example of Guide wanting static typing to
be
optional? I haven't. Any why is it you keep going so abstract in this
discussion.

>
> You may be right to an extent for small or medium-sized non-critical
> projects, but you are certainly not right in general. I read something
> a while back about the flight software for the Boeing 777. I think it
> was something like 3,000,000 lines of Ada code. Normally, for a
> project of that magnitude the final integration would be expected to
> take something like three months. However, the precise interface specs
> and encapsulation methods in Ada allowed the integration to be
> completed in just three days.
>

Well, that isn't just because they used encapsulation, the likelihood
is well thoughtout planning, constant system testing (that DOES
require accessing of those more private methods to ensure there are no
problems throughout), and re-testing. Again since I'm not sure how
much I trust you and your statistics anymore, have you a link to
anything discussing this?

>
> I realize that Python is not designed for such large projects, but
> don't you think certain general principles can be learned anyway?
> Perhaps the benefits of interface specs and encapsulation are not as
> obvious for smaller projects, but certainly they are not zero.

Python is designed to be an efficient high level language for writing
clear readable code at any level. Considering the amount of use it
gets from Google, and the scope and size of many of their projects, I
find it foolish to say it is not designed for large projects. However
I do not myself have an example of a large python project, because I
don't program python at work.

I think the issue here is your want to have python perform exactly
like OO built languages such as Java, but it isn't Java, and that, is
a good thing.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does python not have a mechanism for data hiding?

2008-06-06 Thread cokofreedom
Someone asked about Java;

class FieldTest {
public String publicString = "Foobar";
private String privateString = "Hello, World!";
}

import java.lang.reflect.Field;

public class Test4 {
  public static void main(String args[]) {
final Field fields[] =
FieldTest.class.getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
  System.out.println("Field: " + fields[i]);
}
  }
}

OUTPUT 
Field: public java.lang.String FieldTest.publicString
Field: private java.lang.String FieldTest.privateString

And to edit it;

import java.lang.reflect.Field;

public class Test7 {
  public static void main(String args[])
throws Exception {
final Field fields[] =
FieldTest.class.getDeclaredFields();
for (int i = 0; i < fields.length; ++i) {
  if ("privateString".equals(fields[i].getName())) {
FieldTest fieldTest = new FieldTest();
Field f = fields[i];
f.setAccessible(true);
System.out.println(f.get(fieldTest));
f.set(fieldTest, "Modified Field");
System.out.println(f.get(fieldTest));
break;
  }
}
  }
}

OUTPUT 
Hello, World!
Modified Field

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


Re: Newb question: underscore

2008-06-05 Thread cokofreedom
> > My question is: Why would anyone decide to obfuscate something as easy
> > to read as Python???
>
> They didn't decide to obfuscate; they decided to follow a
> strongly-expected convention for the name of that function by existing
> users of the 'gettext' functionality, in contexts that predate the
> appearance of that functionality in Python.
>

Well _ can also mean the previous output statement that wasn't null,
so it has OTHER uses...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why does python not have a mechanism for data hiding?

2008-06-04 Thread cokofreedom
>
> But the leading underscore doesn't tell you whether it is your own
> private date, which you can use a you see fit, or those of someone
> else, which you have to be very carefull with.
>
> --
> Antoon Pardon

Well how is that different from public accessor and mutators of
private variables?
--
http://mail.python.org/mailman/listinfo/python-list


Re: defaultdict.fromkeys returns a surprising defaultdict

2008-06-04 Thread cokofreedom
>
> No need.  The patch would be rejected.  It would break existing code
> that uses default.fromkeys() as designed and documented.
>

Perhaps that could be useful, so that future questions or posts on the
matter could instantly be directed to the rejected patch?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple of coordinates

2008-05-29 Thread cokofreedom
a = 1, 2
b = 3, 4, 5
c = 6, 7, 8, 9
coord = list()

for i, j, k in zip(a, b, c):
coord.append((i, j, k))

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


Re: php vs python

2008-05-28 Thread cokofreedom
On May 28, 1:42 pm, Michael Fesser <[EMAIL PROTECTED]> wrote:
> .oO(Ivan Illarionov)
>
> >No. Language does matter.
>
> And the weather.
>
> If you know how to program, you can write good code in any language if
> you're familiar enough with it. Many people write good code in PHP, and
> many write total crap in C/C++. It's almost never about the language,
> but about the programmer.
>
> Micha

I'd like to see someone coming from an OO programming background write
good Haskell, Pure Functional Programming code even with a high level
of OO experience. Language matters.
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
On May 21, 4:57 pm, "inhahe" <[EMAIL PROTECTED]> wrote:
> one of the few things i miss from C is being able to use assignment in
> expressions.   that's the only thing, really.
> also there's no switch/case, you have to use a dictionary of functions
> instead, although i rarely need that, usually i just use elif.

One thing I hate from C is the assignment in expressions...Forcing
myself to write
0 == Something
rather than
Something == 0
just to make sure I was mistakenly assigning values in statements is
annoying, it ruins the ease of reading.

I kind of agree with the select:case, but I think a key issue is how
to implement it. Elif is reasonable for now.

Diez, true I guess, but then we haven't seen what these expressions
are, and why there has to be three.
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
On May 21, 4:09 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
> >> And wastes time. regular expressions can become expensive to match -
> >> doing it twice might be hurtful.
>
> >> Diez
>
> > match = (my_re1.match(line) or my_re2.match(line)) or
> > my_re3.match(line)
>
> How do you know *which* of the three has matched then?
>
> Diez

Depends if the OP wants to know that...
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
>
> And wastes time. regular expressions can become expensive to match - doing
> it twice might be hurtful.
>
> Diez

match = (my_re1.match(line) or my_re2.match(line)) or
my_re3.match(line)

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


Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
On May 21, 3:12 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On May 21, 1:47 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
>
> > Although that solution is pretty, it is not the canonical solution
> > because it doesn't cover the important case of "if" bodies needing to
> > access common variables in the enclosing scope.  (This will be easier
> > in Python 3 with 'nonlocal', though.)  The snippet posted by Diez is
> > IMHO closer to a canonical solution to this FAQ.
>
> Hello everybody,
>
> thanks for the various answers. I'm actually pretty puzzled because I
> expected to see some obvious solution that I just hadn't found before.
> In general I find Python more elegant and syntactically richer than C
> (that's where I come from), so I didn't expect the solutions to be a
> lot more verbose and/or ugly (no offense) than the original idea which
> would have worked if Python's assignment statement would double as
> expression, as in C.
>
> Thanks again,
> robert
>
> PS: Since I'm testing only three REs, and I only need the match
> results from one of them, I just re-evaluate that one.

Is it really a lot to change to have it

if my_re1.match(line):
  match = my_re1.match(line)
elseif my_re2.match(line):
  match = my_re2.match(line)
elseif my_re3.match(line):
  match = my_re3.match(line)

?

That reads clearly to me...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Misuse of list comprehensions?

2008-05-21 Thread cokofreedom
''.join(seen.add(c) or c for c in s if c not in seen)

>From what I can understand...

.join will be a String of unique 'c' values.

'seen.add(c) or c' will always point to the second statement 'c'
because seen.add(c) returns None.

'if c not in seen' will ensure 'c' being added to both the .join and
seen is unique.

That is really clever! I like it :) (but does require a bit of
knowledge about .add return None and the affect that has on the ..
or .. statement)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is using range() in for loops really Pythonic?

2008-05-14 Thread cokofreedom
On May 14, 8:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 13 May 2008 10:20:41 -0700, John Nagle wrote:
> > Matt Nordhoff wrote:
>
> >> Well, you should use "xrange(10)" instead of "range(10)".
>
> >CPython really is naive.  That sort of thing should be a
> > compile-time optimization.
>
> It's not naive, it can't know at compile time what object is bound to the
> name `xrange` at runtime.
>
> Ciao,
> Marc 'BlackJack' Rintsch

I think he meant you should just use xrange over range at all times.
--
http://mail.python.org/mailman/listinfo/python-list


Re: anagram finder / dict mapping question

2008-05-09 Thread cokofreedom
>>> key = ''.join(sorted(word))

I tend to strip and lower the word as well, otherwise "Hello" and
"hello" do not compare...depends on what you want though!
Plus you might get a lot of "word\n" as keys...

My technique is the this way

def anagram_finder(words):
anagrams = {}
for word in words:
word = word.strip()
key = ''.join(sorted(word.lower()))
anagrams.setdefault(key, []).append(word)
return anagrams
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie to python --- why should i learn !

2008-05-08 Thread cokofreedom
C#

using System;
namespace HelloWorld
{
Class HelloWorld
{
static void Main(String[] args)
{
Console.WriteLine("Hello World");
}
}
}
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is the purpose of ptyhon in Windows

2008-05-07 Thread cokofreedom
On May 7, 4:08 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> hi All,
> I have no idea why I need to learn a new scripting language,
> nothing much to the sytnax,
> I need to understand what could be the prupose of another scripting
> language
>
> Cna you please help me with this,
> Is there a possibilty to work on bigger projects with Python

Answer, reasons to learn another scripting language;
It provides different techniques to problems,
It is eaiser and clearer to write with a strong community to aid
developers,
Problems can be scaled,
There are a lot of high scale Python projects.

Hope that helped.
--
http://mail.python.org/mailman/listinfo/python-list


Re: comparing dictionaries

2008-05-07 Thread cokofreedom
On May 7, 4:08 pm, brad <[EMAIL PROTECTED]> wrote:
> I want to compare two dicts that should have identical info just in a
> different data structure. The first dict's contents look like this. It
> is authoritative... I know for sure it has the correct key value pairs:
>
> {'001' : '01'}
>
> The second dict's contents are like this with a tuple instead of a
> string for the key:
>
> {('This is one', '001'): '01'}
>
> Pseudo Code:
> for key, value in first_dict.iteritems():
># How do I do the following line?
>if key not in second_dict or if it is, but has has the wrong value,
> then let me know

Well

for k, v in first_dict.items():
  if k not in second_dict or k in second_dict and k[v] !=
second_dict[k]:
let you know?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Reversing a dict?

2008-05-06 Thread cokofreedom
On May 6, 5:20 pm, [EMAIL PROTECTED] wrote:
> Hi - further to my earlier query regarding partial matches (which with
> all your replies enabled me to advance my understanding, thanks), I
> now need to reverse a dict.
>
> I know how to reverse a list (with the reverse method - very handy),
> but it doesn't seem possible to reverse a dict.
>
> I suspect what I need to do is somehow go from:
>
> thelist=list(thedict)
> thelist.reverse()
> thedict=dict(thelist)
>
> Does anyone know how to convert / or reverse a dict?
>
> thanks
>
> kb.

Issue 1: A dictionary is not ordered so cannot be reversed, as is.

Saw something like this though:

info = {"PHP":"17th May",
   "Perl":"15th June",
   "Java":"7th June",
   "Python":"26th May",
   "Tcl":"12th July",
   "MySQL":"24th May"}

topics = info.keys()
topics.sort()
topics.reverse()

for topic in topics:
   print "Next",topic,"course starts",info[topic]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Am I missing something with Python not having interfaces?

2008-05-06 Thread cokofreedom
> I would imagine this is why I haven't found any schools teaching
> Python in their basic programming classes too.  On the dynamic typing,
> isn't that the same sort of thing that lots of scripting languages
> do?  VBScript doesn't require you to define your variables, but I
> don't really want to use it for anything (used to use it a lot in
> Classic ASP.)  I believe everyone that Python is great, but some of it
> doesn't make sense to me as to why.  Thanks.

Well, school-wise we got taught VB because it was easy for the non-
programmers. At university I learnt Java, C++, Haskell, Fortran and
Python. My favourite is obviously Python.

So here is my terrible (likely wrong) view of Python:

Python is a dynamic programming language, different to static ones
like Java or C++, and variables-wise, well you do have types, but it
is up to the interpreter to understand what to do with them. From my
understanding "variables" as you call them can be the following;
Integer 1, String "Hello", Tuple (), List [], Dictionary {} and a
higher level function (you can assign functions as varaible names,
that personally is amazing!).

Python is built to be easy to read, I think Guido (BDFL) said
something about 10% of the time code is written, 90% it is read, or
something to that affect. The point is that anyone who knows Python to
even a small degree should be able to pick up someone elses code and
given a small time understand the idea of it, even with any comments.

That is very powerful and key to the idea of Python, and my main love
for it. The issue I get from University is this idea that OOP is the
way to program, it is one of the ways, not the be all and end all. I
almost died when I got shown Haskell because nothing made sense, but
after using Python and returning, I understood more of the logic
because I had used the same techniques (in a more readable format) in
Python before.

A common bug people suffer from when trying a new language is doing
things how they would in their previous language of choice. Python is
not Java, or C++ or anything else other than Python. So read a few
tutorials on Python, see what people say it is good at and use it for
that purpose.  I think it is an advantage to know how to do things
with different languages in different formats, but it is important to
know when to use one method over another. Personally DiveIntoPython
was a great guide for me as to the uses and benefits of Python, at a
basic level. Try googling it and reading the (free) articles and
tutorials online.

And welcome to Python, the grass is greener :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: computing with characters

2008-05-06 Thread cokofreedom
On May 6, 12:22 pm, Boris Borcic <[EMAIL PROTECTED]> wrote:
> Duncan Booth wrote:
> > Torsten Bronger <[EMAIL PROTECTED]> wrote:
>
> >> The biggest ugliness though is ",".join().  No idea why this should
> >> be better than join(list, separator=" ").  Besides, ",".join(u"x")
> >> yields an unicode object.  This is confusing (but will probably go
> >> away with Python 3).
>
> > It is only ugly because you aren't used to seeing method calls on string
> > literals.
>
> An obviously independent cause of uglyness is the inconsistency of eg
> ','.split() and ','.join()
>
> Cheers, BB

I tend to do ", ".join("%s" % e for e in item)

Is there any difference between this and str()?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question - probably FAQ (but not exactly answered by regular FAQ)

2008-05-06 Thread cokofreedom
2.5 seems the defacto standard now for a new user, NB: probably not
the standard for the common business productions. However are you on
Windows or *nix? *nix may ship a certain version, so for ease of use
it would be best to use that.

Personally I use 2.5 because it is a complete version, and the latest
fully released giving me a lot of features to play with. But as
previously put if you are starting out, you are very unlikely to need
a huge amount of those features for a while.

So my opinion is used 2.5, it is released with no huge new feature
updates to come and won't break on random errors. (Unless you find a
real new one!). Also new is cool...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code/test ratio wrt static vs dynamic typing [was: Re: Python Success stories]

2008-04-30 Thread cokofreedom
>
> A rather off-topic and perhaps naive question, but isn't a 1:4
> production/test ratio a bit too much ? Is there a guesstimate of what
> percentage of this test code tests for things that you would get for
> free in a statically typed language ? I'm just curious whether this
> argument against dynamic typing - that you end up doing the job of a
> static compiler in test code - holds in practice.
>
> George

To me it seems like more of an argument for a (more) concise Test
Framework for Python, or at least a fully fledge IDE beyond pyDev.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Issue with regular expressions

2008-04-29 Thread cokofreedom
| #  Double Quote Text 
|"# match a double quote
|(#  - Two Possiblities:
|\\.  # match two backslashes followed by anything
(include newline)
||# OR
|[^"] # do not match a single quote
|)*   #  - from zero to many
|"# finally match a double quote
|
||#  OR 
|
| #  Single Quote Text 
|'# match a single quote
|(#  - Two Possiblities:
|\\.  # match two backslashes followed by anything
(include newline)
||# OR
|[^'] # do not match a single quote
|)*   #  - from zero to many
|'# finally match a single quote
|""", DOTALL|VERBOSE)

Used this before (minus those | at the beginning) to find double
quotes and single quotes in a file (there is more to this that looks
for C++ and C style quotes but that isn't needed here), perhaps you
can take it another step to not do changes to these matches?

r(\\.|[^"])*"|'(\\.|[^'])*'""", DOTALL)

is it in a single line :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Success stories

2008-04-23 Thread cokofreedom
Civilisation  4 uses Python everywhere and is the main tool used by
Modders of the game.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding a number to nearest even

2008-04-11 Thread cokofreedom
On Apr 11, 1:19 pm, [EMAIL PROTECTED] wrote:
> couldn't you just do.
>
> #untested
> new_round(n):
>   answer = round(n)
>   # is answer now odd
>   if answer % 2:
> return answer - 1
>   else:
> return answer

Whoops, this also affects odd numbers...

Will try and find a GOOD solution later...

Strange request though, why do you need it that way, because 2.5 is
CLOSER to 3 than to 2...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rounding a number to nearest even

2008-04-11 Thread cokofreedom
couldn't you just do.

#untested
new_round(n):
  answer = round(n)
  # is answer now odd
  if answer % 2:
return answer - 1
  else:
return answer
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find documentation about methods etc. for iterators

2008-04-10 Thread cokofreedom
>
> This for me is Python's chief selling point:  dir()dir() and
> help().  Python's two selling points are dir(), help(), and very
> readable code.  Python's *three* selling points are dir(),
> help(), very readable code, and an almost fanatical devotion to
> the BFDL.  Amongst Python's selling points are such elements as
> dir(),  help()...I'll come in again. 
>

This brought a smile to my face :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about Exceptions?

2008-04-10 Thread cokofreedom
> the erase() id alwys need if u wanna abort whilst u wrote something.

But if it is meant to only evaluate once you've pressed the enter key
(I take it?) you shouldn't need that. And if you are to abort while
evaluating it will not do that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about Exceptions?

2008-04-10 Thread cokofreedom
> def Calc():
> global nbr
> try:
> print eval(nbr)
> #a = Label(mygui, text=eval(nbr))
> #a.place(relx=0.4, rely=0.1, anchor=CENTER)
> except:
> print "Not computable"
> nbr = ""
>
> def Erase():
> global nbr
> nbr = ""

Seems to me you could be better off passing a parameter and a return
statement of None (or your parameter cleaned) for those functions,
which should work. Given an input, Eval it and then return None. That
way you wouldn't need the Erase...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: questions about Exceptions?

2008-04-10 Thread cokofreedom
In general you should only catch the exceptions you want to catch,
therefore avoiding the issue of catching "unexpected" ones, for
instances the programming unexpectandly closing.

Well, exception handling is expensive (when it catches one) so it
really is up to you. If you are using eval and know it might "EOF"
then you should probably look to handle that. The main IF statement
style I can think of (checking the end of the string) wouldn't be much
of an improvement.

Currently I would be very worried about seeing that code as it breaks
a number of "conventions". However it depends on the importance of the
code to wherever or not you should change this. (Global variable, the
use of Eval, the CATCH ALL except and the setting of a global variable
at the end.)

I've seen a good few (simple and advanced) calculator examples using
python on the NET, it might be worth looking at some to see their
style of coding a calculator to help your own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PROBLEMS WITH PYTHON IN SOME VARIABLE,FUNCTIONS,ETC.

2008-04-09 Thread cokofreedom
Umm, Mesopotamia is an area geographically located between the Tigris
and Euphrates rivers, Bangalore isn't anywhere near that. And most of
that is presently under American control.

If you don't want to give out your code then try explaining it better.
What is the input, what is the output, how are you currently
processing. Describe these and people might be willing to aid more. Or
complain more about how unhelpful people are. Suits us.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PROBLEMS WITH PYTHON IN SOME VARIABLE,FUNCTIONS,ETC.

2008-04-08 Thread cokofreedom
>
> I have a car. I have turned the ignition key but it fails to start.
> Please tell me what is wrong with it.
>

The engine is missing! Am I close?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PROBLEMS WITH PYTHON IN SOME VARIABLE,FUNCTIONS,ETC.

2008-04-08 Thread cokofreedom
'I have designed a program with more than 500 if elif else'

This was your first mistake...

(ii) x3=x1.find(x2)

returns an integer corresponding to the start position in x1 where it
found x2, otherwise it will return -1.

(i) ...

what kind of vague numbers? It should just give you an integer
response...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: First Python project - comments welcome!

2008-04-07 Thread cokofreedom
Just a random check. Is __gsignals__ a builtin type? Else it would
probably be better not to include the postfix underscores. Though I
might be wrong here. Otherwise seems pretty good and well organised. I
hate it when people go comment mad, but you've kept them to the places
where an explanation is required. Good job :=)
-- 
http://mail.python.org/mailman/listinfo/python-list


Looking for Advanced Python Tutorials

2008-04-04 Thread cokofreedom
I was wondering if anyone knew of some online (free if possible)
advanced tutorials, especially ones that provides tasks and ideas for
small projects. The issue for myself is I want to improve my python
programming level, and my ability to program in general, but come up
blank thinking of a possible task or project to undertake. So with
that in mind I thought I'd ask the community if they knew of sites or
books to read up on and use as a starting block. Of course project
ideas would be great as well!

Thanks for any help you can provide.

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


who said python can't be obsfucated!?

2008-04-02 Thread cokofreedom
def s(c):return[]if c==[]else s([_ for _ in c[1:]if _=c[0]])

Anyone else got some wonders...?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Nested try...except

2008-04-02 Thread cokofreedom
On Apr 2, 3:06 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> I found the following code on the net -
>
> http://mail-archives.apache.org/mod_mbox/httpd-python-cvs/200509.mbox/[EMAIL 
> PROTECTED]
>
> def count(self):
> -db = sqlite.connect(self.filename,
> isolation_level=ISOLATION_LEVEL)
> -try:
> -try:
> -cur = db.cursor()
> -cur.execute("select count(*) from sessions")
> -return cur.fetchone()[0]
> -finally:
> -cur.close()
> -finally:
> -db.close()
>
> I don't understand though why the second try is not after the line cur
> = db.cursor(). Can anyone explain for me why?
>
> /Barry.

Better question is why is there a try with no except...

Better yet, WHY is there two TRY statements when there could quite
happily be only one...

Towards what you are asking, I GUESS...because the author hoped to
handle the cases where cur failed to get assigned...but then
his .close method of it would likely not work anyway...I mean...does
this even work...YUCK
-- 
http://mail.python.org/mailman/listinfo/python-list


globals() using For Loop against Generator

2008-03-18 Thread cokofreedom
if __name__ == '__main__':

print "Globals (For Loop):"
try:
for i in globals():
print "\t%s" % i
except RuntimeError:
print "Only some globals() printed\n"
else:
print "All globals() printed\n"

print "Globals (Generator):"
try:
print "\n".join("\t%s" % i for i in globals())
except RuntimeError:
print "Only some globals() printed\n"
else:
print "All globals() printed\n"

>>>
>>> Globals (For Loop):
>>> __builtins__
>>> Only some globals() printed
>>>
>>> Globals (Generator):
>>> __builtins__
>>> __name__
>>> __file__
>>> i
>>> __doc__
>>> All globals() printed
>>>

Why is it with a generator I get everything out but with a for loop I
don't? I know that globals is not read-only but I would of expected
the same behaviour from both...

Any thoughts?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Immutable and Mutable Types

2008-03-17 Thread cokofreedom
> >>> a = 1
> >>> b = 1
> >>> a is b
> True
> >>> id(a)
> 10901000
> >>> id(b)
> 10901000

Isn't this because integers up to a certain range are held in a single
memory location, thus why they are the same?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List mutation method gotcha - How well known?

2008-03-13 Thread cokofreedom
Still, I suppose this is a gotcha for a lot of people, just follow the
good advice Paul said;
"By Python convention, methods that mutate the object return None, and
also stuff that returns None doesn't generate output at the
interactive prompt."

And you should survive most.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List mutation method gotcha - How well known?

2008-03-13 Thread cokofreedom
On Mar 13, 8:36 am, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am surprised that it took me so long to bloody my nose on this one.
>
> It must be well known - and I would like to find out how well known.
>
> So here is a CLOSED BOOK multiple choice question - no RTFM,
> no playing at the interactive prompt:
>
> Given the following three lines of code at the interactive prompt:
>
> foo = [1,2,3,4]
> x = foo.append(5)
> print x
>
> What will be the output (choose one):
>
> 1)  [1,2,3,4]
> 2)  [1,2,3,4,5]
> 3)  That famous picture of Albert Einstein sticking out his tongue
> 4)  Nothing - no output
> 5)  None of the above
>
> I undertake to summarise answers posted to complete this "survey".
>
> - Hendrik

None is the likely answer as .append is an inplace change and will
return None...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a file with $SIZE

2008-03-12 Thread cokofreedom
On Mar 12, 2:44 pm, Robert Bossy <[EMAIL PROTECTED]> wrote:
> Matt Nordhoff wrote:
> > Robert Bossy wrote:
>
> >> k.i.n.g. wrote:
>
> >>> I think I am not clear with my question, I am sorry. Here goes the
> >>> exact requirement.
>
> >>> We use dd command in Linux to create a file with of required size. In
> >>> similar way, on windows I would like to use python to take the size of
> >>> the file( 50MB, 1GB ) as input from user and create a uncompressed
> >>> file of the size given by the user.
>
> >>> ex: If user input is 50M, script should create 50Mb of blank or empty
> >>> file
>
> >> def make_blank_file(path, size):
> >> f = open(path, 'w')
> >> f.seek(size - 1)
> >> f.write('\0')
> >> f.close()
>
> >> I'm not sure the f.seek() trick will work on all platforms, so you can:
>
> >> def make_blank_file(path, size):
> >> f = open(path, 'w')
> >> f.write('\0' * size)
> >> f.close()
>
> > I point out that a 1 GB string is probably not a good idea.
>
> > def make_blank_file(path, size):
> > chunksize = 10485760 # 10 MB
> > chunk = '\0' * chunksize
> > left = size
> > fh = open(path, 'wb')
> > while left > chunksize:
> > fh.write(chunk)
> > left -= chunksize
> > if left > 0:
> > fh.write('\0' * left)
> > fh.close()
>
> Indeed! Maybe the best choice for chunksize would be the file's buffer
> size... I won't search the doc how to get the file's buffer size because
> I'm too cool to use that function and prefer the seek() option since
> it's lighning fast regardless the size of the file and it takes near to
> zero memory.
>
> Cheers,
> RB

But what platforms does it work on / not work on?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-10 Thread cokofreedom
The trick in the case of when you do not want to guess, or the choices
grow too much, is to ask the user to tell you in what format they want
it and format according to their wishes.

Neatly avoids too much guessing and isn't much extra to add.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How about adding rational fraction to Python?

2008-02-26 Thread cokofreedom
What is it with people and double++ posting...

If you have a lot to say, say it together and take the time to slow
down, re-read it and not just fly it out, line by line, by line, by
line...

To answer only the following:

> That's creepy for people that are new to programming and doesn't know
> how CPUs work and are used to general mathematics. That means most
> people. As programming language are now more accessible to regular
> people without specialized Computer Science degree, it is a just
> natural trend that computer arithmetic must be done in an expectable
> manner as seen by those general population not by people who holds a
> CS degree.

Couldn't disagree with you more, the fact they don't specialise in
Computer Science shouldn't be a reason to follow their "expected
outcomes", they should be informed of the standard CS approach. I'm
all for punishing people for making "well I thought it would always do
the following..." thought process. The quicker they learn certain
methods and expectations are wrong the quicker they get used to the
proper thought patterns.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie in python

2008-02-21 Thread cokofreedom
> >Can someone help me to get in the right track, and get a good move?
>
> http://wiki.python.org/moin/BeginnersGuide

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


Re: Double underscores -- ugly?

2008-02-21 Thread cokofreedom
On Feb 21, 3:31 am, [EMAIL PROTECTED] wrote:
> On Feb 19, 8:20 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > On Feb 19, 10:26 am, Wildemar Wildenburger
> > > <[EMAIL PROTECTED]> wrote:
> > >> Jason wrote:
> > >>> Hmm.  I must be the only person who doesn't think the double
> > >>> underscores are ugly.
> > >> Nope. I like them too. :)
>
> > >> Frankly, I think it's just a matter of adaption. I too found it rather
> > >> "ugly" in the beginning, but with anything, I've gotten used to it. (And
> > >> I wholeheartedly support your "looks like underlined / is unintrusive
> > >> like whitespace" argument.)
>
> > >> /W
>
> > > My editor actually renders them as miniature chess pieces.  The
> > > bartender said she runs a pre-execution step, that searches and
> > > replaces a double-colon with the underscores.
>
> > If you're taking programming advice from a bartender your postings
> > suddenly start to make sense (though not, unfortunately, as comments
> > about programming). Do you think perhaps yo might be trying just a
> > little too hard?
>
> > regards
> >   Steve
> > --
> > Steve Holden+1 571 484 6266   +1 800 494 3119
> > Holden Web LLC  http://www.holdenweb.com/-Hide quoted text -
>
> > - Show quoted text -
>
> It's definitely possible.  I've been hacking the code for some time,
> and so far, the furthest I've gotten is:
>
> >>> bartender.think()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> AttributeError: 'Bartender' object has no attribute 'think'
>
>
>
> Any ideas?

You need to pass it a parameter for .drink() which in turn calls
the .pay() function, before it can .think()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Double underscores -- ugly?

2008-02-20 Thread cokofreedom
So people's problem with __word__ is that it is not very readable?

How so, it stands out on page, it clearly is different from other
objects and doesn't abuse other symbols that generally have a meaning
based on their use.

I haven't seen a single alternative that really stands out as much as
__word__ does.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's "the standard" for code docs?

2008-02-20 Thread cokofreedom
On Feb 20, 9:12 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > Are people really writing pure HTML snippets in docstrings to document
> > each module/class/method?  For anything other than a toy project?
>
> > One of the main reasons I'm considering moving to epydoc + reST is
> > precisely because it's very un-HTML.
>
> > Mind you I want to be able to produce HTML format docs from the
> > source, but I don't want to actually *put* HTML anywhere near my
> > precious sources.
>
> In the Java-world it *is* pure HTML snipplets... but no, not in python.
>
> Diez

Doxygen is your friend!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TRAC - Trac, Project Leads, Python, and Mr. Noah Kantrowitz (sanitizer)

2008-02-18 Thread cokofreedom
Dear Ilias,

Post in a single reply.

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


Re: Current Fastest Python Implementation?

2008-02-18 Thread cokofreedom
On Feb 18, 9:37 am, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> samuraisam wrote:
> > Has anyone done any recent testing as to which current python
> > implementation is the quickest?
>
> Search for a recent thread on CPython and IronPython.
>
> > Perhaps for Django development -
> > though the current one certainly is fast (and I doubt micro
> > optimizations would make much difference in overall performance).
> > Regardless - have those pypy folks made a faster implementation, or
> > the jython folks? Or the .NET implementation?
>
> Depends on your use case. Take your application, do some benchmarking and use
> the implementation that turns out to be a) most reliable and b) the fastest.
>
> In that order.
>
> Stefan

PyPy [http://codespeak.net/pypy/dist/pypy/doc/home.html] is getting
progressively faster.

In fact for certain things it can be faster than C [http://
morepypy.blogspot.com/2008/01/rpython-can-be-faster-than-c.html]!

However it seems it still has a way to go to be fully operational!
Still looks like the future to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Assignment saves time?

2008-02-15 Thread cokofreedom
> $ python -m timeit -s 'l=[]' 'len(l)==1000'
> 100 loops, best of 3: 0.256 usec per loop
> $ python -m timeit -s 'l=[]' 'len(l)==1000'
> 100 loops, best of 3: 0.27 usec per loop
>
> $ python -m timeit -s 'l=[]' 's=len(l); s==1000'
> 100 loops, best of 3: 0.287 usec per loop
> $ python -m timeit -s 'l=[]' 's=len(l); s==1000'
> 100 loops, best of 3: 0.299 usec per loop

More results pretty much agree with yours:

C:\Python25>python -m timeit -s 'l=range(1000)' 'len(l)==1000'
1000 loops, best of 3: 0.0235 usec per loop

C:\Python25>python -m timeit -s 'l=range(1000)' 'len(l)==1000'
1000 loops, best of 3: 0.0245 usec per loop

C:\Python25>python -m timeit -s 'l=range(1000)' 's=len(l)' 's==1000'
1000 loops, best of 3: 0.0383 usec per loop

C:\Python25>python -m timeit -s 'l=range(1000)' 's=len(l)' 's==1000'
1000 loops, best of 3: 0.038 usec per loop
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-14 Thread cokofreedom
> hmm... interesting
>
> here is another way you can find prime 
> numbershttp://love-python.blogspot.com/2008/02/find-prime-number-upto-100-nu...
>

Sadly that is pretty slow though...

If you don't mind readability you can make the example I gave into
five lines.

def p(_):
 if _<3:return[2]if _==2 else[]
 a,b,b[1]=int(_**0.5)+1,range(_+1),0
 for c in xrange(2,a):
  if b[c]:b[c*c:_+1:c]=[0]*((_/c-c)+1)
 return[_ for _ in b if _]

But then, I would have to kill you...
-- 
http://mail.python.org/mailman/listinfo/python-list


Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread cokofreedom
I was reading up on this site [http://www.noulakaz.net/weblog/
2007/03/18/a-regular-expression-to-check-for-prime-numbers/] of an
interesting way to work out prime numbers using Regular Expression.

However my attempts to use this in Python keep returning none
(obviously no match), however I don't see why, I was under the
impression Python used the same RE system as Perl/Ruby and I know the
convert is producing the correct display of 1's...Any thoughts?

def re_prime(n):
import re
convert = "".join("1" for i in xrange(n))
return re.match("^1?$|^(11+?)\1+$", convert)

print re_prime(2)

Also on a side note the quickest method I have come across as yet is
the following

def prime_numbers(n):
if n < 3: return [2] if n == 2 else []
nroot = int(n ** 0.5) + 1
sieve = range(n + 1)
sieve[1] = 0
for i in xrange(2, nroot):
if sieve[i]:
sieve[i * i: n + 1: i] = [0] * ((n / i - i) + 1)
return [x for x in sieve if x]

Damn clever whoever built this (note sieve will produce a list the
size of your 'n' which is unfortunate)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ways to declare empty set variable

2008-02-13 Thread cokofreedom
The irony that, x = (,) produces an error.

Personally I would of thought it would be a better example of an empty
tuple than anything else, but it still isn't that readable.

The use of dict/list/tuple/set seems to stand out a lot better, makes
it readable! Else in a few years you'll have §x§ = !^!()

Or maybe I am going crazy...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-13 Thread cokofreedom
> And the rest of us just use SI.  (And if you bring up the
> _kilogram-force_, I'll just cry.)

SI = Super Incredible?

Awesome name for Force/Mass / NewItemOfClothing2050!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: Speed of light [was Re: Why not a Python compiler?]

2008-02-11 Thread cokofreedom
On Feb 12, 7:16 am, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> Erik Max Francis wrote:
> > Jeff Schwab wrote:
>
> >> Erik Max Francis wrote:
> >>> Grant Edwards wrote:
>
>  On 2008-02-12, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> > Fair enough!
>
>  Dear me, what's Usenet coming to these days...
>
> >>> I know, really.  Sheesh!  Jeff, I won't stand for that!  Argue with
> >>> me!  :-)
>
> >> OK, uh...  You're a poopy-head.
>
> >> Forgive the cliché, but there's already too much road rage on the
> >> information superhighway.  I've had limited access to Usenet for the
> >> last couple of years, and coming back, I find myself shocked at how
> >> many people seem to be mean and argumentative just for the heck of
> >> it.  Was it really always this hostile?  Maybe I've gotten soft in my
> >> old age.
>
> > Note smiley.  Grant and I were joking.
>
> Yes, I understood.
>
> Ahhh, back to that familiar, awkward discomfort...

Hold it, 2, 3 and release...ahhh good times
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to autorun a python script when a specific user logs on?

2008-02-08 Thread cokofreedom
On Feb 8, 1:30 am, "jack trades" <[EMAIL PROTECTED]> wrote:
> "Mike Hjorleifsson" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > on windows you can put this in HKEY_Local_Machine\Software\Microsoft
> > \Windows\Current Version\Run and it will run at logon (or fast user
> > switch) for each user
> > or if you only want to do it for a specific user you need to determine
> > their CSLID and put it in the same locale under the HKEY_USERS\Users
> > cslid... etc.
>
> Thanks for sparing some time.  I was looking through the registry and found
> that this works as long as you are logged in as the user you want to
> autostart the program for:
>
> def autostartProgram(name, location):
>   os.system(r'reg add HKCU\software\microsoft\windows\currentversion\run /v
> %s /t REG_SZ /d %s' % (name, location) )
>
> Jack Trades

Lets hope no one teaches these kids about run->msconfig and other such
techniques for turning these annoying things off. If the parent is
worried about their childs activites then supervise their usage, only
allow them on the system when they are nearby or present...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does list have no 'get' method?

2008-02-08 Thread cokofreedom
On Feb 8, 8:23 am, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Feb 7, 8:44 am, Steve Holden <[EMAIL PROTECTED]> wrote:
>
> > [EMAIL PROTECTED] wrote:
> > > I'd like to know what others think about it, about this anti-feature.
> > > What I can say is that other computer languages too think that boolean
> > > operations must return boolean values only, so I am not alone in my
> > > folly :-)
>
> > Other languages do indeed refuse the temptation to short-circuit,
>
> Short-circuiting isn't the issue here; a language can short circuit
> and still return a boolean.
>
> > but
> > that doesn't mean that Python is wrong to do so. It's a design choice,
> > and while you are free to disagree with it I imagine you would be
> > pissing in the wind in attempting to get a change like that into Python 3.
>
> > Most people like the semantics of "and" and "or" as they are.
>
> I guess I'll agree with bearophile here; I think booleans should be
> completely disjoint from all other types, as they are in Java.  "and",
> "or", and "not" should accept only boolean operands and return only
> boolean results.
>
> I don't deny that it's convenient to use "or" that returns the first
> true value, or that it's sometimes a marginal improvement in clarity.
>
> I just think this idiom is too error prone, and very often too
> misleading, to justify its convenience.  There's ordinary
> carelessness, of course, where someone writes a function like this:
>
> def op(datum=None):
> result = datum or default
>
> while not stopping to consider that the empty string would be a legal
> value for datum in this case.  But there's a more insidious danger
> that can't be chalked up to carelessness: when the acceptable values
> for datum change *after* the function is written.  This leads to
> subtle breakage.
>
> As far as the user is concerned, this function's correct behavior is
> to "use the default when the argument is not specified", but as-is the
> function is not robust to future changes or uses.  The function is a
> poor, non-robust implementation of the desired behavior.
>
> To me this feels like a ticking bomb, a bug waiting to emerge from
> it's egg.
>
> More generally: I find that the boundary between what Python considers
> to be true and false rarely corresponds exactly to what I'm trying to
> do in cases like the above.
> Usually the true/false test only works for certain set of expected
> values that I have in my mind.  When the acceptable values are
> generalized, when you want to expand this function's role, does the
> true/false test still work?  I find it rarely does.
>
> The Python treatment of booleans is, by far, my biggest gripe with
> Python.  (Which, you know, is a pretty good thing to have as a biggest
> gripe.)
>
> Carl Banks

Can't you just make a subclass of Boolean and add methods to the true/
false, or am i running up a tree with a cat?

I think a clear problem with this is that, this is one area of grief
for some users with the Try/Except: clause usage, there are many other
examples of this where people would prefer one liners, and a good
argument not to allow one is because then you probably wouldn't have a
good defence against disallowing the other forms...

just-my-one-cent-ly's yours Coko
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not a Python compiler?

2008-02-05 Thread cokofreedom
On Feb 5, 9:19 am, Santiago  Romero <[EMAIL PROTECTED]> wrote:
>  ( Surely if this question has been asked for a zillion of times... )
>  ( and sorry for my english! )
>
>  I'm impressed with python. I'm very happy with the language and I
> find Python+Pygame a very powerful and productive way of writing 2D
> games. I'm not, at this moment, worried about execution speed of the
> small game I'm working on (it runs at full 60 fps even in an old AMD-
> K6 450 Laptop computer), but I continue asking me the same question:
>
>  Why not a Python COMPILER?
>
>  It would be very nice to be able to output Linux, MAC or Windows
> binaries of compiled (not bytecompiled) code. It would run faster, it
> will be smaller in size (I think) and it will be easy to distribute to
> people not having python installed. Yes, I know about py2exe, but I'm
> not sure if that's the right aproach.
>
>  So, what's wrong with compiling python?
>
>  Maybe is not possible due to nature of the language? Is just a
> decision?
>
>  What do you think about this?

I don't know the exact details but I think the issue is the dynamic
nature of Python makes it impossible to correctly store the various
types and changes into compiled code. Someone else will probably be
able to provide a good reason as to why it isn't very feasible, nor a
good idea. If you want to speed up your python look at Psyco.
http://psyco.sourceforge.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-30 Thread cokofreedom
Anyone else noticed that the OP has not actually replied to any of the
suggestions...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Removal of element from list while traversing causes the next element to be skipped

2008-01-30 Thread cokofreedom
On Jan 30, 9:50 am, Santiago  Romero <[EMAIL PROTECTED]> wrote:
> On 30 ene, 08:09, Paul Rubin  wrote:
>
> > Santiago  Romero <[EMAIL PROTECTED]> writes:
>
> > > > >>> li = [1,2,3,4,5]
> > > > >>> filter(lambda x: x != 3, li)
> > > > [1, 2, 4, 5]
>
> > >  I haven't measured it, but this should be the fast solution in all
> > > the thread ...
>
> > li.remove(3) is probably faster.
>
>  But that only removes the first ocurrence of item==3.
>
>  In  a = [1, 2, 3, 3, 3, 4, 3, 3, 2, 3], the filter solution will
> efectively remove all items with value == 3 while li.remove(3) will
> only remove the first ocurrence.
>
>  Bye!

from itertools import ifilter
print [x for x in ifilter(lambda x: x != 99, li)]

Will this one be faster or slower than filter?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: optional static typing for Python

2008-01-28 Thread cokofreedom
On Jan 28, 11:42 am, "Russ P." <[EMAIL PROTECTED]> wrote:
> On Jan 28, 1:51 am, Bruno Desthuilliers 
>
>
> [EMAIL PROTECTED]> wrote:
> > Russ P. a écrit :> A while back I came across a tentative proposal from way 
> > back in 2000
> > > for optional static typing in Python:
>
> > (snip)
>
> > > In any case, optional static typing in Python would help tremendously
> > > here. The hardest part of automated conversion of Python to a
> > > statically typed language is the problem of type inference. If the
> > > types are explicitly declared, that problem obviously goes away.
>
> > (snip)
>
> > > Note also that, while "static" type checking would be ideal,
> > > "explicit" typing would be a major step in the right direction
>
> > Lord have mercy(tm).
>
> What is that supposed to mean?
>
> Oh, I almost forgot. I'm supposed to sit here and be polite while
> clueless dolts make wise cracks. Sorry, but I haven't yet mastered
> that level of self-control.
>
> I would just like to thank you for reminding me about what losers hang
> out perpetually on sites like this one, thinking they are in some kind
> of real "community." Being reminded of that will help prevent me from
> becoming such a loser myself. No, I didn't say that all the "regulars"
> here are losers, but you most certainly are.
>
> Do you have a job? How about a life? Have you ever been "with" a
> woman? How in the world is it that every time I come to this site, I
> see your sorry ass hanging around yet again? I can't even imagine how
> "pointless" your life must be if you have that much time to spend
> "hanging around" on comp.lang.python -- and being an a--hole to boot.
>
> Yeah, Lord have mercy -- on losers like you.
>
> And thanks for reminding me to quit wasting so much time here. I've
> been doing way too much of that lately.

Why is it everyone has to resort to name calling and instantly being
offended by everyone. If you don't think he reply has merit, then
either simply ask him what he meant or ignore the post altogether.
Your reply just flames the issue.

I never get the reason why people feel the need to insult someone they
feel has insulted them. That somehow by the re-doing the act they will
solve the issue? Just move on.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping whitespace

2008-01-24 Thread cokofreedom
On Jan 24, 8:21 am, ryan k <[EMAIL PROTECTED]> wrote:
> On Jan 23, 6:30 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
> > On Jan 24, 9:50 am, ryan k <[EMAIL PROTECTED]> wrote:
>
> > > Steven D'Aprano, you are a prick.
>
> > And your reasons for coming to that stridently expressed conclusion
> > after reading a posting that was *not* addressed to you are .?
>
> Because his tone is extremely condescending and quite frankly
> annoying. From this post to others, his terse remarks scar this
> community and fade its atmosphere of friendliness.

And your response was any better because...?
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >