Re: [Tutor] Replacing part of a URL

2010-02-20 Thread spir
On Sun, 21 Feb 2010 11:25:31 +1100
Steven D'Aprano  wrote:

> "Some people, when confronted with a problem, think 'I know, I'll use 
> regular expressions.' Now they have two problems." -- Jamie Zawinski

;-)



la vita e estrany

http://spir.wikidot.com/
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.path.basename() issue with path slashes

2010-02-20 Thread Steven D'Aprano
On Sun, 21 Feb 2010 10:49:19 am Dayo Adewunmi wrote:
> Hi all,
>
> This script I'm working on, should take all the image files in the
> current directory and generate an HTML thumbnails.
>
> import os
> import urllib

You import urllib, but don't appear to use it anywhere.

>
> # Generate thumbnail gallery
> def genThumbs():
> # Get current directory name
> absolutePath = os.getcwd()
> urlprefix = "http://kili.org/~dayo";
> currentdir = os.path.basename(absolutePath)



> for dirname, subdirname, filenames in os.walk(absolutePath):
> for filename in filenames:
> print ""
> %(currentdir,filename,currentdir,filename)

You don't need to escape quotes, just use the other quote. Instead of:

print ""

use:

print ''

Also, I'm not sure why sometimes you use / as a directory separator and 
sometimes \. I think you're trying to do too much in one line, leading 
to repeated code.

# Untested.
for dirname, subdirname, filenames in os.walk(absolutePath):
for filename in filenames:
fullpath = os.path.join(currentdir, filename)
if os.name == 'nt':
fullpath.replace('\\', '/')
print '' % (fullpath, fullpath)


Hope that helps.



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.0

2010-02-20 Thread Mark Tolonen


"bob gailer"  wrote in message 
news:4b7fea0e.6000...@gmail.com...

On 2/20/2010 5:52 AM, Paul Whittaker wrote:


Using the following script, the (Windows 7) PC echoes the key presses
but doesn't quit (ever!)

import msvcrt

print('Press SPACE to stop...')

while True:

k = msvcrt.getch() # Strangely, this echoes to the IDLE window

if k == ' ':   # Not recognized

break




According to the docs: "msvcrt.getch() - Read a keypress and return the
resulting characterThis call will block if a keypress is not already
available, but will not wait for Enter to be pressed. If the pressed key
was a special function key, this will return '\000' or '\xe0'; the next
call will return the keycode. The Control-C keypress cannot be read with
this function."

IOW - getch always returns 1 character.

You are testing for a 0 length string. Will never happen.

What keystroke do you want to break the loop?


To Bob:  There is a space between the quotes.

To the OP:  Are you running from a console window?  The code works fine for 
me from the console, but running under both IDLE and PythonWin 
msvcrt.getch() returns 255 immediately.  Windows applications without a 
console usually don't play nice with C I/O calls.


-Mark


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.path.basename() issue with path slashes

2010-02-20 Thread Shashwat Anand
>
>
>
> If you're using OS functions you should NOT bank on the slashes being
> forward-slashes.  This is platform-specific behavior.  You should use
> os.path.split() to get the elements of your path and do a "/".join() on
> them.  Otherwise your code will break on Windows because the path will be
> denoted with backslashes.
>
>
What about replacing os.path with posixpath ?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.path.basename() issue with path slashes

2010-02-20 Thread Luke Paireepinart
On Sat, Feb 20, 2010 at 6:11 PM, Dayo Adewunmi wrote:

> Shashwat Anand wrote:
>
>>
>> 
>>
>>
>>  for dirname, subdirname, filenames in os.walk(absolutePath):
>>  for filename in filenames:
>>  print ""
>>%(currentdir,filename,currentdir,filename)
>>
>>
>> I see a small typo here.
>> print ""
>> %(currentdir,filename,currentdir,filename)  should rather be print "> href=\"%s/%s\">"
>> %(currentdir,filename,currentdir,filename) ..
>> notice the slashes "%s/%s" in href tag and "%s\%s" in img tag.
>>
>> >>> filename = '1.jpg'
>> >>> absolutePath = os.getcwd()
>> >>> currentdir = os.path.basename(absolutePath)
>> >>> print ""
>> %(currentdir,filename,currentdir,filename)
>> 
>>
>>
>> ~l0nwlf
>>
> Arrrgh. Didn't see that forwardslash I put in there. It's fixed and works
> now.
> Thanks!
>
>
> If you're using OS functions you should NOT bank on the slashes being
forward-slashes.  This is platform-specific behavior.  You should use
os.path.split() to get the elements of your path and do a "/".join() on
them.  Otherwise your code will break on Windows because the path will be
denoted with backslashes.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replacing part of a URL

