Need help improving number guessing game

2008-12-13 Thread feba
#!/usr/bin/python/
#Py3k, UTF-8

import random

print(" --- WELCOME TO THE SUPER NUMBER GUESSING GAME --- " + ("\n" *
5))
pnum = int(input("1 OR 2 PLAYER?\nP#: "))

target = random.randint(1, 99) #Pick a random number under two digits

guess1 = 0 #Zero will never be picked as target...
guess2 = 0 #so it makes a good default value
p1score = 0 #For two player mode...
p2score = 0 #let's keep score!

print("LET'S START THE GAME. \nGUESS ANY WHOLE NUMBER FROM 1 TO 99.")

while True:
if pnum == 1: #1p mode
while True:
guess1 = int(input("\n>> "))
if guess1 > 100:
print("ONLY NUMBERS FROM 1 TO 99")
elif guess1 > target:
print("TOO HIGH")
elif guess1 == target:
print("CONGLATGURATIONS! PLAY AGAIN?")
target = random.randint(1, 99) #Set up the game
again
play = int(input("0 TO END: "))
if play == 0:
print("GOOD BYE. PLAY AGAIN SOON!")
quit()
else:
print("TOO LOW")

if pnum == 2: #2p mode
while True:
guess1 = int(input("\nP1> ")) #Player 1's turn
if guess1 > 100:
print("ONLY NUMBERS FROM 1 to 99")
elif guess1 > target:
print("TOO HIGH")
elif guess1 == target:
p1score += 1
print("GOOD JOB, PLAYER 1! THE SCORE IS:\nP1: %s
--- P2: %s\nPLAY AGAIN?" % (p1score, p2score))
target = random.randint(1, 99) #Set up game
again
play = int(input("0 TO END: "))
if play == 0:
print("GOOD BYE. PLAY AGAIN SOON!")
else:
print("TOO LOW")

guess2 = int(input("\nP2> ")) #Player 2's turn
if guess2 > 100:
print("ONLY NUMBERS FROM 1 to 99")
elif guess2 > target:
print("TOO HIGH")
elif guess2 == target:
p2score += 1
print("GOOD JOB, PLAYER 2! THE SCORE IS:\nP1: %s
--- P2: %s\nPLAY AGAIN?" % (p1score, p2score))
target = random.randint(1, 99) #Set up game again
play = int(input("0 TO END: "))
if play == 0:
print("GOOD BYE. PLAY AGAIN SOON!")
else:
print("TOO LOW")
else:
print("INVALID PLAYER SELECTION")
pnum = int(input("1 OR 2 PLAYER?\nPN#: "))


I have one major problem with this; the 'replay' selection. It quits
if you put in 0, as it should, and continues if you put in any other
number. However, if you just press enter, it exits with an error. it
also looks really ugly, and I'm sure there has to be plenty of better
ways to do it.

I'd also appreciate tips on how it could be better in general. I
should think that P1 and P2's turns shouldn't have to be completely
repeated; but I'm not quite sure how to def something like that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Umlauts in idle

2008-12-13 Thread Martin v. Löwis
> When I try to use umlauts in idle it will only print out as Unicode
> escape characters. Is it possible to configure idle to print them as
> ordinary characters?

Did you really use the print statement? They print out fine for me.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


setup.py installs modules to a wrong place

2008-12-13 Thread Michal Ludvig
Hi,

I have recently seen some reports from users of my s3cmd script [1] who
installed the package using the provided distutils-based setup.py and
immediately after installation the script failed to run because it
couldn't find its modules.

Here's an example session from Mac OS X, but similar behaviour has been
observed on Ubuntu as well. Needless to say it works for me just fine so
I can't easily debug and fix it :-(

First is the reported setup.py output:

-
~/bin/s3cmd $ sudo python setup.py install
Password:
...
running install_lib
creating /usr/lib/python2.5/site-packages
creating /usr/lib/python2.5/site-packages/S3
copying build/lib/S3/PkgInfo.py -> /usr/lib/python2.5/site-packages/S3
... more modules, etc ...
-

It decided to put the modules to /usr/lib/python2.5/site-packages/S3

Now, s3cmd should import from there, but fails:

~/bin/s3cmd $ s3cmd
Traceback (most recent call last):
   File "/usr/bin/s3cmd", line 1207, in 
 from S3 import PkgInfo
ImportError: No module named S3

sys.path at the time the script died had these entries:
/usr/bin
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.5/...other_subdirs...
/Library/Python/2.5/site-packages

There is nothing special in setup.py. After all have a look yourself:
http://s3tools.svn.sourceforge.net/viewvc/s3tools/s3cmd/trunk/setup.py?view=markup

What could be the reason for distutils / setup.py to install the modules
to a directory that's not in sys.path? Can I detect it in setup.py and
prevent or workaround it somehow?

Thanks!

[1] http://s3tools.logix.cz/s3cmd -- Amazon S3 command line client

Michal



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


Re: Need help improving number guessing game

2008-12-13 Thread James Stroud

feba wrote:

#!/usr/bin/python/
#Py3k, UTF-8

import random

print(" --- WELCOME TO THE SUPER NUMBER GUESSING GAME --- " + ("\n" *
5))
pnum = int(input("1 OR 2 PLAYER?\nP#: "))

target = random.randint(1, 99) #Pick a random number under two digits

guess1 = 0 #Zero will never be picked as target...
guess2 = 0 #so it makes a good default value
p1score = 0 #For two player mode...
p2score = 0 #let's keep score!

print("LET'S START THE GAME. \nGUESS ANY WHOLE NUMBER FROM 1 TO 99.")

while True:
if pnum == 1: #1p mode
while True:
guess1 = int(input("\n>> "))
if guess1 > 100:
print("ONLY NUMBERS FROM 1 TO 99")
elif guess1 > target:
print("TOO HIGH")
elif guess1 == target:
print("CONGLATGURATIONS! PLAY AGAIN?")
target = random.randint(1, 99) #Set up the game
again
play = int(input("0 TO END: "))
if play == 0:
print("GOOD BYE. PLAY AGAIN SOON!")
quit()
else:
print("TOO LOW")

if pnum == 2: #2p mode
while True:
guess1 = int(input("\nP1> ")) #Player 1's turn
if guess1 > 100:
print("ONLY NUMBERS FROM 1 to 99")
elif guess1 > target:
print("TOO HIGH")
elif guess1 == target:
p1score += 1
print("GOOD JOB, PLAYER 1! THE SCORE IS:\nP1: %s
--- P2: %s\nPLAY AGAIN?" % (p1score, p2score))
target = random.randint(1, 99) #Set up game
again
play = int(input("0 TO END: "))
if play == 0:
print("GOOD BYE. PLAY AGAIN SOON!")
else:
print("TOO LOW")

guess2 = int(input("\nP2> ")) #Player 2's turn
if guess2 > 100:
print("ONLY NUMBERS FROM 1 to 99")
elif guess2 > target:
print("TOO HIGH")
elif guess2 == target:
p2score += 1
print("GOOD JOB, PLAYER 2! THE SCORE IS:\nP1: %s
--- P2: %s\nPLAY AGAIN?" % (p1score, p2score))
target = random.randint(1, 99) #Set up game again
play = int(input("0 TO END: "))
if play == 0:
print("GOOD BYE. PLAY AGAIN SOON!")
else:
print("TOO LOW")
else:
print("INVALID PLAYER SELECTION")
pnum = int(input("1 OR 2 PLAYER?\nPN#: "))


I have one major problem with this; the 'replay' selection. It quits
if you put in 0, as it should, and continues if you put in any other
number. However, if you just press enter, it exits with an error. it
also looks really ugly, and I'm sure there has to be plenty of better
ways to do it.

I'd also appreciate tips on how it could be better in general. I
should think that P1 and P2's turns shouldn't have to be completely
repeated; but I'm not quite sure how to def something like that.


1. Refactor. You should look at your code and see where you repeat the 
same or similar patterns, see where they differ, make functions, and 
make the differences parameters to the function call:


def guess(player, p1score, p2score):
  guess1 = int(input("\n>> "))
  if guess1 > 100:
print("ONLY NUMBERS FROM 1 TO 99")
  elif guess1 > target:
print("TOO HIGH")
  elif guess1 == target:
print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player)
print("P1: %s --- P2: %s"  % (p1score, p2score)))
print("PLAY AGAIN?")
#Set up the game again
play = int(input("0 TO END: "))
if play == 0:
  print("GOOD BYE. PLAY AGAIN SOON!")
  quit()
else:
  target = random.randint(1, 99)
  else:
print("TOO LOW")

You would call guess() like this, perhaps:

   guess(2, 15, 22)

2. You need to use a try: except: within a loop when you cast the input 
to int:


while True:
  try:
guess1 = int(input("\n>> "))
  except ValueError:
print 'Bad value.'
  else:
break

Same with the seeing if the player will play again. See below.

3. Don't try to fit too much on one line. See how I broke the print 
statement at logical places (new lines).



4. Further subdivide functions based on conceptual tasks. For example, I 
would define a function like this:


def play_again():
  while True:
try:
  print("PLAY AGAIN?")
  again = bool(input("0 TO END: "))
except ValueError:
  print 'Bad value.'
else:
  break
  return again

You would use play_again() like this:

if play_again():
  print("GOOD BYE. PLAY AGAIN SOON!")
  quit()
else:
  target = random.randint(1, 99)


5. Don't do anything until you need to do it. See how I handled setting 
the new target for what I mean. You set a new target befo

Re: Need help improving number guessing game

2008-12-13 Thread Steven D'Aprano
On Sat, 13 Dec 2008 00:57:12 -0800, feba wrote:

> I have one major problem with this; the 'replay' selection. It quits if
> you put in 0, as it should, and continues if you put in any other
> number. However, if you just press enter, it exits with an error. it
> also looks really ugly, and I'm sure there has to be plenty of better
> ways to do it.

Start by refactoring your code into small, easy to understand functions. 
For example, 

You mix in the same piece of code the logic for:

- error handling;
- starting a new game;
- quiting (although you use a function for this, well done);
- and game logic

and then you have to repeat it all again, almost word-for-word, for one 
player mode and two player mode.

Start with a high-level approach. The guessing game has the following 
structure:

while you want to play a game:
play a game
ask play again?

which in Python might look like this:

playing = True
while playing:
play_one_game()
playing = play_again()

def play_again():
# For Python 3, change "raw_input" to "input".
response = raw_input("Would you like to play again? y/n ")
return response.strip().lower() == "y"

This function accepts *only* Y or y to play another game. Later, after 
you've got the game working, you can come back to this and modify it so 
that it accepts Yes or just enter on it's own. Make it work as simply as 
possible first, then come back and make it more complicated later.


Now do the same thing for playing one game. A single game in two player 
mode looks something like this:

pick a target number
start with one person as the guesser
until the target is guessed:
guess a number
let the other person be the guesser

which in Python might look like this:

def play_one_game():
target = pick_target()  # you need to write this function
guessed = False
player = "Player One"
while not guessed:
guess = guess_number(player)  # you need to write this too
if guess == target:
guessed = True
else:
player = swap_player(player)  # player one <=> player two
# When we exit the loop, player is the person who guessed correctly.
if player == "Player One":
p1score += 1
else:
p2score += 1


Best of all, you can change from two player mode to one player mode just 
by skipping the line "player = swap_player(player)". The rest of the code 
remains exactly the same, and you don't need to repeat everything.


Have a play around with this approach, and then come back to us if you 
need more hints.



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


Re: Need help improving number guessing game

2008-12-13 Thread James Stroud

James Stroud wrote:
1. Refactor. You should look at your code and see where you repeat the 
same or similar patterns, see where they differ, make functions, and 
make the differences parameters to the function call:


def guess(player, p1score, p2score):
  guess1 = int(input("\n>> "))
  if guess1 > 100:
print("ONLY NUMBERS FROM 1 TO 99")
  elif guess1 > target:
print("TOO HIGH")
  elif guess1 == target:
print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player)
print("P1: %s --- P2: %s"  % (p1score, p2score)))
print("PLAY AGAIN?")
#Set up the game again
play = int(input("0 TO END: "))
if play == 0:
  print("GOOD BYE. PLAY AGAIN SOON!")
  quit()
else:
  target = random.randint(1, 99)
  else:
print("TOO LOW")


I realized this has a bug. The target is locked in the scope of the 
function. I wouldn't use global, though:


def guess(player, p1score, p2score):
  target = None
  guess1 = int(input("\n>> "))
  if guess1 > 100:
print("ONLY NUMBERS FROM 1 TO 99")
  elif guess1 > target:
print("TOO HIGH")
  elif guess1 == target:
print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player)
print("P1: %s --- P2: %s"  % (p1score, p2score)))
print("PLAY AGAIN?")
#Set up the game again
play = int(input("0 TO END: "))
if play == 0:
  print("GOOD BYE. PLAY AGAIN SOON!")
  quit()
else:
  target = random.randint(1, 99)
  else:
print("TOO LOW")

Use it like this:

new_target = gues(player, p1score, p2score)
if new_target is not None:
  target = new_target

I officially declare that I can't guarantee no more bugs in my previous 
post. I just fixed this one because my conscience was bothering me.


James



--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: Need help improving number guessing game

2008-12-13 Thread James Stroud

I forgot to return target:


def guess(player, p1score, p2score):
  target = None
  guess1 = int(input("\n>> "))
  if guess1 > 100:
print("ONLY NUMBERS FROM 1 TO 99")
  elif guess1 > target:
print("TOO HIGH")
  elif guess1 == target:
print("GOOD JOB, PLAYER %s! THE SCORE IS:" % player)
print("P1: %s --- P2: %s"  % (p1score, p2score)))
print("PLAY AGAIN?")
#Set up the game again
play = int(input("0 TO END: "))
if play == 0:
  print("GOOD BYE. PLAY AGAIN SOON!")
  quit()
else:
  target = random.randint(1, 99)
  else:
print("TOO LOW")
  return target

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: Umlauts in idle

2008-12-13 Thread a_olme
On 13 Dec, 10:38, "Martin v. Löwis"  wrote:
> > When I try to use umlauts in idle it will only print out as Unicode
> > escape characters. Is it possible to configure idle to print them as
> > ordinary characters?
>
> Did you really use the print statement? They print out fine for me.
>
> Regards,
> Martin

No I just put the characters in quotes like this "öäå"[::-1] and
pressed return.

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


Re: Removing None objects from a sequence

2008-12-13 Thread Steven D'Aprano
On Fri, 12 Dec 2008 19:02:24 -0500, Terry Reedy wrote:

> Tim Chase wrote:
>>> If you want to literally remove None objects from a list(or
>>> mutable sequence)
>>>
>>> def deNone(alist):
>>>n=len(alist)
>>>i=j=0
>>>while i < n:
>>>  if alist[i] is not None:
>>>alist[j] = alist[i]
>>>j += 1
>>>  i += 1
>>>alist[j:i] = []
>>>
>>> blist=[None,1,None,2,None,3,None,None,4,None] deNone(blist)
>>> print(blist)
>>>
>>> # prints [1, 2, 3, 4]
>> 
>> ...wouldn't a cleaner way of doing this just be
>> 
>>   >>> blist=[None,1,None,2,None,3,None,None,4,None]
> 
> No, making a filtered copy that is then copied back before being deleted
> is algorithmically much messier.  My code does the minimum work
> necessary and is algorithmically cleaner.

Er what? You're joking, right?

Your function has eight lines, all of which are very low level: you're 
dealing with not one but TWO list indexes yourself. You have three 
internal names to deal with, although in fairness one is set once then 
used as a constant from then on. The algorithm is unclear: try explaining 
what you are doing in English, and see how difficult it is.

"Keep two indexes into the list. If the first index isn't pointing at 
None, copy that value to the second index, which is either the same as 
the first index, or pointing at None. Then advance the second index, and 
the first index, as needed. It will never over-write a non-None value, 
but just try proving it."

Contrast that with the alternative suggested by Tim:

def deNone2(alist):
alist[:] = [x for x in alist if x is not None]


It's one line, with one internal variable. You don't have to manipulate 
index variables. The explanation is simple:

"Make a new list with the non-None values and assign it in-place to the 
old list."

Clear, succinct, and understandable, with no corner cases like empty 
lists to worry about.


Here's another low-level algorithm, the classical delete items in place 
algorithm. Three lines, one index, lousy O(N**2) performance.

def deNone3(alist):
for i in xrange(len(alist)-1, -1, -1):
if alist[i] is None:
del alist[i]

Now, let's do a shoot-out. Do they return the same thing?

>>> masterlist = [None]*2 + range(5) + [None]*3 + range(5, 10) + [None]*4 
+ [10, None, 11, None, 12, None]
>>> alist = masterlist[:]
>>> blist = masterlist[:]
>>> clist = masterlist[:]
>>> deNone(alist)
>>> deNone2(blist)
>>> deNone3(clist)
>>> alist == blist == clist
True


Which is faster?

>>> from timeit import Timer
>>> setup = "from __main__ import deNone, deNone2, deNone3;" \
... " from __main__ import masterlist as m"
>>> t1 = Timer("a=m[:];deNone(a)", setup)
>>> t2 = Timer("a=m[:];deNone2(a)", setup)
>>> t3 = Timer("a=m[:];deNone3(a)", setup)
>>> t1.repeat(number=1)
[0.39079904556274414, 0.38915109634399414, 0.39700794219970703]
>>> t2.repeat(number=1)
[0.17854905128479004, 0.1782989501953125, 0.17886185646057129]
>>> t3.repeat(number=1)
[0.26834988594055176, 0.25835609436035156, 0.25850009918212891]


Not surprisingly, Tim's version is twice as fast as yours. Surprisingly, 
even the deNone3 function is faster than yours.

What about a real test? None of these piddly toy data sets, with 25 
items. Something *real*.

>>> masterlist = masterlist*100
>>> masterlist += range(1000)
>>> masterlist += [None]*1000
>>> masterlist += [None, 0]*1000
>>> masterlist += [1]*1
>>> len(masterlist)
16500
>>> t1.repeat(number=100)
[2.1611621379852295, 1.2539350986480713, 1.2424759864807129]
>>> t2.repeat(number=100)
[0.93860101699829102, 0.44704914093017578, 0.41285014152526855]
>>> t3.repeat(number=100)
[4.5643420219421387, 3.216562032699585, 3.2176508903503418]

Not surprisingly, my version really suffers. But so does yours: it's now 
three times slower than Tim's. I expect that Tim's version will look 
better and better until the list is so huge that memory paging to disk 
becomes a factor.

Now, sure, most of the work in Tim's version is executed in fast C code 
instead of slow Python code. If we were programming in C, your version 
might perform better relative to Tim's. But even if performance was 
better, I wouldn't describe the algorithm as particularly clean. 


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


Re: var or inout parm?

2008-12-13 Thread Marc 'BlackJack' Rintsch
On Sat, 13 Dec 2008 02:20:59 +0100, Hrvoje Niksic wrote:

> Saner (in this respect) behavior in the tuple example would require a
> different protocol.  I don't understand why Python doesn't just call
> __iadd__ for side effect if it exists.  The decision to also rebind the
> result of __i*__ methods continues to baffle me.  I guess it is a result
> of a desire to enable the __i*__ methods to punt and return a different
> instance after all, but if so, that design decision brings more problems
> than benefits.

How often do you use ``+=`` with mutable objects?  I use it very often 
with number types and sometimes with tuples, and there rebinding is 
necessary.  If I couldn't use it in this way:  ``x = 0; x += z``, I'd 
call that a bad design decision.  It would be a quite useless operator 
then.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


__future__ and compile: unrecognised flags

2008-12-13 Thread Poor Yorick
I have a future statement in a script which is intended to work in 2.6 and 3.
Shouldn't compile flags in __future__ objects essentially be noops for versions
that already support the feature? doctest is complaining about unrecognised
flags.  This illustrates the problem:

Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] 
on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import unicode_literals
>>> src = 'a = "hello"'
>>> c1 = compile(src,'','exec',unicode_literals.compiler_flag)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: compile(): unrecognised flags

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


Re: Umlauts in idle

2008-12-13 Thread Marc 'BlackJack' Rintsch
On Sat, 13 Dec 2008 02:58:48 -0800, a_olme wrote:

> On 13 Dec, 10:38, "Martin v. Löwis"  wrote:
>> > When I try to use umlauts in idle it will only print out as Unicode
>> > escape characters. Is it possible to configure idle to print them as
>> > ordinary characters?
>>
>> Did you really use the print statement? They print out fine for me.
>>
>> Regards,
>> Martin
> 
> No I just put the characters in quotes like this "öäå"[::-1] and pressed
> return.

Then you have two problems:  First, you don't have unicode characters but 
a bunch of bytes which encode the three characters you've showed above.  
Reversing the bytes might "break" them if your system uses multiple bytes 
to encode one character, e.g. UTF-8, because the order does matter.

Second, if you don't ``print`` but let the interpreter show the result 
you get the `repr()` form of that character displayed, which always uses 
escapes for bytes that are non-printable or not within the ASCII range 
for strings.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Removing None objects from a sequence

2008-12-13 Thread Filip Gruszczyński
Just to be clear, I decided to use generator by alex23, as it seems
simple, short and understandable. Still reading this thread was quite
interesting, thanks :-)

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Parallelizing python code - design/implementation questions

2008-12-13 Thread stdazi
Hello!

I'm about to parallelize some algorithm that turned out to be too
slow. Before I start doing it, I'd like to hear some suggestions/hints
from you.

The algorithm essentially works like this:  There is a iterator
function "foo" yielding a special kind permutation of [1,n]. The
main program then iterates through this permutations calculating some
proprieties. Each time a calculation ends, a counter is incremented
and each time the counter is divisible by 100, the current progress is
printed.

The classical idea is to spawn m threads and use some global lock when
calling the instance of the iterator + one global lock for
incrementing the progress counter. Is there any better way? I'm
especially concerned with performance degradation due to locking - is
there any way to somehow avoid it?

I've also read about the `multiprocessing' module and as far as I've
understood :


permutation = foo()
threadlst = []
for i in xrange(m) :
   p = Process(target=permutation.next)
   threadlst.append(p)
   p.start()
for p in threadlst:
   p.join()


should do the trick. Am I right? Is there any better way other than
this?
--
http://mail.python.org/mailman/listinfo/python-list


Re: __future__ and compile: unrecognised flags

2008-12-13 Thread Steve Holden
Poor Yorick wrote:
> I have a future statement in a script which is intended to work in 2.6 and 3.
> Shouldn't compile flags in __future__ objects essentially be noops for 
> versions
> that already support the feature? doctest is complaining about unrecognised
> flags.  This illustrates the problem:
> 
> Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] 
> on win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> from __future__ import unicode_literals
> >>> src = 'a = "hello"'
> >>> c1 = compile(src,'','exec',unicode_literals.compiler_flag)
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: compile(): unrecognised flags
> 
This could arguably be classed as a bug given that the 2.6 documentation
for __future__ says "No feature description will ever be deleted from
__future__." However I suspect that the feature has been removed because
all string literals are Unicode in 3.0 and up, and 3.0 is allowed to
break compatibility.

One question is whether the 2to3 translator will remove such an import.
If it does then one could argue this is just another of the many
expected incompatibilities between 2.x and 3.x. If it doesn't, it should
probably be made to.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Removing None objects from a sequence

2008-12-13 Thread bearophileHUGS
Steven D'Aprano:
> The algorithm is unclear: try explaining
> what you are doing in English, and see how difficult it is.

That algorithm is a standard one, and quite clear. Any programmer
worth his/her/hir salt has to be able to understand that.

I agree that the idiom with the list comp (algorithm2) is better for
Python, but you have to know that algorithm1 to use it in other
languages.


> Now, sure, most of the work in Tim's version is executed in fast C code
> instead of slow Python code. If we were programming in C, your version
> might perform better relative to Tim's.

Try Psyco too:

from timeit import default_timer as clock

def remove_nones1(alist):
n = len(alist)
i = j = 0
while i < n:
if alist[i] is not None:
alist[j] = alist[i]
j += 1
i += 1
alist[j : i] = []


def remove_nones2(alist):
alist[:] = [x for x in alist if x is not None]


def remove_nones3(alist):
for i in xrange(len(alist)-1, -1, -1):
if alist[i] is None:
del alist[i]


def test123(data):
data1 = data[:]
data2 = data[:]
data3 = data[:]

t = clock()
remove_nones1(data1)
print "remove_nones1:", round(clock() - t, 2), "s"

t = clock()
remove_nones2(data2)
print "remove_nones2:", round(clock() - t, 2), "s"

t = clock()
remove_nones3(data3)
print "remove_nones3:", round(clock() - t, 2), "s"

assert data1 == data2 == data3
assert data1 == data2


def test12(data):
data1 = data[:]
data2 = data[:]
data3 = data[:]

t = clock()
remove_nones1(data1)
print "remove_nones1:", round(clock() - t, 2), "s"

t = clock()
remove_nones2(data2)
print "remove_nones2:", round(clock() - t, 2), "s"

print "remove_nones3: (not tested)"

assert data1 == data2


def gen_data(N):
print "  N:", N
data = [None]*2 + range(5) + [None]*3 + range(5, 10) + [None]*4 +
\
 [10, None, 11, None, 12, None]
data *= N
data += range(N * 10)
data += [None] * (N * 10)
data += [None, 0] * (N * 10)
data += [1] * (N * 100)
return data

print "Without Psyco:"
test123(gen_data(1000))
test12(gen_data(3))
print

print "With Psyco:"
import psyco; psyco.full()
test123(gen_data(1000))
test12(gen_data(3))


Results on a Core2 2 GHz, Python 2.6.1, latest Psyco:

Without Psyco:
  N: 1000
remove_nones1: 0.05 s
remove_nones2: 0.02 s
remove_nones3: 3.04 s
  N: 3
remove_nones1: 1.51 s
remove_nones2: 0.62 s
remove_nones3: (not tested)

With Psyco:
  N: 1000
remove_nones1: 0.0 s
remove_nones2: 0.01 s
remove_nones3: 3.01 s
  N: 3
remove_nones1: 0.08 s
remove_nones2: 0.33 s
remove_nones3: (not tested)