2010-02-20 Thread Steven D'Aprano
On Sun, 21 Feb 2010 09:34:34 am Lao Mao wrote:
> Hello,
>
> I need to be able to replace the last bit of a bunch of URLs.
>
> The urls look like this:
>
> www.somesite.com/some/path/to/something.html
>
> They may be of varying lengths, but they'll always end with
> .something_or_other.html
>
> I want to take the "something" and replace it with something else.
>
> My current plan is to simply do a string.split("/")[-1]
>
> and then another .split('.') to result in ['something', 'html'], and
> then replace sometihing, and join them together again.
>
> But - wouldn't it make more sense to do this with re.sub?

Heavens no! Why do you need a 80 pound sledgehammer to crack a peanut???


"Some people, when confronted with a problem, think 'I know, I'll use 
regular expressions.' Now they have two problems." -- Jamie Zawinski



-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Superclass call problem

2010-02-20 Thread Steven D'Aprano
On Sun, 21 Feb 2010 04:50:49 am Alan Harris-Reid wrote:
> Hi,
>
> I am having trouble understanding how superclass calls work.  Here's
> some code...

What version of Python are you using?

In Python 2.x, you MUST inherit from object to use super, and you MUST 
explicitly pass the class and self:

class ParentClass(object):
def __init__(self, a, b, c):
do something here

class ChildClass(ParentClass):
def __init__(self, a, b, c):
super(ChildClass, self).__init__(a, b, c)

In Python 3.x, all classes inherit from object and you no longer need to 
explicitly say so, and super becomes a bit smarter about where it is 
called from:

# Python 3 only
class ParentClass:
def __init__(self, a, b, c):
do something here

class ChildClass(ParentClass):
def __init__(self, a, b, c):
super().__init__(a, b, c)


I assume you are using Python 3.0 or 3.1. (If you're 3.0, you should 
upgrade to 3.1: 3.0 is s-l-o-w and no longer supported.)


Your mistake was to pass self as an explicit argument to __init__. This 
is not needed, because Python methods automatically get passed self:

> def __init__(self):
> super().__init__(self)

That has the effect of passing self *twice*, when __init__ expects to 
get self *once*, hence the error message you see:

> When the super().__init__ line runs I get the error "__init__() takes
> exactly 1 positional argument (2 given)"





-- 
Steven D'Aprano
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.path.basename() issue with path slashes

2010-02-20 Thread Dayo Adewunmi

Shashwat Anand wrote:



 



  for dirname, subdirname, filenames in os.walk(absolutePath):
  for filename in filenames:
  print ""
%(currentdir,filename,currentdir,filename)


I see a small typo here.
print "" 
%(currentdir,filename,currentdir,filename)  should rather be print "href=\"%s/%s\">" 
%(currentdir,filename,currentdir,filename) ..

notice the slashes "%s/%s" in href tag and "%s\%s" in img tag.

>>> filename = '1.jpg'
>>> absolutePath = os.getcwd()
>>> currentdir = os.path.basename(absolutePath)
>>> print "" 
%(currentdir,filename,currentdir,filename)




~l0nwlf
Arrrgh. Didn't see that forwardslash I put in there. It's fixed and 
works now.

Thanks!

Dayo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] os.path.basename() issue with path slashes

2010-02-20 Thread Shashwat Anand



>
>   for dirname, subdirname, filenames in os.walk(absolutePath):
>   for filename in filenames:
>   print ""
> %(currentdir,filename,currentdir,filename)
>
>
I see a small typo here.
print ""
%(currentdir,filename,currentdir,filename)  should rather be print ""
%(currentdir,filename,currentdir,filename) ..
notice the slashes "%s/%s" in href tag and "%s\%s" in img tag.

>>> filename = '1.jpg'
>>> absolutePath = os.getcwd()
>>> currentdir = os.path.basename(absolutePath)
>>> print ""
%(currentdir,filename,currentdir,filename)



~l0nwlf
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Superclass call problem

2010-02-20 Thread Alan Harris-Reid

Luke Paireepinart wrote:

Your call to super is wrong. It should be super and you pass the class
and instance, then call init.

On 2/20/10, Alan Harris-Reid  wrote:
  

Hi,

I am having trouble understanding how superclass calls work.  Here's
some code...

class ParentClass():
def __init__(self):
do something here

class ChildClass(ParentClass):
def __init__(self):
   super().__init__(self) # call parentclass
__init__ method
   do something else here


When the super().__init__ line runs I get the error "__init__() takes
exactly 1 positional argument (2 given)"

Can anyone tell me where I have gone wrong?  I thought the self
parameter should be passed to all class methods.

TIA
Alan Harris-Reid
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Hi Luke, thanks for the reply,