As you see even with Psyco a (bit) lower level style of coding
wins :-)
In practice if that routine is important (or if it's a generic library
routine that you don't know how it will be used) you use two different
algorithms according to the availability of Psyco. Something like:

def remove_nones4(alist):
if psyco_available:
n = len(alist)
i = j = 0
while i < n:
if alist[i] is not None:
alist[j] = alist[i]
j += 1
i += 1
alist[j : i] = []
else:
alist[:] = [x for x in alist if x is not None]

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Shorter tracebacks

2008-12-13 Thread bearophileHUGS
When I write recursive code in Python I sometimes go past the maximum
allowed stack depth, so I receive a really long traceback. The show of
such traceback on my screen is very slow (despite a CPU able to
perform billions of operations each second). So I think I'd like
something to shorten them.
I am thinking about something like:
from __future__ import short_traceback

That allows me to see only the first and last parts of the stack
trace, and skips the (generally very redundant) middle part.

Note that generally using sys.setrecursionlimit(limit) to set a
smaller limit isn't good, because I may need a big depth anyway.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Shorter tracebacks

2008-12-13 Thread rdmurray

On Sat, 13 Dec 2008 at 06:13, [email protected] wrote:

When I write recursive code in Python I sometimes go past the maximum
allowed stack depth, so I receive a really long traceback. The show of
such traceback on my screen is very slow (despite a CPU able to
perform billions of operations each second). So I think I'd like
something to shorten them.
I am thinking about something like:
from __future__ import short_traceback

That allows me to see only the first and last parts of the stack
trace, and skips the (generally very redundant) middle part.


_If_ such a feature were to be added, it should be a runtime option
to the interpreter, not a __future__ import.

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


Re: var or inout parm?

2008-12-13 Thread Hrvoje Niksic
Marc 'BlackJack' Rintsch  writes:

> On Sat, 13 Dec 2008 02:20:59 +0100, Hrvoje Niksic wrote:
>
>> Saner (in this respect) behavior in the tuple example would require
>> a different protocol.  I don't understand why Python doesn't just
>> call __iadd__ for side effect if it exists.  The decision to also
>> rebind the result of __i*__ methods continues to baffle me.  I
>> guess it is a result of a desire to enable the __i*__ methods to
>> punt and return a different instance after all, but if so, that
>> design decision brings more problems than benefits.
>
> How often do you use ``+=`` with mutable objects?  I use it very
> often with number types and sometimes with tuples, and there
> rebinding is necessary.  If I couldn't use it in this way: ``x = 0;
> x += z``, I'd call that a bad design decision.  It would be a quite
> useless operator then.

Marc, I agree with you, I wasn't arguing that += shouldn't work for
immutable objects.  If an object doesn't support __iadd__ at all (as
is already the case for numbers, strings, etc.), += should fall back
to __add__ followed by assignment.  My point is that, *if they do*, it
would be better to just use __iadd__ and not attempt to also rebind.
Again, in pseudocode, I'd expect A += x to be implemented as:

lhsobj = A
if hasattr(lhsobj, '__iadd__'):
lhsobj.__iadd__(x) # lhsobj has __iadd__, just use it
else:
A = lhsobj.__add__(x)  # fails if __add__ is not present either

That way tupleobj[0] += blah would work just fine for mutable objects
and would throw an exception for immutable objects.  The current
situation where += first modifies the mutable object, and *then*
throws an exception feels like a design glitch.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Shorter tracebacks

2008-12-13 Thread Peter Otten
[email protected] wrote:

> When I write recursive code in Python I sometimes go past the maximum
> allowed stack depth, so I receive a really long traceback. The show of
> such traceback on my screen is very slow (despite a CPU able to
> perform billions of operations each second). So I think I'd like
> something to shorten them.
> I am thinking about something like:
> from __future__ import short_traceback
> 
> That allows me to see only the first and last parts of the stack
> trace, and skips the (generally very redundant) middle part.
> 
> Note that generally using sys.setrecursionlimit(limit) to set a
> smaller limit isn't good, because I may need a big depth anyway.

That's none of __future__'s business, I think. Python offers a hook which
you can modify:

>>> import sys, traceback
>>> from functools import partial
>>> sys.excepthook = partial(traceback.print_exception, limit=5)
>>> x = 0
>>> def f():
... global x
... x += 1
... f()
...
>>> f()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 4, in f
  File "", line 4, in f
  File "", line 4, in f
  File "", line 4, in f
RuntimeError: maximum recursion depth exceeded
>>> x
999

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


Re: Bidirectional Networking

2008-12-13 Thread Emanuele D'Arrigo
On Dec 12, 9:04 pm, "Gabriel Genellina" 
wrote:
> If you're using 2.5 or older, override serve_forever:
>
>  def serve_forever(self):
>  while not getattr(self, 'quit', False):
>  self.handle_request()
>
> and set the server 'quit' attribute to True in response to some command
>  from the client.

Ok, I've tried this method and it would work if I wanted to shut down
the server from the remote client. But if I want the server to shut
down from the server itself upon some condition it doesn't work
because the while statement is evaluated again only after there has
been a request. If requests are infrequent or have ceased the
self.handle_request() is never invoked and both the loop and the
thread that contains it hang. I wasn't able to set a timeout upon
which the handle_request() method returns. I'm not sure why. But I was
able to make the original serve_forever() work.

The problem was that in my code I used:

asyncServer.daemon = True

but somehow that doesn't work. I then tried:

asyncServer.setDaemon(True)

and that does work: when the asyncClient thread ends the only thread
left running is the asyncServer, but as it is a daemon thread and
there are no non-daemon threads left, the application exits regularly.
So, below there's an updated version of my code that works as
intended.

Thanks for your help!

Manu


-
To use the following code, cut&paste into two separate *.py files and
invert the port numbers in one file. Then, start them in two separate
shells.
-

import SocketServer
import socket
import threading
import random
from time import sleep

## Network request handler
class MyTCPHandler(SocketServer.StreamRequestHandler):

def handle(self):
self.data = self.rfile.readline().strip()
print "-> RECV: " + self.data + " - Sent by:" +
self.client_address[0]

## Server Thread
class ServerThread(threading.Thread):
def __init__(self, localServer):
threading.Thread.__init__(self)
self.server = SocketServer.TCPServer(localServer,
MyTCPHandler)

def run(self):
self.server.serve_forever()

## Client Thread
class ClientThread(threading.Thread):

def __init__(self, remoteServer):
threading.Thread.__init__(self)
self.remoteServer = remoteServer

def run(self):
cycle = 0
while cycle < 1000:

chance = random.random()
if(chance < 0.01):

randomNumber = int(random.random() * 1000)
message = str(randomNumber) + " from remote cycle " +
str(cycle)

try:
sock = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
sock.connect(self.remoteServer)
sock.send(message + "\n")
sock.close()
print("SENT ->: "+str(randomNumber)+ " by local
cycle "+str(cycle))
except:
print("Failed to send number on cycle "+str
(cycle))

cycle += 1
sleep(0.01)

## Simulating local/remote servers with different ports
localServer = ("localhost", )
remoteServer = ("localhost", 1)

serverThread = ServerThread(localServer)
serverThread.setDaemon(True)
serverThread.start()

clientThread = ClientThread(remoteServer)
clientThread.start()


---


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


Re: Bidirectional Networking

2008-12-13 Thread Emanuele D'Arrigo
On Dec 13, 12:08 am, "James Mills" 
wrote:
> Just as a matter of completeness for my own suggestion, here
> is my implementation of your code (using circuits):

It's longer! But I bet is a little bit more resilient against all
sorts of problems that arise while using network connections.

Well, thank you for that. The code I posted in this thread it was just
a test to understand how it all works and how it all works with python
out of the box. When I get to write the actual application I might end
up using circuits instead!

Thank you again!

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


zip a created file

2008-12-13 Thread frendy zhang

if form.accepts(request.vars,session): for table in db.tables:  
   rows=db(db[table].id).select() print rows 
open(str(os.sep).join([os.getcwd(), 'applications', 
request.application, 'databases', 
table+'.csv']),'w').write(str(db(db[table].id).select ())) 
 
where and what should i put the zip code to zip the file created above? thanks 
in advance
_
Easily edit your photos like a pro with Photo Gallery.
http://get.live.com/photogallery/overview--
http://mail.python.org/mailman/listinfo/python-list


encrypt and descrypt a created file

2008-12-13 Thread frendy zhang

if form.accepts(request.vars,session): for table in db.tables:  
   rows=db(db[table].id).select() print rows 
open(str(os.sep).join([os.getcwd(), 'applications', 
request.application, 'databases', 
table+'.csv']),'w').write(str(db(db[table].id).select ())) 
 
 
How can i encrypt and descrypt the created file above??
 
thanks in advance...
_
NEW! Get Windows Live FREE.
http://www.get.live.com/wl/all--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-13 Thread Isaac Gouy
On Dec 12, 6:58 am, [email protected] wrote:
> sturlamolden:
>
> > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3 And
> > most of that magic comes from an implementation of a dynamically typed
> > language (Smalltalk). [...]
> >http://shootout.alioth.debian.org/u32q/benchmark.php?test=all〈=all
>
> That is indeed a nice result, JavaVM has come a long way from the
> first one used for applets. That result comes mostly from the fact
> that this is a test on a 4-core CPU, that is less easy to manage from
> C. You can see that in the single 64-bit core 
> tests:http://shootout.alioth.debian.org/u64/benchmark.php?test=all〈=all


Whether or not it's less easy to manage from C is unclear, but you are
correct to point out few of those C programs have been updated to
exploit quadcore - so the reasonable comparison is with C++.


And the benchmarks game also provides x86 measurements with programs
forced onto a single core which shows GCC ahead

http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=all



> And take a look at the memory used too, up to 34 times higher for the
> JVM on the 4-core CPU.
>
> In the next years people that use low-level languages like C may need
> to invent a new language fitter for multi-core CPUs, able to be used
> on GPUs too (see the OpenCL), less error-prone than C, able to use the
> CPU vector instructions efficiently. (The D language is probably unfit
> for this purpose, because even if it's meant to be a system language,
> I don't think it can be used much to replace C everywhere it's used
> now.) A C+ maybe? :-)
>
> I agree that CPython may quite enjoy having something built-in like
> Psyco, but it's a lot of work for an open source project. Probably
> with 1/3 or 1/2 of the work poured on PyPy you may create that
> improvement for CPython. Maybe PyPy will someday produce some fruit,
> but I think they have used the wrong strategy: instead of trying to
> create something very new that someday will work, it's often better to
> try to improve something that today everybody uses, AND try to be
> useful from almost the very beginning.
>
> Bye,
> bearophile

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


Re: Python is slow

2008-12-13 Thread Isaac Gouy
On Dec 12, 11:41 am, Bruno Desthuilliers
 wrote:
> sturlamolden a écrit :
> (snip)
>
> > Creating a fast implementation of a dynamic language is almost rocket
> > science. But it has been done. There is Stronghold, the fastest
> > version of Smalltalk known to man, on which the Sun Java VM is based.
> > On a recent benchmark Java 6 -server beats C compiled by GCC 4.2.3
>
> cf bearophile's comment on this point (CPU architecture and RAM)
>
> > And
> > most of that magic comes from an implementation of a dynamically typed
> > language (Smalltalk).
>
> Err... Where is _Java_ "dynamic" actually ? A benchmark of _Smalltalk_
> VM vs CPython VM would make more sense.


http://shootout.alioth.debian.org/u32/benchmark.php?test=all&lang=vw&lang2=python


>
> > Second, there are other fast implementations of dynamic languages. The
> > CMUCL and SBCL versions of Common Lisp comes to min; you can see how
> > SBCL does in the same benchmark (CMUCL tends to be even faster).
>
> Could it be that there are some type hints in the lisp versions of the
> source code ?
>
> > So Python is a lot slower than it needs to be.
>
> Please fix it, you're welcome.

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


Re: Bidirectional Networking

2008-12-13 Thread Emanuele D'Arrigo
Hey Bryan, thank you for your reply!

On Dec 13, 3:51 am, Bryan Olson  wrote:
> > Is it possible then to establish both a server and a client in the
> > same application?
>
> Possible, and not all that hard to program, but there's a gotcha.
> Firewalls, including home routers and software firewalls, typically
> default to disallowing connections in the 'wrong' direction. If the
> client initiates all connections, you avoid a world of hassles.

Ah yes, I can see that. Uhm. I have absolutely no idea right now how a
firewall works from a programming point of view and what happens in
normal "residential" circumstances. I.e. it's clear that firewalls are
configured to allow http traffic because I can browse the internet. Is
that done leaving a specific port open? Or does the browser request
the firewall to open a specific port for it and the firewall trust the
browser to handle safely anything that comes through?

I.e. in the case of the code in this thread, would it be the
responsibility of the application to tunnel through the firewall and
listen for connections or would it be the responsibility of the user
to configure the firewall so that the application can receive a
connection?

Thanks for your help!

Manu

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


Re: Need help improving number guessing game

2008-12-13 Thread feba
#!/usr/bin/python
#Py3k, UTF-8

import random

def startup():
print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
global pnum, play, player, p1sc, p2sc
pnum = int(input("1 OR 2 PLAYERS?\n> "))
play = True
player = "P1" #P1 goes first
p1sc = 0 #Number of times...
p2sc = 0 #player guessed before opponent

def setup():
global target, guess, a, b
a = 1
b = 99
target = random.randint(a, b)
guess = 0 #Won't fall between 1 and 99


def playerswap():
global player
if player == "P1":
player = "P2"
else:
player = "P1"

def guessing():
global guess, player, target, play, pnum, p1sc, p2sc, a, b
guess = int(input("[%s-%s]%s>> " % (a, b, player))) #keeps the
user aware of min/max
if guess == target:
if pnum == 1:
print("CONGRATULATIONS!" )
else:
if player == "P1":
p1sc += 1
else:
p2sc += 1
print("CONGRATULATIONS %s! SCORE -- P1:%s P2:%s" %(player,
p1sc, p2sc))

playover = input("PLAY AGAIN? Y/N: ")
if playover.strip().lower() == "y":
play = True
setup()
else:
play = False
elif guess > b:
print("NUMBER MUST BE IN RANGE")
elif guess <= a:
print("NUMBER MUST BE IN RANGE")
elif guess > target:
print("TOO HIGH")
b = guess
else:
print("TOO LOW")
a = guess
if pnum ==2:
playerswap()

startup()
setup()

while play is True:
guessing()


This is what I have so far. better? worse? I'm guessing a mix of the
two. It took me a lot longer to get working, but I think it works
better. I also added a bit that tells you if you go higher or lower
than an already specified too high/low markers; although it doesn't
make you repeat that turn. I'm not sure if all those 'globals' are
bad, but they don't seem like they're something that should be good.
Functionally, it seems to work just fine.
--
http://mail.python.org/mailman/listinfo/python-list


Why %e not in time.strftime directives?

2008-12-13 Thread Leo jay
Any special reasons?

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


Re: Why %e not in time.strftime directives?

2008-12-13 Thread skip

Leo> Any special reasons?

Nobody thought to add it?  Got a patch?

-- 
Skip Montanaro - [email protected] - http://smontanaro.dyndns.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why %e not in time.strftime directives?

2008-12-13 Thread Tim Chase

Any special reasons?


Because it is there (at least on my Debian box)?

  t...@rubbish:~$ python
  Python 2.5.2 (r252:60911, May 28 2008, 08:35:32)
  [GCC 4.2.4 (Debian 4.2.4-1)] on linux2
  Type "help", "copyright", "credits" or "license" for
  more information.

  >>> import time
  >>> time.strftime('%c')
  'Sat Dec 13 09:35:03 2008'
  >>> time.strftime('%e')
  '13'

Taken from[1]

  The full set of format codes supported varies across
  platforms, because Python calls the platform C library's
  strftime() function, and platform variations are common.

So if your underlying C implementation of strftime() supports 
"%e", then Python will.  My guess is that the same applies to 
time.strftime as it does to datetime.strftime


The docs list ones that are fairly cross-platform.  However, it 
would seem that not all platforms support "%e"



-tkc


[1]
http://docs.python.org/library/datetime.html#module-datetime




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


Re: Netbeans Early Access and Python3

2008-12-13 Thread vk
Netbeans is a very polished IDE.

I just tried the Python EA plugin, however, and it does not have 3.x
support as of now.
--
http://mail.python.org/mailman/listinfo/python-list


Re: encrypt and descrypt a created file

2008-12-13 Thread Tim Chase

open(str(os.sep).join([
os.getcwd(),
'applications',
request.application,
'databases',
table+'.csv']),'w').write(str(db(db[table].id).select ())) 
 
 
How can i encrypt and descrypt the created file above??


Well, as I was recently admonished (and have come to love), the 
first recommendation is to use the "csv" module for writing CSV 
files.  It deals with oddities like quotation-escaping, and a 
bunch of other details.


However, you want some sort of encryption/decryption method, but 
you don't specify what type.  You can do something simple like


  def encrypt(s):
return s.encode('rot13')
  def decrypt(s):
return s.decode('rot13')
  f = open(filename, 'wb')
  f.write(encrypt(content))
  f.close()
  f = open(filename, 'r')
  content = decrypt(f.read())
  f.close()

It's not very good encryption though ;-)  For better encryption 
see [1] & [2] for the pycrypto module.  It's been a while since 
I've done anything using this module, but the docs are available 
for it and the basic premise is the same (encrypt the content 
before writing, decrypt the content upon reading).  It would help 
to read up on crypto best-practices about storing key-files, 
password-management, etc.


-tkc


[1]
http://www.pycrypto.org

[2]
http://www.amk.ca/python/code/crypto.html



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


Re: Removing None objects from a sequence

2008-12-13 Thread Steven D'Aprano
On Sat, 13 Dec 2008 11:07:53 +, Steven D'Aprano wrote:

> Now, sure, most of the work in Tim's version is executed in fast C code
> instead of slow Python code.

Say what???

I'm sorry, I must have been smoking crack when I wrote that. It does 
nothing of the sort. Tim's version is pure Python.

def deNone2(alist):
alist[:] = [x for x in alist if x is not None]


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


Re: Removing None objects from a sequence

2008-12-13 Thread Steven D'Aprano
On Sat, 13 Dec 2008 06:00:09 -0800, bearophileHUGS wrote:

> Steven D'Aprano:
>> The algorithm is unclear: try explaining what you are doing in English,
>> and see how difficult it is.
> 
> That algorithm is a standard one, and quite clear. Any programmer worth
> his/her/hir salt has to be able to understand that.

I didn't say it can't be understood. But please, if you think it is quite 
clear, go ahead and explain how it works, and how you know the algorithm 
is correct and there are no odd corner cases where it fails. As my comp 
sci lecturer used to say, "prove the algorithm is correct".

Remember, Terry made a specific claim: the algorithm is simpler and 
cleaner than Tim's copy-the-values-that-aren't-None solution. It's not 
just clear, it's significantly clearer:

"No, making a filtered copy that is then copied back before being deleted 
is algorithmically much messier.  My code does the minimum work 
necessary and is algorithmically cleaner."

Do you agree with Terry's claim?


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


Re: Best way of debigging a C extension

2008-12-13 Thread Paul Moore
On 11 Dec, 23:57, Christian Heimes  wrote:
> Paul Moore schrieb:
> > That's what I thought. I was just hoping that using a debug build of
> > an extension would be usable with a standard release build of Python,
> > as that's what will be easy for most people to set up.
>
> A debug build changes large parts of the ABI. Every PyObject struct
> gains additional fields, lots of checks are added to Python's memory
> allocation system and asserts are enabled. Debug extensions have a _d
> suffix for a very good reason. We aren't just trying to make *your* life
> harder. :)

Ah. That's the bit of information I was missing. If the ABI changes,
it's a wonder my hacking of my extension to build in debug mode worked
at all!

I suspect that if I could get distutils to let me specify that it
keeps debug symbols in a release-mode build, I could get what I
needed. But the arcane contortions needed to get distutils to do this
are beyond me :-)

I'll stick with printf - it's served me well enough so far :-)

Thanks for clarifying,
Paul.
--
http://mail.python.org/mailman/listinfo/python-list


[OT] stable algorithm with complexity O(n)

2008-12-13 Thread David Hláčik
Hi guys,

i am really sorry for making offtopic, hope you will not kill me, but
this is for me life important problem which needs to be solved within
next 12 hours..

I have to create stable algorithm for sorting n numbers from interval
[1,n^2] with time complexity O(n) .

Can someone please give me a hint. Would be very very thankful!

Thanks in advance!
D.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Diez B. Roggisch

David Hláčik schrieb:

Hi guys,

i am really sorry for making offtopic, hope you will not kill me, but
this is for me life important problem which needs to be solved within
next 12 hours..

I have to create stable algorithm for sorting n numbers from interval
[1,n^2] with time complexity O(n) .

Can someone please give me a hint. Would be very very thankful!


Unless I grossly miss out on something in computer science 101, the 
lower bound for sorting is O(n * log_2 n). Which makes your task 
impossible, unless there is something to be assumed about the 
distribution of numbers in your sequence.


Who has given you that assignment - a professor? Or some friend who's 
playing tricks on you?


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


Re: zip a created file

2008-12-13 Thread Tino Wildenhain
frendy zhang wrote:
> if form.accepts(request.vars,session):
> for table in db.tables:
> rows=db(db[table].id).select()
> print rows
> open(str(os.sep).join([os.getcwd(), 'applications',
> request.application, 'databases',
> table+'.csv']),'w').write(str(db(db[table].id).select ()))
> 
>  
> where and what should i put the zip code to zip the file created above?
> thanks in advance

You don't? ;) The code is very -crappy- suboptimal... - can you
reformulate the problem first?

Where is request, session coming from? If its a web application,
what are you doing with open() and why this complicated code
instead of just os.path.join() ?

In short, creating a file and zipping and sending to the browser
should not need to create an intermediate file in the file
system. (This also avoids a lot of problems with your approach
above - for example if the same query is put twice the same time...)

Just have a look at the examples in the documentation which come
with the zipfile module.


Cheers
Tino



smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread David Hláčik
> Unless I grossly miss out on something in computer science 101, the lower
> bound for sorting is O(n * log_2 n). Which makes your task impossible,
> unless there is something to be assumed about the distribution of numbers in
> your sequence.

There is n numbers from interval [1 , n^2]
I should do measurement for :
n = 500, 1000, 1500, 2000, ..., 4500, 5000

O(n) means linear complexivity, so complexivity of algorithmus must be
linear, which i have to prove.


>
> Who has given you that assignment - a professor? Or some friend who's
> playing tricks on you?

It is official assignment , by professor from Data Structures &
Algorithms course.

Thanks in advance!
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Dan Upton
On Sat, Dec 13, 2008 at 2:00 PM, David Hláčik  wrote:
>> Unless I grossly miss out on something in computer science 101, the lower
>> bound for sorting is O(n * log_2 n). Which makes your task impossible,
>> unless there is something to be assumed about the distribution of numbers in
>> your sequence.

This is only true for comparison-based sorts.

>
> There is n numbers from interval [1 , n^2]
> I should do measurement for :
> n = 500, 1000, 1500, 2000, ..., 4500, 5000
>
> O(n) means linear complexivity, so complexivity of algorithmus must be
> linear, which i have to prove.
>
>
>>
>> Who has given you that assignment - a professor? Or some friend who's
>> playing tricks on you?
>
> It is official assignment , by professor from Data Structures &
> Algorithms course.
>
> Thanks in advance!
>>
>> Diez
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Look at things like bucket sort and radix sort.  You can also do
tricky things like translating your problem domain by making a fixed
number of linear-time passes without affecting the asymptotic run
time.