In addition to your suggestion, looks like I can use

class ChildClass(ParentClass):
   def __init__(self, arg):
   super(ParentClass, self).__init__(arg)
   or
   super().__init__(arg)# this only works in Python 3, I think

I prefer the 2nd way, as it is more generic (ie. don't need to state 
parent-class).


Regards,
Alan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] os.path.basename() issue with path slashes

2010-02-20 Thread Dayo Adewunmi

Hi all,

This script I'm working on, should take all the image files in the current 
directory
and generate an HTML thumbnails.

import os
import urllib

# Generate thumbnail gallery
def genThumbs():
   # Get current directory name
   absolutePath = os.getcwd()
   urlprefix = "http://kili.org/~dayo";
   currentdir = os.path.basename(absolutePath)

   for dirname, subdirname, filenames in os.walk(absolutePath):
   for filename in filenames:
   print "" 
%(currentdir,filename,currentdir,filename)

# Generate thumbnail gallery
genThumbs()

However, this is the type of output I get:

http://kili.org/~dayo/thumbs/00838_drops_1024x768.jpg";>http://kili.org/~dayo\thumbs\00838_drops_1024x768.jpg"; />


See how in the url in the src attribute of the img tag the slashes after "~dayo"
are somehow turned into backslashes, instead of forwardslashes. How come?

Best regards

Dayo

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replacing part of a URL

2010-02-20 Thread Kent Johnson
On Sat, Feb 20, 2010 at 5:34 PM, Lao Mao  wrote:
> Hello,
> I need to be able to replace the last bit of a bunch of URLs.
> The urls look like this:
> www.somesite.com/some/path/to/something.html
> They may be of varying lengths, but they'll always end with
> .something_or_other.html
> I want to take the "something" and replace it with something else.
> My current plan is to simply do a string.split("/")[-1]
> and then another .split('.') to result in ['something', 'html'], and then
> replace sometihing, and join them together again.
> But - wouldn't it make more sense to do this with re.sub?
> In which case, how would I specify only the bit between the last / and the
> .html?

In [11]: import re

In [13]: re.sub(r'/[^/]+\.html', '/something_else.html',
'www.somesite.com/some/path/to/something.html')
Out[13]: 'www.somesite.com/some/path/to/something_else.html'

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replacing part of a URL

2010-02-20 Thread Shashwat Anand
>
> They may be of varying lengths, but they'll always end with
> .something_or_other.html
>

Missed this point. You can use posixpath module too as an option.
>>> url = 'http://www.somesite.com/some/path/to/something.html
>>> var = 'anotherthing'
>>> posixpath.dirname(url)
'http://www.somesite.com/some/path/to'
>>> posixpath.dirname(url) + '/' + var + '.html'
'http://www.somesite.com/some/path/to/anotherthing.html'


On Sun, Feb 21, 2010 at 4:45 AM, Shashwat Anand wrote:

> >>> url = 'http://www.somesite.com/some/path/to/something.html'
> >>> var = 'anotherthing'
> >>> i = url.rfind('/') + 1
> >>> j = url.rfind('.')
> >>> if i < j:
> ... newurl = url[:i] + var + url[j:]
> ... else:
> ... newurl = url[:i] + var
> >>> newurl
> 'http://www.somesite.com/some/path/to/anotherthing.html'
>
> Changing the url to 'http://www.somesite.com/some/path/to/something' we
> get newurl as 'http://www.somesite.com/some/path/to/anotherthing'
>
> However if you are absolutely sure the pattern is '
> http://www.somesite.com/some/path/to/something.html' , then you can simply
> write one-liner as:
> >>> url[:url.rfind('/') + 1] + var + url[url.rfind('.'):]
> 'http://www.somesite.com/some/path/to/anotherthing.html'
>
> Literally the same stuff. I don't think you need regex for such simple
> string manipulation.
>
> ~l0nwlf
>
>
> On Sun, Feb 21, 2010 at 4:04 AM, Lao Mao wrote:
>
>> Hello,
>>
>> I need to be able to replace the last bit of a bunch of URLs.
>>
>> The urls look like this:
>>
>> www.somesite.com/some/path/to/something.html
>>
>> They may be of varying lengths, but they'll always end with
>> .something_or_other.html
>>
>> I want to take the "something" and replace it with something else.
>>
>> My current plan is to simply do a string.split("/")[-1]
>>
>> and then another .split('.') to result in ['something', 'html'], and then
>> replace sometihing, and join them together again.
>>
>> But - wouldn't it make more sense to do this with re.sub?
>>
>> In which case, how would I specify only the bit between the last / and the
>> .html?
>>
>> Thanks,
>>
>> Laomao
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Replacing part of a URL