(Hopefully that's helpful... don't want to give too much away on a
homework assignment, plus tricky algorithms have never been my strong
suit.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Wojciech Muła
"David Hláčik"  wrote:

> I have to create stable algorithm for sorting n numbers from interval
> [1,n^2] with time complexity O(n) .

Some kind of radix sort or counting sort.  These algo. has O(n) complexity.

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


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Duncan Booth
"Diez B. Roggisch"  wrote:

> David Hláčik schrieb:
>> Hi guys,
>> 
>> i am really sorry for making offtopic, hope you will not kill me, but
>> this is for me life important problem which needs to be solved within
>> next 12 hours..
>> 
>> I have to create stable algorithm for sorting n numbers from interval
>> [1,n^2] with time complexity O(n) .
>> 
>> Can someone please give me a hint. Would be very very thankful!
> 
> Unless I grossly miss out on something in computer science 101, the 
> lower bound for sorting is O(n * log_2 n). Which makes your task 
> impossible, unless there is something to be assumed about the 
> distribution of numbers in your sequence.
> 
> Who has given you that assignment - a professor? Or some friend who's 
> playing tricks on you?
> 
I think you must have fallen asleep during CS101. The lower bound for 
sorting where you make a two way branch at each step is O(n * log_2 n), but 
if you can choose between k possible orderings in a single comparison you 
can get O(n * log_k n).

To beat n * log_2 n just use a bucket sort: for numbers with a known 
maximum you can sort them digit by digit for O(n log_k n), and if you don't 
restrict yourself to decimal then k can be as large as you want, so for the 
problem in question I think you can set k=n and (log_n n)==1 so you get 
O(n)

i.e. digit by digit bucket sort the numbers in base n.

Something like (untested):

n = len(data)
buckets1 = [[] for i in range(n)]
buckets2 = [[] for i in range(n)]

for x in data:
   buckets1[x % n].append(x)

for x in (v for b in buckets1 for v in reversed(b)):
   buckets2[x // n].append(x)

for x in (v for b in buckets2 for v in b):
   print x

All loops are order n (the last two have about 2*n steps).

I lied about the untested:

>>> def f(data):
n = len(data)
buckets1 = [[] for i in range(n)]
buckets2 = [[] for i in range(n)]

for x in data:
   buckets1[x % n].append(x)

for x in (v for b in buckets1 for v in reversed(b)):
   buckets2[x // n].append(x)

for x in (v for b in buckets2 for v in b):
   print x

>>> import random
>>> data = [ random.randint(1,100) for i in range(10)]
>>> f(data)
1
16
30
35
70
70
75
76
82
99
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread MRAB

Diez B. Roggisch wrote:

David Hláčik schrieb:

Hi guys,

i am really sorry for making offtopic, hope you will not kill me, but
this is for me life important problem which needs to be solved within
next 12 hours..

I have to create stable algorithm for sorting n numbers from interval
[1,n^2] with time complexity O(n) .

Can someone please give me a hint. Would be very very thankful!


Unless I grossly miss out on something in computer science 101, the 
lower bound for sorting is O(n * log_2 n). Which makes your task 
impossible, unless there is something to be assumed about the 
distribution of numbers in your sequence.


Who has given you that assignment - a professor? Or some friend who's 
playing tricks on you?


I'm assuming that the numbers are integers. I can think of an O(n) 
algorithm for this particular problem provided that n isn't huge, but if 
it's your assignment then it's up to you to discover it.

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


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Diez B. Roggisch

Duncan Booth schrieb:

"Diez B. Roggisch"  wrote:


David Hlá�ik schrieb:

Hi guys,

i am really sorry for making offtopic, hope you will not kill me, but
this is for me life important problem which needs to be solved within
next 12 hours..

I have to create stable algorithm for sorting n numbers from interval
[1,n^2] with time complexity O(n) .

Can someone please give me a hint. Would be very very thankful!
Unless I grossly miss out on something in computer science 101, the 
lower bound for sorting is O(n * log_2 n). Which makes your task 
impossible, unless there is something to be assumed about the 
distribution of numbers in your sequence.


Who has given you that assignment - a professor? Or some friend who's 
playing tricks on you?


I think you must have fallen asleep during CS101. The lower bound for 
sorting where you make a two way branch at each step is O(n * log_2 n), but 
if you can choose between k possible orderings in a single comparison you 
can get O(n * log_k n).


To beat n * log_2 n just use a bucket sort: for numbers with a known 
maximum you can sort them digit by digit for O(n log_k n), and if you don't 
restrict yourself to decimal then k can be as large as you want, so for the 
problem in question I think you can set k=n and (log_n n)==1 so you get 
O(n)


Thanks. I *totally* forgot about that.

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


Bidrectional Subprocess Communication

2008-12-13 Thread Emanuele D'Arrigo
Hi everybody,

I'm trying to replicate the positive results of the Client/Server
scripts from the thread "Bidirectional Networking", but this time
using a Process/SubProcess architecture.

The SubProcess, acting as a server, is working just fine. But the
Process executing the SubProcess, the client, somehow doesn't hear any
of the standard output from the SubProcess. What am I missing?

Below you can find the two short pieces of code. Thanks for your help!

Manu

---
# serverTest.py
import sys

print("Starting Server!")

while True:
data = sys.stdin.readline().strip()
if(data):
print("SERVER RECV: '" + data + "'")

if(data == "Stop!"):
break

print("Server Stopped!")

---
#clientTest.py

import sys
import threading
from time import sleep
from subprocess import Popen, PIPE

## Server Thread
class ListenerThread(threading.Thread):

def __init__(self, inChannel):
threading.Thread.__init__(self)
self.inChannel = inChannel

def run(self):
while True:
data = self.inChannel.readline().strip()
print("serverTest.py says: " + data)

print("Starting Client!")

server = Popen("python serverTest.py", stdin=PIPE, stdout=PIPE)

listenerThread = ListenerThread(server.stdout)
listenerThread.setDaemon(True)
listenerThread.start()

server.stdin.write("Something very meaningful!\n")
server.stdin.write("Stop!")

print("Client Stopped!")
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parallelizing python code - design/implementation questions

2008-12-13 Thread Philip Semanchuk


On Dec 13, 2008, at 7:00 AM, stdazi wrote:


Hello!

I'm about to parallelize some algorithm that turned out to be too
slow. Before I start doing it, I'd like to hear some suggestions/hints
from you.


Hi stdazi,
If you're communicating between multiple processes with Python, you  
might find my IPC extensions useful. They're much less sophisticated  
than multiprocessing; they just give access to IPC semaphores and  
shared memory (no message queues yet) on Unix.


POSIX IPC:
http://semanchuk.com/philip/posix_ipc/

System V IPC:
http://semanchuk.com/philip/sysv_ipc/

More System V IPC:
http://nikitathespider.com/python/shm/

The System V IPC extensions are similar; the latter is older and  
better tested but won't be developed anymore. The former is newer, has  
a couple more features and is the future of System V IPC w/Python, at  
least as far as my work is concerned.


Good luck
Philip





The algorithm essentially works like this:  There is a iterator
function "foo" yielding a special kind permutation of [1,n]. The
main program then iterates through this permutations calculating some
proprieties. Each time a calculation ends, a counter is incremented
and each time the counter is divisible by 100, the current progress is
printed.

The classical idea is to spawn m threads and use some global lock when
calling the instance of the iterator + one global lock for
incrementing the progress counter. Is there any better way? I'm
especially concerned with performance degradation due to locking - is
there any way to somehow avoid it?

I've also read about the `multiprocessing' module and as far as I've
understood :


permutation = foo()
threadlst = []
for i in xrange(m) :
  p = Process(target=permutation.next)
  threadlst.append(p)
  p.start()
for p in threadlst:
  p.join()


should do the trick. Am I right? Is there any better way other than
this?
--
http://mail.python.org/mailman/listinfo/python-list


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


Re: var or inout parm?

2008-12-13 Thread sturlamolden
On 13 Des, 02:20, Hrvoje Niksic  wrote:

> > tmp = mytuple.__getitem__(0)
> > tmp = tmp.__iadd__(1)
> > mytuple.__setitem__(0, tmp) # should this always raise an exception?
>
> What do you mean by "a sane parser"?  This is exactly what happens in
> current Python.  

Yes, but Steve Holden was suggesting mytuple.__iadd__ would be
invoked.

> The decision to also rebind
> the result of __i*__ methods continues to baffle me.  

Python methods always have a return value, even those that seem to do
not - they silently return None. Thus, __iadd__ must return self to
avoid rebinding to None.


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


Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread John Machin

Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = u'\u9876'
>>> x
u'\u9876'

# As expected

Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
(Intel)] on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = '\u9876'
>>> x
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\python30\lib\io.py", line 1491, in write
b = encoder.encode(s)
  File "C:\python30\lib\encodings\cp850.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in
position
1: character maps to 

# *NOT* as expected (by me, that is)

Is this the intended outcome?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Problems running on HP Intel duo core machine

2008-12-13 Thread Aaron Brady
On Dec 11, 3:16 pm, jim-on-linux  wrote:
> Aaron,
>
> The TraceBack is :
>
> TraceBack:
> File win32ui.pyc, line 12, in 
> File win32ui.pyc Line 10, in _load
> ImportError: DLL Load Failed: The specified module
> could not be found.
snip

> > Both modules 'win32api.pyd'  and win32ui.pyd are in
> > the same directory.
>
> > Below is a copy of the win32ui.py module. The only
> > difference between this and win32api.py module is
> > the name that is installed when creating the path.
>
> > def __load():
> >     import imp, os, sys
> >     try:
> >         dirname =
> > os.path.dirname(__loader__.archive) except
> > NameError:
> >         dirname = sys.prefix
> >     path = os.path.join(dirname, 'win32ui.pyd')
> >     #print "py2exe extension module", __name__,
> > "->", path
> >     mod = imp.load_dynamic(__name__, path)
> > ##    mod.frozen = 1
> > __load()
> > del __load
snip

'load_dynamic' help says this:

"(Note: using shared libraries is highly system dependent, and not all
systems support it.)"

You can try this:  create a bare-bones shared library, 'temp_load.pyd'
perhaps, place it in the folder, and create 'temp_load.py' there too,
as follows:

import imp
imp.load_dynamic( 'temp_load', 'temp_load.pyd' )

That will tell us if the problem is Python or win32ui.
--
http://mail.python.org/mailman/listinfo/python-list


curses and refreshing problem

2008-12-13 Thread Karlo Lozovina
Hi, I'm trying to implement text output interface, something similar to 
wget, using curses module. There are just two things I can't find out how 
to do: prevent curses from clearing the terminal when starting my program, 
and leaving my output after the program closes. Any way to do this with 
curses?

Thanks...


-- 
 ___Karlo Lozovina - Mosor
|   |   |.-.-. web: http://www.mosor.net || ICQ#: 10667163
|   ||  _  |  _  | Parce mihi domine quia Dalmata sum.
|__|_|__||_|_|
--
http://mail.python.org/mailman/listinfo/python-list


Re: var or inout parm?

2008-12-13 Thread sturlamolden
On 13 Des, 21:26, sturlamolden  wrote:

> Python methods always have a return value, even those that seem to do
> not - they silently return None. Thus, __iadd__ must return self to
> avoid rebinding to None.

Except for immutable types, for which __iadd__ must return a new
instance.




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


Re: var or inout parm?

2008-12-13 Thread Aaron Brady
On Dec 12, 7:31 am, Steve Holden  wrote:
> sturlamolden wrote:
> > On Dec 12, 1:56 pm, sturlamolden  wrote:
>
> >> That is because integers are immutable. When x += 1 is done on an int,
> >> there will be a rebinding. But try the same on say, a numpy array, and
> >> the result will be different:
snip

> This was all thrashed out exhaustively in the still-feared call
> semantics thread. Yes, augmented operations work differently on mutable
> and immutable objects. Nothing to see here, move right along ...

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


Re: Python is slow

2008-12-13 Thread sturlamolden
On 10 Des, 19:42, cm_gui  wrote:

> And it is not just this Python site that is slow. There are many many
> Python sites which are very slow. And please don’t say that it could
> be the web hosting or the server which is slow — because when so many
> Python sites are slower than PHP sites, it couldn’t be the web
> hosting.   Also, Zope/Plone is even slower.
>
> Python is slow. Very slow.


By the way... I know of a very slow Python site called YouTube.com. In
fact, it is so slow that nobody ever uses it.









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


Re: stable algorithm with complexity O(n)

2008-12-13 Thread Aaron Brady
On Dec 13, 1:17 pm, Duncan Booth  wrote:
> "Diez B. Roggisch"  wrote:
>
>
>
> > David Hláčik schrieb:
> >> Hi guys,
>
> >> i am really sorry for making offtopic, hope you will not kill me, but
> >> this is for me life important problem which needs to be solved within
> >> next 12 hours..
>
> >> I have to create stable algorithm for sorting n numbers from interval
> >> [1,n^2] with time complexity O(n) .
>
> >> Can someone please give me a hint. Would be very very thankful!
>
> > Unless I grossly miss out on something in computer science 101, the
> > lower bound for sorting is O(n * log_2 n). Which makes your task
> > impossible, unless there is something to be assumed about the
> > distribution of numbers in your sequence.
>
> > Who has given you that assignment - a professor? Or some friend who's
> > playing tricks on you?
>
> I think you must have fallen asleep during CS101. The lower bound for
> sorting where you make a two way branch at each step is O(n * log_2 n), but
> if you can choose between k possible orderings in a single comparison you
> can get O(n * log_k n).
>
> To beat n * log_2 n just use a bucket sort: for numbers with a known
> maximum you can sort them digit by digit for O(n log_k n), and if you don't
> restrict yourself to decimal then k can be as large as you want, so for the
> problem in question I think you can set k=n and (log_n n)==1 so you get
> O(n)

Minor detail: with k= n, you have log_n (n^2)= 2, so you get O(2n)= O
(n).  Same answer.

The generic sort theorems also assume you can compare arbitrarily
large numbers in constant time, which isn't true.  That is, for any
given machine, there exist numbers that you can't compare on them in
constant time.  But with a known upper bound k, you can just use a k-
bit machine.

So, what's the group policy on helping with homework?  
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread Vlastimil Brom
2008/12/13 John Machin :
>
> Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
 x = u'\u9876'
 x
> u'\u9876'
>
> # As expected
>
> Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
> (Intel)] on win 32
> Type "help", "copyright", "credits" or "license" for more information.
 x = '\u9876'
 x
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "C:\python30\lib\io.py", line 1491, in write
>b = encoder.encode(s)
>  File "C:\python30\lib\encodings\cp850.py", line 19, in encode
>return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in
> position
> 1: character maps to 
>
> # *NOT* as expected (by me, that is)
>
> Is this the intended outcome?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

I also found this a bit surprising, but it seems to be the intended
behaviour (on a non-unicode console)

http://docs.python.org/3.0/whatsnew/3.0.html
"PEP 3138: The repr() of a string no longer escapes non-ASCII
characters. It still escapes control characters and code points with
non-printable status in the Unicode standard, however."

I get the same error in windows cmd, (Idle prints the respective glyph
correctly).
To get the old behaviour of repr, one can use ascii, I suppose.

Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.

>>> repr('\u9876')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python30\lib\io.py", line 1491, in write
b = encoder.encode(s)
  File "C:\Python30\lib\encodings\cp852.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in position
2: character maps to 
>>> '\u9876'.encode("unicode-escape")
b'\\u9876'
>>> ascii('\u9876')
"'\\u9876'"
>>>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread Chris Rebert
On Sat, Dec 13, 2008 at 12:28 PM, John Machin  wrote:
>
> Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
 x = u'\u9876'
 x
> u'\u9876'
>
> # As expected
>
> Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
> (Intel)] on win 32
> Type "help", "copyright", "credits" or "license" for more information.
 x = '\u9876'
 x
> Traceback (most recent call last):
>  File "", line 1, in 
>  File "C:\python30\lib\io.py", line 1491, in write
>b = encoder.encode(s)
>  File "C:\python30\lib\encodings\cp850.py", line 19, in encode
>return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in
> position
> 1: character maps to 
>
> # *NOT* as expected (by me, that is)
>
> Is this the intended outcome?

When Python tries to display the character, it must first encode it
because IO is done in bytes, not Unicode codepoints. When it tries to
encode it in CP850 (apparently your system's default encoding judging
by the traceback), it unsurprisingly fails (CP850 is an old Western
Europe codec, which obviously can't encode an Asian character like the
one in question). To signal that failure, it raises an exception, thus
the error you see.
This is intended behavior. Either change your default system/terminal
encoding to one that can handle such characters or explicitly encode
the string and use one of the provided options for dealing with
unencodable characters.

Also, please don't call it a "crash" as that's very misleading. The
Python interpreter didn't dump core, an exception was merely thrown.
There's a world of difference.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python is slow

2008-12-13 Thread Benjamin Kaplan
On Sat, Dec 13, 2008 at 3:35 PM, sturlamolden  wrote:

> On 10 Des, 19:42, cm_gui  wrote:
>
> > And it is not just this Python site that is slow. There are many many
> > Python sites which are very slow. And please don't say that it could
> > be the web hosting or the server which is slow — because when so many
> > Python sites are slower than PHP sites, it couldn't be the web
> > hosting.   Also, Zope/Plone is even slower.
> >
> > Python is slow. Very slow.
>
>
> By the way... I know of a very slow Python site called YouTube.com. In
> fact, it is so slow that nobody ever uses it.
>


And there's also a web crawler written in Python, used by a site called
Google, that's so slow that the search engine gives very few results.


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


Re: ActivePython 2.6.1.1 and 3.0.0.0 released!

2008-12-13 Thread Trent Mick

Kay Schluehr wrote:

On 13 Dez., 00:16, Trent Mick  wrote:


Note that currently PyWin32 is not included in ActivePython 3.0.


Is there any activity in this direction?


The PyWin32 CVS tree is getting checkins from Mark Hammond and Roger 
Upole with a py3k tag. I'm not sure how close they are currently.


Trent

--
Trent Mick
trentm at activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: stable algorithm with complexity O(n)

2008-12-13 Thread Benjamin Kaplan
2008/12/13 Aaron Brady 

> On Dec 13, 1:17 pm, Duncan Booth  wrote:
> > "Diez B. Roggisch"  wrote:
> >
> >
> >
> > > David Hláčik schrieb:
> > >> Hi guys,
> >
> > >> i am really sorry for making offtopic, hope you will not kill me, but
> > >> this is for me life important problem which needs to be solved within
> > >> next 12 hours..
> >
> > >> I have to create stable algorithm for sorting n numbers from interval
> > >> [1,n^2] with time complexity O(n) .
> >
> > >> Can someone please give me a hint. Would be very very thankful!
> >
> > > Unless I grossly miss out on something in computer science 101, the
> > > lower bound for sorting is O(n * log_2 n). Which makes your task
> > > impossible, unless there is something to be assumed about the
> > > distribution of numbers in your sequence.
> >
> > > Who has given you that assignment - a professor? Or some friend who's
> > > playing tricks on you?
> >
> > I think you must have fallen asleep during CS101. The lower bound for
> > sorting where you make a two way branch at each step is O(n * log_2 n),
> but
> > if you can choose between k possible orderings in a single comparison you
> > can get O(n * log_k n).
> >
> > To beat n * log_2 n just use a bucket sort: for numbers with a known
> > maximum you can sort them digit by digit for O(n log_k n), and if you
> don't
> > restrict yourself to decimal then k can be as large as you want, so for
> the
> > problem in question I think you can set k=n and (log_n n)==1 so you get
> > O(n)
>
> Minor detail: with k= n, you have log_n (n^2)= 2, so you get O(2n)= O
> (n).  Same answer.
>
> The generic sort theorems also assume you can compare arbitrarily
> large numbers in constant time, which isn't true.  That is, for any
> given machine, there exist numbers that you can't compare on them in
> constant time.  But with a known upper bound k, you can just use a k-
> bit machine.
>
> So, what's the group policy on helping with homework?   rhetorical>


The policy is "don't do the homework for them". It's more for people who
post "write a O(n) sort algorithm for integers in a range [0, n^2]" with a
subject of "URGENT: RESPOND QUICKLY". The OP asked for advice on this
problem, not for someone to give him the algorithm.
--
http://mail.python.org/mailman/listinfo/python-list


Re: stable algorithm with complexity O(n)

2008-12-13 Thread Duncan Booth
Aaron Brady  wrote:

>So, what's the group policy on helping with homework?   rhetorical>

In my book anyone who is dumb enough to ask for homework help on a 
newsgroup and doesn't acknowledge that when they hand in their answer 
deserves whatever they get. Oh, and of course there are 2 deliberate error 
in the 'solution' I posted so they're not going to get full marks if they 
simply reuse it. (If there are more than 2 errors then at least one of them 
is not deliberate.)

That's assuming the teacher is savvy enough to keep an eye on the obvious 
sources for quick answers.
--
http://mail.python.org/mailman/listinfo/python-list


pypi package dates

2008-12-13 Thread sokol
Am I missing something? There are no release dates for packages in
pypi.
One cannot have an idea how current the package is...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread John Machin
On Dec 14, 8:07 am, "Chris Rebert"  wrote:
> On Sat, Dec 13, 2008 at 12:28 PM, John Machin  wrote:
>
> > Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
> > (Intel)] on win32
> > Type "help", "copyright", "credits" or "license" for more information.
>  x = u'\u9876'
>  x
> > u'\u9876'
>
> > # As expected
>
> > Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
> > (Intel)] on win 32
> > Type "help", "copyright", "credits" or "license" for more information.
>  x = '\u9876'
>  x
> > Traceback (most recent call last):
> >  File "", line 1, in 
> >  File "C:\python30\lib\io.py", line 1491, in write
> >    b = encoder.encode(s)
> >  File "C:\python30\lib\encodings\cp850.py", line 19, in encode
> >    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
> > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876' in
> > position
> > 1: character maps to 
>
> > # *NOT* as expected (by me, that is)
>
> > Is this the intended outcome?
>
> When Python tries to display the character, it must first encode it
> because IO is done in bytes, not Unicode codepoints. When it tries to
> encode it in CP850 (apparently your system's default encoding judging
> by the traceback), it unsurprisingly fails (CP850 is an old Western
> Europe codec, which obviously can't encode an Asian character like the
> one in question). To signal that failure, it raises an exception, thus
> the error you see.
> This is intended behavior.

I see. That means that the behaviour in Python 1.6 to 2.6 (i.e.
encoding the text using the repr() function (as then defined) was not
intended behaviour?

> Either change your default system/terminal
> encoding to one that can handle such characters or explicitly encode
> the string and use one of the provided options for dealing with
> unencodable characters.

You are missing the point. I don't care about the visual
representation. What I care about is an unambiguous representation
that can be used when communicating about problems across cultures/
networks/mail-clients/news-readers ... the sort of problems that are
initially advised as "I got this UnicodeEncodeError" and accompanied
by no data or garbled data.

> Also, please don't call it a "crash" as that's very misleading. The
> Python interpreter didn't dump core, an exception was merely thrown.

"spew nonsense on the screen and then stop" is about as useful and as
astonishing as "dump core".

core? You mean like ferrite doughnuts on a wire trellis? I thought
that went out of fashion before cp850 was invented :-)

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


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Arnaud Delobelle
"David Hláčik"  writes:

> Hi guys,
>
> i am really sorry for making offtopic, hope you will not kill me, but
> this is for me life important problem which needs to be solved within
> next 12 hours..
>
> I have to create stable algorithm for sorting n numbers from interval
> [1,n^2] with time complexity O(n) .
>
> Can someone please give me a hint. Would be very very thankful!
>
> Thanks in advance!
> D.

I don't have an algorithm but I have an implementation :)

def sort2(numbers):
"sort n positive integers in O(n) provided that they are all < n^2"
N = len(numbers)
units = [[] for i in xrange(N)]
tens = [[] for i in xrange(N)]
for n in numbers:
units[n % N].append(n)
for l in units:
for n in l:
tens[n / N].append(n)
return [n for l in tens for n in l]

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


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread Martin v. Löwis
>> This is intended behavior.
> 
> I see. That means that the behaviour in Python 1.6 to 2.6 (i.e.
> encoding the text using the repr() function (as then defined) was not
> intended behaviour?

Sure. This behavior has not changed. It still uses repr().

Of course, the string type has changed in 3.0, and now uses a different
definition of repr.

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] Python 2.4.6 and 2.5.3, release candidate 1

2008-12-13 Thread Martin v. Löwis
On behalf of the Python development team and the Python community, I'm
happy to announce the release candidates of Python 2.4.6 and 2.5.3.

2.5.3 is the last bug fix release of Python 2.5. Future 2.5.x releases
will only include security fixes. According to the release notes, over
100 bugs and patches have been addressed since Python 2.5.1, many of
them improving the stability of the interpreter, and improving its
portability.

2.4.6 includes only a small number of security fixes. Python 2.6 is
the latest version of Python, we're making this release for people who
are still running Python 2.4.

See the release notes at the website (also available as Misc/NEWS in
the source distribution) for details of bugs fixed; most of them prevent
interpreter crashes (and now cause proper Python exceptions in cases
where the interpreter may have crashed before).

Assuming no major problems crop up, a final release of Python 2.4.6
and 2.5.3 will follow in about a week's time.

For more information on Python 2.4.6 and 2.5.3, including download
links for various platforms, release notes, and known issues, please
see:

http://www.python.org/2.4.6
http://www.python.org/2.5.3

Highlights of the previous major Python releases are available
from the Python 2.5 page, at

http://www.python.org/2.4/highlights.html
http://www.python.org/2.5/highlights.html

Enjoy this release,
Martin

Martin v. Loewis
[email protected]
Python Release Manager
(on behalf of the entire python-dev team)
--
http://mail.python.org/mailman/listinfo/python-list


1000 Earn Dollars $$$

2008-12-13 Thread [email protected]
"How To Make $1,000,000 THIS YEAR With our Online Business"
--
http://mail.python.org/mailman/listinfo/python-list


http://1000earndollars.blogspot.com/

2008-12-13 Thread [email protected]
"How To Make $1,000,000 THIS YEAR With our Online Business"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread John Machin
On Dec 14, 9:20 am, "Martin v. Löwis"  wrote:
> >> This is intended behavior.
>
> > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e.
> > encoding the text using the repr() function (as then defined) was not
> > intended behaviour?
>
> Sure.

"Sure" as in "sure, it was not intended behaviour"?

> This behavior has not changed. It still uses repr().
>
> Of course, the string type has changed in 3.0, and now uses a different
> definition of repr.

So was the above-reported non-crash consequence of the change of
definition of repr intended?

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


Re: Bidirectional Networking

2008-12-13 Thread Bryan Olson

Emanuele D'Arrigo wrote:

Hey Bryan, thank you for your reply!

Bryan Olson wrote:

Is it possible then to establish both a server and a client in the
same application?

Possible, and not all that hard to program, but there's a gotcha.
Firewalls, including home routers and software firewalls, typically
default to disallowing connections in the 'wrong' direction. If the
client initiates all connections, you avoid a world of hassles.


Ah yes, I can see that. Uhm. I have absolutely no idea right now how a
firewall works from a programming point of view and what happens in
normal "residential" circumstances. I.e. it's clear that firewalls are
configured to allow http traffic because I can browse the internet. Is
that done leaving a specific port open? Or does the browser request
the firewall to open a specific port for it and the firewall trust the
browser to handle safely anything that comes through?


Software firewalls will often simply refuse incoming connections. The 
basic protection of the garden-variety home router comes from "network 
address translation" (NAT), in which case TCP connections initiated from 
the inside will generally work, regardless of port, and incoming 
connections will fail.


Internet server farms often enforce the other side of the client-side 
policy, with firewalls configured to disallow outgoing initiation of 
connections.


If the application need to work in restrictive environments where 
firewalls only pass known protocols, a popular approach to build the 
application protocol on top of HTTP, with all the required standard 
headers and a new content-type.



I.e. in the case of the code in this thread, would it be the
responsibility of the application to tunnel through the firewall and
listen for connections 


I'm not clear on what that means.


or would it be the responsibility of the user
to configure the firewall so that the application can receive a
connection?


That can be a huge hassle. The first choice is for the application to 
conform to popular firewall policies, so no special configuration is 
required.



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


Re: Bidirectional Networking

2008-12-13 Thread Emanuele D'Arrigo
On Dec 13, 11:13 pm, Bryan Olson  wrote:
> Software firewalls will often simply refuse incoming connections. The
> basic protection of the garden-variety home router comes from "network
> address translation" (NAT), in which case TCP connections initiated from
> the inside will generally work, regardless of port, and incoming
> connections will fail.

Ok, I think I'm getting the picture here. So this means that in most
circumstances where the data flow from the server is frequent the
client initiates the connection, usually requests some initial data
and keeps polling the server periodically, issuing new requests. In
this context can the client simply keep the connection alive and
listen for new data from the server coming at any time rather than
actively issuing requests? Are there drawbacks to this strategy? I.e.
is there a limit to the number of simultaneous connections a server
can keep alive? I've noticed that the socket pages mention a 5
connections limit. Is that it? What if I want to make a virtual room
with 20 people connected simultaneously?

> > or would it be the responsibility of the user
> > to configure the firewall so that the application can receive a
> > connection?
>
> That can be a huge hassle. The first choice is for the application to
> conform to popular firewall policies, so no special configuration is
> required.

I agree, I'd rather have the user do nothing in this regard. I'm just
wondering how it's done with data intensive application where the
server needs to send new data to the client frequently. Does the
client just keep the connection live at all time for the server to
send stuff or does the client continuously open, sends a request,
receives data and closes the connection every time? Here I'm thinking
about an online game, with 100 players moving their avatars. Does the
client requests their position nearly every frame?

Manu


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


subprocess to C program

2008-12-13 Thread Aaron Brady
Hi,

I am writing a C process and I want to read data from a file that I
write to in Python.  I'm creating a pipe in Python, passing it to the
C process, and calling '_read'.  It gives me error 9, bad file number.

Python code:

import subprocess as s, os
r, w= os.pipe( )
os.write( w, 'abcdefghij\n' )
a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working
\try_start', '%i'%r, '%i'%w ] )

C code:

char buf[ 16 ];
memset( buf, 0, 16 );
int readfd= atoi( argv[ 1 ] );
int ct= _read( readfd, buf, 15 );
printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf );

Output:

'_read -1 3 9'

meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
to be 11 at this point.  Thanks in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess to C program

2008-12-13 Thread MRAB

Aaron Brady wrote:

Hi,

I am writing a C process and I want to read data from a file that I
write to in Python.  I'm creating a pipe in Python, passing it to the
C process, and calling '_read'.  It gives me error 9, bad file number.

Python code:

import subprocess as s, os
r, w= os.pipe( )
os.write( w, 'abcdefghij\n' )
a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working
\try_start', '%i'%r, '%i'%w ] )

C code:

char buf[ 16 ];
memset( buf, 0, 16 );
int readfd= atoi( argv[ 1 ] );
int ct= _read( readfd, buf, 15 );
printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf );

Output:

'_read -1 3 9'

meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
to be 11 at this point.  Thanks in advance.


It looks like the ids aren't system global.
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess to C program