2010-02-20 Thread Shashwat Anand
>>> url = 'http://www.somesite.com/some/path/to/something.html'
>>> var = 'anotherthing'
>>> i = url.rfind('/') + 1
>>> j = url.rfind('.')
>>> if i < j:
... newurl = url[:i] + var + url[j:]
... else:
... newurl = url[:i] + var
>>> newurl
'http://www.somesite.com/some/path/to/anotherthing.html'

Changing the url to 'http://www.somesite.com/some/path/to/something' we get
newurl as 'http://www.somesite.com/some/path/to/anotherthing'

However if you are absolutely sure the pattern is '
http://www.somesite.com/some/path/to/something.html' , then you can simply
write one-liner as:
>>> url[:url.rfind('/') + 1] + var + url[url.rfind('.'):]
'http://www.somesite.com/some/path/to/anotherthing.html'

Literally the same stuff. I don't think you need regex for such simple
string manipulation.

~l0nwlf


On Sun, Feb 21, 2010 at 4:04 AM, Lao Mao  wrote:

> Hello,
>
> I need to be able to replace the last bit of a bunch of URLs.
>
> The urls look like this:
>
> www.somesite.com/some/path/to/something.html
>
> They may be of varying lengths, but they'll always end with
> .something_or_other.html
>
> I want to take the "something" and replace it with something else.
>
> My current plan is to simply do a string.split("/")[-1]
>
> and then another .split('.') to result in ['something', 'html'], and then
> replace sometihing, and join them together again.
>
> But - wouldn't it make more sense to do this with re.sub?
>
> In which case, how would I specify only the bit between the last / and the
> .html?
>
> Thanks,
>
> Laomao
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Replacing part of a URL

2010-02-20 Thread Lao Mao
Hello,

I need to be able to replace the last bit of a bunch of URLs.

The urls look like this:

www.somesite.com/some/path/to/something.html

They may be of varying lengths, but they'll always end with
.something_or_other.html

I want to take the "something" and replace it with something else.

My current plan is to simply do a string.split("/")[-1]

and then another .split('.') to result in ['something', 'html'], and then
replace sometihing, and join them together again.

But - wouldn't it make more sense to do this with re.sub?

In which case, how would I specify only the bit between the last / and the
.html?

Thanks,

Laomao
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Superclass call problem

2010-02-20 Thread Luke Paireepinart
>
>
> Hi Kent, thanks for the reply,
>
> Sorry, left out 'object' from my example.  The actual code already reads
> class ParentClass(object):
>
> Did you figure it out from my previous e-mail?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fast sampling with replacement

2010-02-20 Thread Luke Paireepinart
On Sat, Feb 20, 2010 at 1:50 PM, Kent Johnson  wrote:

> On Sat, Feb 20, 2010 at 11:22 AM, Andrew Fithian 
> wrote:
> >  can
> > you help me speed it up even more?
> > import random
> > def sample_with_replacement(list):
> > l = len(list) # the sample needs to be as long as list
> > r = xrange(l)
> > _random = random.random
> > return [list[int(_random()*l)] for i in r]
>
> You don't have to assign to r, just call xrange() in the list comp.
> You can cache int() as you do with random.random()
> Did you try random.randint(0, l) instead of int(_random()*i) ?
> You shouldn't call your parameter 'list', it hides the builtin list
> and makes the code confusing.
>
> You might want to ask this on comp.lang.python, many more optimization
> gurus there.
>
> Also the function's rather short, it would help to just inline it (esp.
with Kent's modifications, it would basically boil down to a list
comprehension (unless you keep the local ref's to the functions), I hear the
function call overhead is rather high (depending on your usage - if your
lists are huge and you don't call the function that much it might not
matter.)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Superclass call problem

2010-02-20 Thread Alan Harris-Reid

Kent Johnson wrote:

On Sat, Feb 20, 2010 at 12:50 PM, Alan Harris-Reid
 wrote:
  

Hi,

I am having trouble understanding how superclass calls work.  Here's some
code...

class ParentClass():
  def __init__(self):
  do something here



You should inherit object to use super():
class ParentClass(object):

Kent


Hi Kent, thanks for the reply,

Sorry, left out 'object' from my example.  The actual code already reads
class ParentClass(object):

Alan

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fast sampling with replacement

2010-02-20 Thread Kent Johnson
On Sat, Feb 20, 2010 at 11:22 AM, Andrew Fithian  wrote:
>  can
> you help me speed it up even more?
> import random
> def sample_with_replacement(list):
>     l = len(list) # the sample needs to be as long as list
>     r = xrange(l)
>     _random = random.random
>     return [list[int(_random()*l)] for i in r]

You don't have to assign to r, just call xrange() in the list comp.
You can cache int() as you do with random.random()
Did you try random.randint(0, l) instead of int(_random()*i) ?
You shouldn't call your parameter 'list', it hides the builtin list
and makes the code confusing.

You might want to ask this on comp.lang.python, many more optimization
gurus there.

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Superclass call problem

2010-02-20 Thread Kent Johnson
On Sat, Feb 20, 2010 at 12:50 PM, Alan Harris-Reid
 wrote:
> Hi,
>
> I am having trouble understanding how superclass calls work.  Here's some
> code...
>
> class ParentClass():
>   def __init__(self):
>       do something here

You should inherit object to use super():
class ParentClass(object):

Kent
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] fast sampling with replacement

2010-02-20 Thread Luke Paireepinart
Can you explain what your function is doing and also post some test code to
profile it?

On Sat, Feb 20, 2010 at 10:22 AM, Andrew Fithian  wrote:

> Hi tutor,
>
> I'm have a statistical bootstrapping script that is bottlenecking on a
> python function sample_with_replacement(). I wrote this function myself
> because I couldn't find a similar function in python's random library. This
> is the fastest version of the function I could come up with (I used
> cProfile.run() to time every version I wrote) but it's not fast enough, can
> you help me speed it up even more?
>
> import random
> def sample_with_replacement(list):
> l = len(list) # the sample needs to be as long as list
> r = xrange(l)
> _random = random.random
> return [list[int(_random()*l)] for i in r] # using
> list[int(_random()*l)] is faster than random.choice(list)
>
> FWIW, my bootstrapping script is spending roughly half of the run time in
> sample_with_replacement() much more than any other function or method.
> Thanks in advance for any advice you can give me.
>
> -Drew
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Superclass call problem

2010-02-20 Thread Luke Paireepinart
Your call to super is wrong. It should be super and you pass the class
and instance, then call init.

On 2/20/10, Alan Harris-Reid  wrote:
> Hi,
>
> I am having trouble understanding how superclass calls work.  Here's
> some code...
>
> class ParentClass():
> def __init__(self):
> do something here
>
> class ChildClass(ParentClass):
> def __init__(self):
>super().__init__(self) # call parentclass
> __init__ method
>do something else here
>
>
> When the super().__init__ line runs I get the error "__init__() takes
> exactly 1 positional argument (2 given)"
>
> Can anyone tell me where I have gone wrong?  I thought the self
> parameter should be passed to all class methods.
>
> TIA
> Alan Harris-Reid
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

-- 
Sent from my mobile device
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] fast sampling with replacement

2010-02-20 Thread Andrew Fithian
Hi tutor,

I'm have a statistical bootstrapping script that is bottlenecking on a
python function sample_with_replacement(). I wrote this function myself
because I couldn't find a similar function in python's random library. This
is the fastest version of the function I could come up with (I used
cProfile.run() to time every version I wrote) but it's not fast enough, can
you help me speed it up even more?

import random
def sample_with_replacement(list):
l = len(list) # the sample needs to be as long as list
r = xrange(l)
_random = random.random
return [list[int(_random()*l)] for i in r] # using
list[int(_random()*l)] is faster than random.choice(list)

FWIW, my bootstrapping script is spending roughly half of the run time in
sample_with_replacement() much more than any other function or method.
Thanks in advance for any advice you can give me.

-Drew
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Superclass call problem

2010-02-20 Thread Alan Harris-Reid

Hi,

I am having trouble understanding how superclass calls work.  Here's 
some code...


class ParentClass():
   def __init__(self):
   do something here

class ChildClass(ParentClass):
   def __init__(self):
  super().__init__(self) # call parentclass 
__init__ method

  do something else here


When the super().__init__ line runs I get the error "__init__() takes 
exactly 1 positional argument (2 given)"


Can anyone tell me where I have gone wrong?  I thought the self 
parameter should be passed to all class methods.


TIA
Alan Harris-Reid
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyMVPA and OSError

2010-02-20 Thread Luke Paireepinart
On Thu, Feb 18, 2010 at 10:23 AM, Juli  wrote:

> Dear All,
>
> I am very much new to python, therefore I am likely to feel stupid
> about asking this. I need pyMPVA module to play around with some fMRI
> data. I have installed Python2.6 on Mac OS X Leopard. When I input >>>
> import mvpa i get a deprecation warning, which is not a problem,
> however when I try the following: >>> >>> import mvpa.suite as mvpa i
> do not get a deprecating warning however I get a number of errors that
> are as follows:
> >>> import mvpa.suite as mvpa
>


In addition to what Yaroslav mentioned, I may also suggest that it's
probably not a great idea to import a sub-package as the base package's
name.  You may have problems later if you want to import from mvpa. I.E. it
would be better to say
import mvpa.suite as suite
or
from mvpa import suite