2008-12-13 Thread Grant Edwards
On 2008-12-14, MRAB  wrote:

>> I am writing a C process and I want to read data from a file that I
>> write to in Python.  I'm creating a pipe in Python, passing it to the
>> C process, and calling '_read'.  It gives me error 9, bad file number.
>> 
>> Python code:
>> 
>> import subprocess as s, os
>> r, w= os.pipe( )
>> os.write( w, 'abcdefghij\n' )
>> a= s.Popen( [ r'C:\Documents and Settings\usr\Desktop\working
>> \try_start', '%i'%r, '%i'%w ] )
>> 
>> C code:
>> 
>> char buf[ 16 ];
>> memset( buf, 0, 16 );
>> int readfd= atoi( argv[ 1 ] );
>> int ct= _read( readfd, buf, 15 );
>> printf( "\n\n'_read %i %i %i': %s\n", ct, readfd, errno, buf );
>> 
>> Output:
>> 
>> '_read -1 3 9'
>> 
>> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
>> to be 11 at this point.  Thanks in advance.
>> 
> It looks like the ids aren't system global.

They certainly aren't in Unix: Their a property of the process.

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


1 or 1/0 doesn't raise an exception

2008-12-13 Thread Daniel Fetchinson
Is it a feature that

1 or 1/0

returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale?


-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Re: 1 or 1/0 doesn't raise an exception

2008-12-13 Thread Wojciech Muła
"Daniel Fetchinson"  wrote:

> Is it a feature that
> 
> 1 or 1/0
> 
> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale?

See: http://en.wikipedia.org/wiki/Short-circuit_evaluation
--
http://mail.python.org/mailman/listinfo/python-list


Re: 1 or 1/0 doesn't raise an exception

2008-12-13 Thread Tim Chase

Is it a feature that

1 or 1/0

returns 1 and doesn't raise a ZeroDivisionError? If so, what's the rationale?


Yes, it's a feature:

http://en.wikipedia.org/wiki/Short-circuit_evaluation

When you have "True or False", you know it's true by the time 
you've got the first piece, so there's no need to evaluate the 
2nd piece.  The opposite is helpful too:


  lst = [some list or an empty list]
  ...
  if lst and lst[0] == 42:

This ensures that the "lst[0]" doesn't fail if lst is empty, 
because lst evaluating to false (an empty list) short-circuits 
preventing the evaluation of "lst[0]".


-tkc


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


Re: Bidirectional Networking

2008-12-13 Thread Brian Allen Vanderburg II

[email protected] wrote:

On Dec 13, 11:13 pm, Bryan Olson  wrote:
  

Software firewalls will often simply refuse incoming connections. The
basic protection of the garden-variety home router comes from "network
address translation" (NAT), in which case TCP connections initiated from
the inside will generally work, regardless of port, and incoming
connections will fail.



Ok, I think I'm getting the picture here. So this means that in most
circumstances where the data flow from the server is frequent the
client initiates the connection, usually requests some initial data
and keeps polling the server periodically, issuing new requests. In
this context can the client simply keep the connection alive and
listen for new data from the server coming at any time rather than
actively issuing requests? Are there drawbacks to this strategy? I.e.
is there a limit to the number of simultaneous connections a server
can keep alive? I've noticed that the socket pages mention a 5
connections limit. Is that it? What if I want to make a virtual room
with 20 people connected simultaneously?
  


I've done some network programming not much.  I think if you need to 
receive update from a server frequently a constant connection would be 
better than connect-request-disconnect.  As for the backlog (5), this 
doesn't mean that you can only have a maximum of 5 established 
connections.  Each established connection gets a new socket object.  But 
what I think it means is that during the listen for an incoming 
connection on the listening socket, if multiple connection attempts are 
coming in at one time it can keep a backlog of up to 5 of these 
connection attempts for that individual socket.



Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: PyQt: Pulling Abstract Item Data from Mime Data using Drag and Drop.

2008-12-13 Thread Mudcat
On Dec 12, 6:17 pm, David Boddie  wrote:
> That's correct, retrieveData() is a protected function in C++ and the
> QMimeData object was created by the framework, not you, in this case.

Ah, well that explains it. Figured as much but was hoping maybe I was
trying to access it incorrectly.


> You could use the data() method to get the serialized data then try to
> extract the list item-by-item using the QDataStream class, or perhaps
> PyQt has a convenience function to unpack the items.

I tried to get info back using data() but kept getting null values.
Same goes for the items() function which is fed with mimeData and is
supposed to return a list. From the documentation it appeared that was
supposed to be the middle-man to re-convert the data. I know the data
existed because I could drag/drop elements from one treeWidget to
another but still couldn't get data back from the target widget.


> Alternatively - and this is a bit speculative - perhaps you can copy
> the data to another QMimeData object which you have created, and use
> its retrieveData() method to retrieve the items.

I started down the path of creating my own MimeType but then realized
it was quicker to just override the drop() function and grab the
selected items from the source widget, just letting the mime data
disappear into the ether. A little klugey but deadline is fast
approaching. However I'll give the pyqt mailing list a shot. I didn't
know there was one just for pyqt.

Thanks for all the help,
Marc



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


Re: subprocess to C program

2008-12-13 Thread Aaron Brady
On Dec 13, 7:51 pm, Grant Edwards  wrote:
> On 2008-12-14, MRAB  wrote:
>
>
>
> >> I am writing a C process and I want to read data from a file that I
> >> write to in Python.  I'm creating a pipe in Python, passing it to the
> >> C process, and calling '_read'.  It gives me error 9, bad file number.
snip
> >> meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
> >> to be 11 at this point.  Thanks in advance.
>
> > It looks like the ids aren't system global.
>
> They certainly aren't in Unix: Their a property of the process.
>
> --
> Grant

I'm not on Unix.  It has to be possible somehow.  Do I need to set
permissions on the IDs?  Are Stdin and Stdout my only options?  Or
does Popen prevent sharing IDs somehow?
--
http://mail.python.org/mailman/listinfo/python-list


Re: 1 or 1/0 doesn't raise an exception

2008-12-13 Thread r
These are just the kind of things that make Python so beautiful ;)
Thanks Guido!
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess to C program

2008-12-13 Thread MRAB

Aaron Brady wrote:

On Dec 13, 7:51 pm, Grant Edwards  wrote:

On 2008-12-14, MRAB  wrote:




I am writing a C process and I want to read data from a file that I
write to in Python.  I'm creating a pipe in Python, passing it to the
C process, and calling '_read'.  It gives me error 9, bad file number.

snip

meaning that 'ct' is -1, 'readfd' is 3, and 'errno' is 9.  I want 'ct'
to be 11 at this point.  Thanks in advance.

It looks like the ids aren't system global.

They certainly aren't in Unix: Their a property of the process.

--
Grant


I'm not on Unix.  It has to be possible somehow.  Do I need to set
permissions on the IDs?  Are Stdin and Stdout my only options?  Or
does Popen prevent sharing IDs somehow?


You'd be better off using sockets.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] stable algorithm with complexity O(n)

2008-12-13 Thread Steven D'Aprano
On Sat, 13 Dec 2008 19:17:41 +, Duncan Booth wrote:

> I think you must have fallen asleep during CS101. The lower bound for
> sorting where you make a two way branch at each step is O(n * log_2 n),
> but if you can choose between k possible orderings in a single
> comparison you can get O(n * log_k n).

I think you might have been sleeping through Maths 101 :-)

The difference between log_2 N and log_k N is a constant factor (log_2 k) 
and so doesn't effect the big-oh complexity.


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


Re: 1 or 1/0 doesn't raise an exception

2008-12-13 Thread Benjamin Kaplan
Not that I'm against promoting Python, but most languages have support for
short circuit evaluation. That's why you usually use && and || in C, C++, C#
and Java- & and | will always evaluate both sides. Short circuit evaluation
is what allows you to write things like "if foo is not None and
foo.isTrue()".


On Sat, Dec 13, 2008 at 9:57 PM, r  wrote:

> These are just the kind of things that make Python so beautiful ;)
> Thanks Guido!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need help improving number guessing game

2008-12-13 Thread James Stroud

feba wrote:

This is what I have so far. better? worse?


Much better. I didn't check if it works. But you need to figure out a 
way to give up on your reliance on global variables. They will end up 
stifling you in the long run when you move to substantial projects.


Also, you should start moving the nested if: then: blocks to functions.

Finally, you should limit your lines to no more than 80 chars. I do 71. 
Don't be afraid to use transient variables to help.


Be assured that it takes on special intelligence to write unintelligible 
code at will. Also be assured that fitting everything on one line is not 
a good way to save time.


Aim for clarity.

If you want to start off on the right foot, you'll grind on your 
guessing game until all variables are insulated within local scope and 
the logic of the program becomes apparent from its architecture as a 
collection of functions.


This is an example of how to combine these concepts:


def update_scores(player, p1sc, p2sc):
  if player == "P1":
plsc +=1
  else:
p2sc +=1
  tmplt = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s"
  print(tmplt % (player, p1sc, p2sc))
  return p1sc, p2sc

p1sc, p2sc = update_scores(player, p1sc, p2sc)


Finally, put comments on their own lines. Google "python style guide".

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


Re: Need help improving number guessing game

2008-12-13 Thread James Stroud

James Stroud wrote:
Be assured that it takes on special intelligence to write unintelligible 


I meant "*no* special intelligence".
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread Lie Ryan
On Sat, 13 Dec 2008 14:09:04 -0800, John Machin wrote:

> On Dec 14, 8:07 am, "Chris Rebert"  wrote:
>> On Sat, Dec 13, 2008 at 12:28 PM, John Machin 
>> wrote:
>>
>> > Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit
>> > (Intel)] on win32
>> > Type "help", "copyright", "credits" or "license" for more
>> > information.
>>  x = u'\u9876'
>>  x
>> > u'\u9876'
>>
>> > # As expected
>>
>> > Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
>> > (Intel)] on win 32
>> > Type "help", "copyright", "credits" or "license" for more
>> > information.
>>  x = '\u9876'
>>  x
>> > Traceback (most recent call last):
>> >  File "", line 1, in 
>> >  File "C:\python30\lib\io.py", line 1491, in write
>> >    b = encoder.encode(s)
>> >  File "C:\python30\lib\encodings\cp850.py", line 19, in encode
>> >    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
>> > UnicodeEncodeError: 'charmap' codec can't encode character '\u9876'
>> > in position
>> > 1: character maps to 
>>
>> > # *NOT* as expected (by me, that is)
>>
>> > Is this the intended outcome?
>>
>> When Python tries to display the character, it must first encode it
>> because IO is done in bytes, not Unicode codepoints. When it tries to
>> encode it in CP850 (apparently your system's default encoding judging
>> by the traceback), it unsurprisingly fails (CP850 is an old Western
>> Europe codec, which obviously can't encode an Asian character like the
>> one in question). To signal that failure, it raises an exception, thus
>> the error you see.
>> This is intended behavior.
> 
> I see. That means that the behaviour in Python 1.6 to 2.6 (i.e. encoding
> the text using the repr() function (as then defined) was not intended
> behaviour?
> 
>> Either change your default system/terminal encoding to one that can
>> handle such characters or explicitly encode the string and use one of
>> the provided options for dealing with unencodable characters.
> 
> You are missing the point. I don't care about the visual representation.
> What I care about is an unambiguous representation that can be used when
> communicating about problems across cultures/
> networks/mail-clients/news-readers ... the sort of problems that are
> initially advised as "I got this UnicodeEncodeError" and accompanied by
> no data or garbled data.

Python defaulted to using strict encoding, which means to throw errors on 
unencodable characters, but this is NOT the only behavior, you can change 
the behavior to "replace using placeholder character" or "ignore any 
errors and discard unencodable characters"

 |  errors can be 'strict', 'replace' or 'ignore' and defaults 
 |  to 'strict'.

If you don't like the default behavior or you want another kind of 
behavior, you're welcome to file a bug report at http://bugs.python.org

>> Also, please don't call it a "crash" as that's very misleading. The
>> Python interpreter didn't dump core, an exception was merely thrown.
> 
> "spew nonsense on the screen and then stop" is about as useful and as
> astonishing as "dump core".

That's an interesting definition of crash. You're just like saying: "C 
has crashed because I made a bug in my program". In this context, it is 
your program that crashes, not python nor C, it is misleading to say so.

It will be python's crash if:
1. Python 'segfault'ed
2. Python interpreter exits before there is instruction to exit (either 
implicit (e.g. falling to the last line of the script) or explicit (e.g 
sys.exit or raise SystemExit))
3. Python core dumped
4. Python does something that is not documented

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


Re: 1 or 1/0 doesn't raise an exception

2008-12-13 Thread Daniel Fetchinson
>> Is it a feature that
>>
>> 1 or 1/0
>>
>> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the
>> rationale?
>
> Yes, it's a feature:
>
> http://en.wikipedia.org/wiki/Short-circuit_evaluation
>
> When you have "True or False", you know it's true by the time
> you've got the first piece, so there's no need to evaluate the
> 2nd piece.  The opposite is helpful too:
>
>lst = [some list or an empty list]
>...
>if lst and lst[0] == 42:
>
> This ensures that the "lst[0]" doesn't fail if lst is empty,
> because lst evaluating to false (an empty list) short-circuits
> preventing the evaluation of "lst[0]".

Okay, it's clear, thanks.

Let me just point out that unsuspecting people (like me) might rely on
the whole expression to be evaluated and rely on exceptions being
raised if needed.

So from now on I will not do!

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
--
http://mail.python.org/mailman/listinfo/python-list


Error with SOAPpy

2008-12-13 Thread Amit Goyal
Hi All,

I am new to Python and was trying the sample code on Dive into Python
for WSDL. Below is the error I get.

Traceback (most recent call last):
  File "", line 4, in -toplevel-
print 'Light sensor value: ' + server._ns(namespace).readLSpercent
(int_1 = "1")
  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 470, in
__call__
return self.__r_call(*args, **kw)
  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 492, in
__r_call
self.__hd, self.__ma)
  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 363, in