Also I think you are supposed to use the syntax
from mvpa import suite as foobar
not
import mvpa.suite as foobar

but I'm not sure.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.0

2010-02-20 Thread Alan Gauld


"bob gailer"  wrote

k = msvcrt.getch() # Strangely, this echoes to the IDLE window
if k == ' ':   # Not recognized



IOW - getch always returns 1 character.

You are testing for a 0 length string. Will never happen.


No, he is testing for a space character.
But he is running it in IDLE and msvcrt only works n the 
OS command window world.


I've updated my tutorial page to point that out.


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.0

2010-02-20 Thread Alan Gauld


"Paul Whittaker"  wrote


Using the following script, the (Windows 7) PC echoes the key presses but
doesn't quit (ever!)

import msvcrt
print('Press SPACE to stop...')
while True:
   k = msvcrt.getch() # Strangely, this echoes to the IDLE window


You will need to run it in an OS command window not in IDLE.
Idle does its own keystoke capturing since its a GUI.

I'll need to add a note to my tutor page to emphasise that since
its probably not intuitively obvious! :-)


Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The Disappearing Program (py2exe)

2010-02-20 Thread Wayne Watson

(This might be slightly readable. Missed two words.)
This apparently is not quite as easy as the py2exe tutorial suggests 
when MPL is involved. See . 
It looks like I have some reading and work to do.


The link came from my post to the MPL list. I hadn't noticed it last 
night, since it got stuck in my server as spam.


On 2/20/2010 3:21 AM, Wayne Watson wrote:

Yes, I sent a message there last night. No responses yet. Strangely I
don't see it posted yet.  That was six hours ago. Well, I finish off
my night's sleep in about 4 hours maybe it will have made it.py2exe
seems a little less traveled subject than most.

On 2/20/2010 1:36 AM, Alan Gauld wrote:


"Wayne Watson"  wrote


 File "matplotlib\__init__.pyc", line 478, in _get_data_path
RuntimeError: Could not find the matplotlib data files
<---What is this?

C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist>

==
I Googled this  py2exe message RuntimeError: Could not find the
matplotlib data files.
As of yet, it does not look like a solution ia available for
matplotlib.


Have you tried asking on the matplotlib groups? I notice on
gmane that there are four matplotlib groups listed. One of them
might be able to help?

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor





--
"There is nothing so annoying as to have two people
 talking when you're busy interrupting." -- Mark Twain

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The Disappearing Program (py2exe)

2010-02-20 Thread Wayne Watson
This apparently not quite as easy as the py2exe suggests when MPL is 
involved. See . It looks 
like I have some reading and work to do.


On 2/20/2010 3:21 AM, Wayne Watson wrote:
Yes, I sent a message there last night. No responses yet. Strangely I 
don't see it posted yet.  That was six hours ago. Well, I finish off 
my night's sleep in about 4 hours maybe it will have made it.py2exe 
seems a little less traveled subject than most.


On 2/20/2010 1:36 AM, Alan Gauld wrote:


"Wayne Watson"  wrote


 File "matplotlib\__init__.pyc", line 478, in _get_data_path
RuntimeError: Could not find the matplotlib data files 
<---What is this?


C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist> 


==
I Googled this  py2exe message RuntimeError: Could not find the 
matplotlib data files.
As of yet, it does not look like a solution ia available for 
matplotlib.


Have you tried asking on the matplotlib groups? I notice on
gmane that there are four matplotlib groups listed. One of them
might be able to help?

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor





--
"There is nothing so annoying as to have two people
 talking when you're busy interrupting." -- Mark Twain

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Network Socket question

2010-02-20 Thread Tom Green
Hello group,

First, I love this forum as I find it to be a wealth of info on Python
and programming in general.  I have a general question about sockets,
which is what I primarily use Python for.  My environment is Windows
and I am using Python 2.5.

My sockets are working great but now I am running into a client that
sends multiple sends and I have no EOF (end of file) marker.  I have
read up on Twistted and threads and was wondering if someone could
share a Windows method for working with a non-blocking socket.  I
believe I have to use POLL or select to check for data.  Right now my
socket hangs on RECV.  Sorry if I am not explaining this correctly.
Maybe someone can share with me some papers on writing Windows
sockets.

Thank you,
Tom Green.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List append method: St Petersburg Game

2010-02-20 Thread AG

bob gailer wrote:

On 2/20/2010 7:43 AM, AG wrote:





Please let me know how I can clarify my question

1 - You are giving way too much information. We do not need to know 
the rules of the game or all the code. Our time to read email is 
limited. The less you tell us that is not relevant the better. 