__call
config = self.config)
  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in
call
r.endheaders()
  File "c:\Python24\lib\httplib.py", line 798, in endheaders
self._send_output()
  File "c:\Python24\lib\httplib.py", line 679, in _send_output
self.send(msg)
  File "c:\Python24\lib\httplib.py", line 646, in send
self.connect()
  File "c:\Python24\lib\httplib.py", line 614, in connect
socket.SOCK_STREAM):
gaierror: (11001, 'getaddrinfo failed')

I am using Python 2.4.4 and the following versions.

>>> xml.__version__
'0.8.4'
>>> fpconst.__version__
'0.7.2'
>>> SOAPpy.__version__
'0.12.0'

Regards,
Amit
--
http://mail.python.org/mailman/listinfo/python-list


Re: File names, character sets and Unicode

2008-12-13 Thread Дамјан Георгиевски

> In a nutshell, this is likely to cause pain until all file systems are
> standardized on a particular encoding of Unicode. Probably only about
> another fifteen years to go ...

well, most Linux distros are defaulting to a UTF-8 locale now, the
exception beeing Gentoo&similar that expect the user to know what to
configure - which he often doesn't :) 

but, yes, there's no way of enforcing that.

-- 
дамјан ( http://softver.org.mk/damjan/ )

... knowledge is exactly like power - something 
to be distributed as widely as humanly possible,
for the betterment of all. -- jd
--
http://mail.python.org/mailman/listinfo/python-list


subprocess to pipe through several processes?

2008-12-13 Thread Neal Becker
How would I use suprocess to do the equivalent of:

cat - | program_a | program_b


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


Re: Bidirectional Networking

2008-12-13 Thread Gabriel Genellina
En Sat, 13 Dec 2008 13:03:17 -0200, Emanuele D'Arrigo   
escribió:

On Dec 12, 9:04 pm, "Gabriel Genellina" 
wrote:

If you're using 2.5 or older, override serve_forever:

 def serve_forever(self):
 while not getattr(self, 'quit', False):
 self.handle_request()

and set the server 'quit' attribute to True in response to some command
 from the client.


Ok, I've tried this method and it would work if I wanted to shut down
the server from the remote client. But if I want the server to shut
down from the server itself upon some condition it doesn't work
because the while statement is evaluated again only after there has
been a request. If requests are infrequent or have ceased the


Yes, this is the problem with this simple approach, handle_request is  
blocking. Python 2.6 has great improvements on this situation.



The problem was that in my code I used:

asyncServer.daemon = True

but somehow that doesn't work. I then tried:

asyncServer.setDaemon(True)

and that does work:


daemon became a property in Python 2.6; setDaemon was the only way to set  
it in previous versions.



Thanks for your help!


Thanks for sharing your code!

--
Gabriel Genellina

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


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread Mark Tolonen


"John Machin"  wrote in message 
news:a8cd683f-853d-4665-bee4-7a0bdb841...@c36g2000prc.googlegroups.com...

On Dec 14, 9:20 am, "Martin v. Löwis"  wrote:
> >> This is intended behavior.
>
> > I see. That means that the behaviour in Python 1.6 to 2.6 (i.e.
> > encoding the text using the repr() function (as then defined) was not
> > intended behaviour?
>
> Sure.

"Sure" as in "sure, it was not intended behaviour"?

> This behavior has not changed. It still uses repr().
>
> Of course, the string type has changed in 3.0, and now uses a different
> definition of repr.

So was the above-reported non-crash consequence of the change of
definition of repr intended?


It is intended.  I ran into your same issue and voiced a similar complaint, 
but Martin pointed out that users of other characters sets wanted to see the 
characters they were using.  If you were in China, would you rather see:


   IDLE 2.6.1
   >>> x=u'\u9876'
   >>> x
   u'\u9876'
   >>> x=u'顶'
   >>> x
   u'\u9876'

or:

   IDLE 3.0
   >>> x='\u9876'
   >>> x
   '顶'
   >>> x='顶'
   >>> x
   '顶'

On Asian consoles that support the required characters, 3.0 makes much more 
sense.  Your cp850 console or my cp437 console can't support the characters, 
so we get the encoding error.  I'm sure our Asian colleagues love it, but 
our encoding-challenged consoles now need:



x='\u9876'
print(ascii(x))

'\u9876'

It's not very convenient, and I've found it is easier to use IDLE (or any 
other IDE supporting UTF-8) rather than the console when dealing with 
characters outside what the console supports.


-Mark


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


Re: Error with SOAPpy

2008-12-13 Thread Jeremiah Dodds
On Sat, Dec 13, 2008 at 10:54 PM, Amit Goyal  wrote:

> Hi All,
>
> I am new to Python and was trying the sample code on Dive into Python
> for WSDL. Below is the error I get.
>
> Traceback (most recent call last):
>  File "", line 4, in -toplevel-
>print 'Light sensor value: ' + server._ns(namespace).readLSpercent
> (int_1 = "1")
>  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 470, in
> __call__
>return self.__r_call(*args, **kw)
>  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 492, in
> __r_call
>self.__hd, self.__ma)
>  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 363, in
> __call
>config = self.config)
>  File "c:\Python24\Lib\site-packages\SOAPpy\Client.py", line 187, in
> call
>r.endheaders()
>  File "c:\Python24\lib\httplib.py", line 798, in endheaders
>self._send_output()
>  File "c:\Python24\lib\httplib.py", line 679, in _send_output
>self.send(msg)
>  File "c:\Python24\lib\httplib.py", line 646, in send
>self.connect()
>  File "c:\Python24\lib\httplib.py", line 614, in connect
>socket.SOCK_STREAM):
> gaierror: (11001, 'getaddrinfo failed')
>
> I am using Python 2.4.4 and the following versions.
>
> >>> xml.__version__
> '0.8.4'
> >>> fpconst.__version__
> '0.7.2'
> >>> SOAPpy.__version__
> '0.12.0'
>
> Regards,
> Amit
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Are you behind a proxy?
--
http://mail.python.org/mailman/listinfo/python-list


Re: 1 or 1/0 doesn't raise an exception

2008-12-13 Thread Benjamin Kaplan
On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson <
[email protected]> wrote:

> >> Is it a feature that
> >>
> >> 1 or 1/0
> >>
> >> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the
> >> rationale?
> >
> > Yes, it's a feature:
> >
> > http://en.wikipedia.org/wiki/Short-circuit_evaluation
> >
> > When you have "True or False", you know it's true by the time
> > you've got the first piece, so there's no need to evaluate the
> > 2nd piece.  The opposite is helpful too:
> >
> >lst = [some list or an empty list]
> >...
> >if lst and lst[0] == 42:
> >
> > This ensures that the "lst[0]" doesn't fail if lst is empty,
> > because lst evaluating to false (an empty list) short-circuits
> > preventing the evaluation of "lst[0]".
>
> Okay, it's clear, thanks.
>
> Let me just point out that unsuspecting people (like me) might rely on
> the whole expression to be evaluated and rely on exceptions being
> raised if needed.
>
> So from now on I will not do!



If you want both expressions evaluated, you can use & and |, just like in C
and Java (&& and || are used for short circuit evaluation in those
languages).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Bidrectional Subprocess Communication

2008-12-13 Thread Gabriel Genellina
En Sat, 13 Dec 2008 18:19:29 -0200, Emanuele D'Arrigo   
escribió:



I'm trying to replicate the positive results of the Client/Server
scripts from the thread "Bidirectional Networking", but this time
using a Process/SubProcess architecture.

The SubProcess, acting as a server, is working just fine. But the
Process executing the SubProcess, the client, somehow doesn't hear any
of the standard output from the SubProcess. What am I missing?


(Pipes don't work the same as sockets, although unix-like systems try hard  
to hide the differences...)


- you have to close server.stdin when you don't have more data to send.  
The server will see an end-of-file and knows it has to exit the loop. Same  
thing on the client side.


- you have to wait until the server answers, else it will get a "broken  
pipe" error or similar.


- end-of-file, in Python, is detected when a read/readline returns an  
empty string


- you sent "Stop!" without a \n - readline() on the server side would wait  
forever; it doesn't matter in the code below because server.stdin is  
explicitely closed.


Below are the modified version of your programs:

#clientTest.py

import sys
import threading
from time import sleep
from subprocess import Popen, PIPE

## Server Thread
class ListenerThread(threading.Thread):

def __init__(self, inChannel):
threading.Thread.__init__(self)
self.inChannel = inChannel

def run(self):
while True:
data = self.inChannel.readline()
if not data:  # data=='' means eof
break
data = data.strip()
print("serverTest.py says: " + data)

print("Starting Client!")

server = Popen("python serverTest.py", stdin=PIPE, stdout=PIPE)

listenerThread = ListenerThread(server.stdout)
listenerThread.start()

server.stdin.write("Something very meaningful!\n")
server.stdin.write("Stop!")
server.stdin.close() # notify server: no more data
listenerThread.join() # wait until server closes channel
print("Client Stopped!")

# serverTest.py
import sys

print("Starting Server!")

while True:
data = sys.stdin.readline()
if not data: # data=='' means eof
  break

data = data.strip()
print("SERVER RECV: '" + data + "'")

if(data == "Stop!"):
break

print("Server Stopped!")


--
Gabriel Genellina

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


Re: Python 3.0 crashes displaying Unicode at interactive prompt

2008-12-13 Thread Martin v. Löwis
> "Sure" as in "sure, it was not intended behaviour"?

It was intended behavior, and still is in 3.0.

>> This behavior has not changed. It still uses repr().
>>
>> Of course, the string type has changed in 3.0, and now uses a different
>> definition of repr.
> 
> So was the above-reported non-crash consequence of the change of
> definition of repr intended?

Yes. If you want a display that is guaranteed to work on your terminal,
use the ascii() builtin function.

py> x = '\u9876'
py> ascii(x)
"'\\u9876'"
py> print(ascii(x))
'\u9876'

Regards,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Re: curses and refreshing problem

2008-12-13 Thread Carl Banks
On Dec 13, 2:29 pm, Karlo Lozovina <_kar...@_mosor.net_> wrote:
> Hi, I'm trying to implement text output interface, something similar to
> wget, using curses module. There are just two things I can't find out how
> to do: prevent curses from clearing the terminal when starting my program,
> and leaving my output after the program closes. Any way to do this with
> curses?

Unless you are referring to some wget screen mode I don't know about,
I suspect wget outputs its progress bar using carriage returns without
newlines.  If that's all you want, there is no need to use curses.

Here is a little example program to illustrate:

import time, sys
for i in range(21):
sys.stdout.write('\rProgress: [' + '='*i + ' '*(20-i) + ']')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\nFinised!\n")


Notice I'm using sys.stdout.write instead of print, because print
automatically appends a newline (which we don't want here).  Yes you
can suppress the newline on print by using a trailing comma, but that
creates an undesirable artifact--a leading space--on the following
cycle.

Notice the '\r' at the beginning of the sys.stdout.write call.  This
tells the terminal to move the cursor back to the beginning of the
line, whence it draws the new progress bar over the old progress bar.

And finally, notice the call to sys.stdout.flush().  When a program is
run on a terminal the underlying I/O is usually line-buffered, meaning
that nothing actually gets output until a newline character is sent.
Therefore we have to call sys.stdout.flush() to flush the buffer
manually.


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


Re: XMPP xmpppy - User Authorization

2008-12-13 Thread Henson
In my own bot, using the latest xmpppy, I've been printing everything
going to the message handler to the screen.  I've yet to see a
'subscribe' string.  Has this changed?


James Mills wrote:
> On Wed, Nov 5, 2008 at 11:28 AM, James Mills
>  wrote:
> > Can anyone shed any light on how I might
> > be able to react to "User Authorization Requests"
> > from other users on an XMPP server/network
> > using teh xmlpp [1] library ?
>
> [SOLVED}:
>
> I found out from having a peek at jabberbot [1]
> that it was as simple as parsing the message.
>
> Here's a code snippet:
>
> 
>def messageHandler(self, cnx, message):
>   text = message.getBody()
>   user = message.getFrom()
>
>   if text is not None:
>  self.env.log.debug("<%s> %s" % (user, text))
>
>  if " " in text:
> command, args = text.split(" ", 1)
>  else:
> command, text = text, ""
>
>  command = command.upper()
>
>  if command == "SUBSCRIBE":
> self._client.Roster.Authorize(user)
> reply = "Authorized."
> 
>
> --JamesMills
>
> --
> --
> -- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


the official way of printing unicode strings

2008-12-13 Thread Piotr Sobolewski
Hello,

in Python (contrary to Perl, for instance) there is one way to do common
tasks. Could somebody explain me what is the official python way of
printing unicode strings?

I tried to do this such way:
s = u"Stanisław Lem"
print u.encode('utf-8')
This works, but is very cumbersome.

Then I tried to do this that way:
s = u"Stanisław Lem"
print u
This breaks when I redirect the output of my program to some file, like
that:
$ example.py > log

Then I tried to do this that way:
sys.stdout = codecs.getwriter("utf-8")(sys.__stdout__)
s = u"Stanisław Lem"
print u
This works but is even more combersome.

So, my question is: what is the official, recommended Python way?


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


  1   2   >