Thanks Bob.

Also you don't show the code for the "next level of complexity". 


Here it is, then:

import random
import matplotlib.pyplot as plt
import math

def flipCoin():
   coinToss = random.randrange(1, 3)
   return coinToss

toss_list = []
tosscounts = []
winnings = []


for i in range(0, 10):

   while flipCoin() != 2:
   toss_list.append("Tails")
   flipCoin()


   print
   print "Heads"


   tosscounts.append( len(toss_list))

   if toss_list == 0:
   print "You won $2"
   winnings += 2

   else:
   toss_list.append( "Tail" )

   winnings += [2 ** len( toss_list )]
  


print
print tosscounts
print winnings

print "Here's the graph: "

for i in winnings:  # Convert int to float for log
   i * 1.0
  
plt.plot( [tosscounts], [winnings] )

plt.ylabel( "how often" )
plt.xlabel( "how much" )
plt.show()




The result of the first call to flipCoin is ignored.
Each cycle of the loop results in 2 calls to flipCoin. The result of 
the 2nd call is ignored.


Aha!  Thanks for spotting that.  Now fixed in the code cited above, but 
still gives the same problem.


Thanks for any further ideas.

AG

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List append method: St Petersburg Game

2010-02-20 Thread bob gailer

On 2/20/2010 7:43 AM, AG wrote:

Hi Pythonistas

I am having difficulty with applying the list.append(x) method to 
produce a list that will contain outputs which will become coordinates 
for a later call to Matplotlib.  Perhaps someone here can help me 
figure this out?



Please let me know how I can clarify my question

1 - You are giving way too much information. We do not need to know the 
rules of the game or all the code. Our time to read email is limited. 
The less you tell us that is not relevant the better. Also you don't 
show the code for the "next level of complexity". What you should show 
us is:

for i  in range( 0, 10 ):
some lists are initialized and appended to. What are they and how are 
they appended?


   #Main function:
   def flipCoin():
  coinToss = random.randrange(1, 3)
  return coinToss

   # Storage of output
   toss_list = []

   # Get things going
   flipCoin()

   # Want to capture the coin lands heads (2)
   while flipCoin() != 2:
  toss_list.append("Tails")
  flipCoin()


2 - The most obvious problem is here:

flipCoin()
while flipCoin() != 2:
   toss_list.append("Tails")
   flipCoin()

The result of the first call to flipCoin is ignored.
Each cycle of the loop results in 2 calls to flipCoin. The result of the 
2nd call is ignored.



The overall purpose of the game is, for this discussion, irrelevant, 
but some background info will be helpful I think.   The above program 
will give one run only and produces the output I expect. 


Then your expectation is misguided, given my comments regarding multiple 
calls to flipCoin! You don't actually know how many tosses were made!


[snip]

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python 3.0

2010-02-20 Thread bob gailer

On 2/20/2010 5:52 AM, Paul Whittaker wrote:


Using the following script, the (Windows 7) PC echoes the key presses 
but doesn't quit (ever!)


import msvcrt

print('Press SPACE to stop...')

while True:

k = msvcrt.getch() # Strangely, this echoes to the IDLE window

if k == ' ':   # Not recognized

break




According to the docs: "msvcrt.getch() - Read a keypress and return the 
resulting characterThis call will block if a keypress is not already 
available, but will not wait for Enter to be pressed. If the pressed key 
was a special function key, this will return '\000' or '\xe0'; the next 
call will return the keycode. The Control-C keypress cannot be read with 
this function."


IOW - getch always returns 1 character.

You are testing for a 0 length string. Will never happen.

What keystroke do you want to break the loop?

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List append method: St Petersburg Game

2010-02-20 Thread AG

Hi Pythonistas

I am having difficulty with applying the list.append(x) method to 
produce a list that will contain outputs which will become coordinates 
for a later call to Matplotlib.  Perhaps someone here can help me figure 
this out?


The basic program is below:

# St Petersburg Game: v. 2:
# Toss a coin.  If it is heads, win $2, if not keep
#   tossing it until it falls heads.
#   Heads first toss = H = $2
#   Heads third toss = TTH = $8
#   Heads fifth toss = H = $32

# The game is to win more by not scoring Heads

print """St Petersburg Game: win multiples of $2 the
more you land Tails"""

# Required libraries
import random
import matplotlib.pyplot as plt

#Main function:
def flipCoin():
   coinToss = random.randrange(1, 3)
   return coinToss

# Storage of output
toss_list = []

# Get things going
flipCoin()

# Want to capture the coin lands heads (2)
while flipCoin() != 2:
   toss_list.append("Tails")
   flipCoin()

# Heads lands & show output   
print

print "Heads"

print toss_list

# Interpret results & 'reward'
print "You flipped %d tails before landing Heads" % len(toss_list)

if toss_list == 0:
   print "You won $2"

else:
   toss_list.append( "Tail" )
   print "You won $%d" % 2 ** len(toss_list)



The overall purpose of the game is, for this discussion, irrelevant, but 
some background info will be helpful I think.   The above program will 
give one run only and produces the output I expect.  When I take this to 
the next level of complexity I run into problems.


1. I have tried to make this program run a given number of times, and 
use the for repetition loop to do this, basically:


for i  in range( 0, 10 ):

and then the above program is appropriately indented.

2. Collecting the number of coin "tosses" into a list appends these to a 
list just fine.  However, what this does is adds the numbers together so 
that one ends up like this:


[0, 1, 2, 4, 5, 6, 8, 10, 11, 15]

With a corresponding increase in the values derived from multiplying the 
exponent, thus:


[2, 4, 8, 32, 64, 128, 512, 2048, 4096, 65536]

Both are correct applications of the method, but I am unable to get the 
list to not sum the values up in the first list, these are not 
accumulative values, but discrete.  If I am understanding what is 
currently happening, the values are being accumulated, and I want to 
stop that from happening.


If this isn't clear, please let me know how I can clarify my question to 
help shape the relevance of the responses.


Thanks for any ideas.

AG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python 3.0

2010-02-20 Thread Paul Whittaker
Using the following script, the (Windows 7) PC echoes the key presses but
doesn't quit (ever!)

 

import msvcrt

 

print('Press SPACE to stop...')

 

while True:

k = msvcrt.getch() # Strangely, this echoes to the IDLE window

if k == ' ':   # Not recognized

break

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyMVPA and OSError

2010-02-20 Thread Yaroslav Halchenko
Hi Juli,

why not to ask at our mailing list? ;)

http://lists.alioth.debian.org/mailman/listinfo/pkg-exppsy-pymvpa

usually we don't bite too hard ;)

so, in your case, would you get similar crash when you simply

import pylab

?

try to upgrade your pylab installation, or otherwise disable it for now
within PyMPVA so it doesn't even try to import it when you want to
import a complete suite:

echo -e '[externals]\nhave pylab = no\n' > ~/.pymvpa.cfg

P.S. note for myself -- may be we should catch not only ImportError while
checking external dependencies.

-- 
  .-.
=--   /v\  =
Keep in touch// \\ (yoh@|www.)onerussian.com
Yaroslav Halchenko  /(   )\   ICQ#: 60653192
   Linux User^^-^^[17]


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The Disappearing Program (py2exe)

2010-02-20 Thread Wayne Watson
Yes, I sent a message there last night. No responses yet. Strangely I 
don't see it posted yet.  That was six hours ago. Well, I finish off my 
night's sleep in about 4 hours maybe it will have made it.py2exe seems a 
little less traveled subject than most.


On 2/20/2010 1:36 AM, Alan Gauld wrote:


"Wayne Watson"  wrote


 File "matplotlib\__init__.pyc", line 478, in _get_data_path
RuntimeError: Could not find the matplotlib data files 
<---What is this?


C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist> 


==
I Googled this  py2exe message RuntimeError: Could not find the 
matplotlib data files.

As of yet, it does not look like a solution ia available for matplotlib.


Have you tried asking on the matplotlib groups? I notice on
gmane that there are four matplotlib groups listed. One of them
might be able to help?

Alan G.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



--
"There is nothing so annoying as to have two people
 talking when you're busy interrupting." -- Mark Twain

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ask

2010-02-20 Thread Alan Gauld


"Shurui Liu (Aaron Liu)"  wrote


How to describe a math formula: sphere=(4/3)*PI*R**3?


I'm not sure what you are asking?


Shurui Liu (Aaron Liu)
Computer Science & Engineering Technology
University of Toledo


I assume from this that you have a basic knowledge of math 
so you understand about expressions and arithmetic operations etc?


Are you asking how to express that in Python?
Have you tried just entering it as written?


--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] The Disappearing Program (py2exe)

2010-02-20 Thread Alan Gauld


"Wayne Watson"  wrote


 File "matplotlib\__init__.pyc", line 478, in _get_data_path
RuntimeError: Could not find the matplotlib data files 
<---What is this?


C:\Users\Wayne\Sandia_Meteors\Sentinel_Development\Learn_Python\Py2exe_Test\dist>
==
I Googled this  py2exe message RuntimeError: Could not find the 
matplotlib data files.

As of yet, it does not look like a solution ia available for matplotlib.


Have you tried asking on the matplotlib groups? I notice on
gmane that there are four matplotlib groups listed. One of them
might be able to help?

Alan G. 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor