mac install

2010-02-09 Thread Thomas Nelson
I downloaded the 3.1.1 dmg from http://www.python.org/download/releases/3.1.1/
but when I run it I get the error "The folowing install step failed:
run postflight script for python documentation."  The bugs list has
this bug at http://bugs.python.org/issue6934 but it's described as
fixed.  Is it only fixed for the source version?  Where should I go to
install?

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


Re: Looping through File Question

2007-09-05 Thread Thomas Nelson
> > > On Sep 5, 8:58 pm, planetmatt <[EMAIL PROTECTED]> wrote:
>
> > > > I am a Python beginner.  I am trying to loop through a CSV file which
> > > > I can do.  What I want to change though is for the loop to start at
> > > > row 2 in the file thus excluding column headers.

The DictReader object automatically does this for you:

>>> data = """Name,age,job
... Tom,21,programmer
... Sara,22,chef
... Molly,23,doctor"""
>>> from csv import DictReader
>>> myStuff = DictReader(data.split('\n'))
>>> for line in myStuff:
... print line
...
{'job': 'programmer', 'age': '21', 'Name': 'Tom'}
{'job': 'chef', 'age': '22', 'Name': 'Sara'}
{'job': 'doctor', 'age': '23', 'Name': 'Molly'}

HTH,
Tom

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


Re: Combinatorial of elements in Python?

2007-08-15 Thread Thomas Nelson
On Aug 15, 8:39 am, "Sebastian Bassi" <[EMAIL PROTECTED]>
wrote:
> That was easy :)
> What about extending it for N elements inside the dictionary? Sounds
> like a work for a recursive function.

Here's my attempt:
[code]
def backtrack(groups,position=0, answer=''):
if position==len(groups):
yield answer
else:
for e in groups[position]:
for x in backtrack(groups,position+1,answer+e):
yield x


groups = [
['a','b','c'],
['w','x','y','z'],
['1','2']]


for i in backtrack(groups):
print i
[/code]

If you need to put the result into a set, you can.  As for the
original question "Is there a builtin function for this", what you're
asking is essentially the standard recursive backtracking algorithm.
In your case, each "layer" in the network is fully connected to the
network below it, much the way layers in a neural network are set up.
Sadly, there isn't a graph/network algorithm module in the python
standard library.  There are graph-algorithm type libraries out there
I think, but I've never used any of them, so I can't be much help.

-Tom

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


condor_compiled python interpreter

2007-07-11 Thread Thomas Nelson
Does anyone know where I could find help on condor_compiling a python
interpreter?  My own attempts have failed, and I can't find anything
on google.
Here's the condor page:
http://www.cs.wisc.edu/condor/

Thanks,

Tom

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


Re: Trouble killing a process on windows

2007-06-02 Thread Thomas Nelson
On Jun 2, 11:43 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> Thomas Nelson wrote:
> > from subprocess import Popen
> > from time import sleep
> > import win32api
> > war3game = Popen(["C:\Program Files\Warcraft III\Frozen Throne.exe"])
> > sleep(30)
> > print "slept for 30"
> > print win32api.TerminateProcess(int(war3game._handle),-1)
> > #print
> > ctypes.windll.kernel32.TerminateProcess(int(war3game._handle),-1)
> > print "terminated process"
>
> > Here's the output:
> > slept for 30
> > Traceback (most recent call last):
> >   File "C:\Python24\warcraft\runwar3.py", line 7, in ?
> > print win32api.TerminateProcess(int(war3game._handle),-1)
> > error: (5, 'TerminateProcess', 'Access is denied.')
>
> > I'm logged in as adminstrator.  Does anyone know how to fix this
> > problem?
>
> There's nothing obvious. I assume you got your info
> from here?
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347462
>
> Just for completeness, have you tried the pid-based technique
> shown there? I've no idea why it should work if this one
> doesn't but... (I have a slight suspicion that the fact that
> it opens the process with a "for-termination" flag might help).
>
> Failing that, you can see if WMI can do it (although I assume
> that, under the covers, WMI just calls TerminateProcess):
>
> http://timgolden.me.uk/python/wmi_cookbook.html#create_destroy_notepad
>
> I suppose you might have to adjust your token privs to include,
> say the Debug priv. This is designed to let you take control
> of any process (and terminate it, or whatever). If it looks
> like you need to do that, post back and I -- or someone else --
> can try to run up an example.
>
> TJG

I Tried the PID method, and the Taskkill method, and neither worked.
This is what I get for trying to work on a windows machine.  If you
could explain how to add the debug privilege, that would be great.
Just out of curiosity, is there a reason a python module like os
couldn't have a universal terminateProcess type function, that works
on all systems?  Something like os.listdir seems to work really well
everywhere.  Maybe killing processes is too complicated for this?

Thanks for the help,
Tom

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


Trouble killing a process on windows

2007-06-02 Thread Thomas Nelson
Hi, I'd like to start a program, run it for a while, then terminate
it.  I can do this on linux, but I'm new to working with windows.
Here's my script:

from subprocess import Popen
from time import sleep
import win32api
war3game = Popen(["C:\Program Files\Warcraft III\Frozen Throne.exe"])
sleep(30)
print "slept for 30"
print win32api.TerminateProcess(int(war3game._handle),-1)
#print
ctypes.windll.kernel32.TerminateProcess(int(war3game._handle),-1)
print "terminated process"

Here's the output:
slept for 30
Traceback (most recent call last):
  File "C:\Python24\warcraft\runwar3.py", line 7, in ?
print win32api.TerminateProcess(int(war3game._handle),-1)
error: (5, 'TerminateProcess', 'Access is denied.')

I'm logged in as adminstrator.  Does anyone know how to fix this
problem?
Thanks for your time,
Tom

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


Re: Sorting troubles

2007-05-14 Thread Thomas Nelson
On May 14, 11:05 am, [EMAIL PROTECTED] wrote:
> I have the following implementations of quicksort and insertion sort:
>
> def qSort(List):
> if List == []: return []
> return qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \
>qSort([x for x in List[1:] if x>=List[0]])
>
> def insertSort(List):
> for i in range(1,len(List)):
> value=List[i]
> j=i
> while List[j-1]>value and j>0:
> List[j]=List[j-1]
> j-=1
> List[j]=value
>
> Now, the quickSort does not modify the original list, mostly because
> it works on products and concatenations, rather than alterations.
> The insertion sort, however, does modify the list. Now, to give
> results, they should be called in such a way( A is an unsorted list)
> A=qSort(A)
> # the insertion sort does not require this,
> insertSort(A)
>
> I would like to know how can I modify the qSort function such that it
> affects the list directly inside
> I have tried doing it like this
>
> def qSort(List):
> if List == []: return []
> List = qSort([x for x in List[1:] if x< List[0]]) + List[0:1] + \
>qSort([x for x in List[1:] if x>=List[0]])
> return List
>
> while processing, the list changes, but those changes remain inside
> the function, so that once it's over, if nothis catches the return,
> the original List remains unchanged.
>
> If not a solution, I would like to at least know why it does what it
> does. I so understand that List(above) is only a reference to the
> actual data(a list), but I'm not passing a copy of the data to the
> function, but the actual reference(hence, insertSort does
> modifications). But then how can I change, inside the function, the
> object List is referencing to? If I can't modify the original list,
> maybe I can make the variable List point to another list? But changes
> inside the function are local. Sorry if this is a bit confusing.

The thing is that [x for x in List[1:]...] is a brand new list created
by iterating over the old one.
How about:
qSortHelp(List):
newlist = qSort(List)
for i, val in enumerate(newlist):
List[i] = val
You have to iterate over one more time, but this sorts the list in
place.
HTH,
Tom

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


Re: How do I get type methods?

2007-05-04 Thread Thomas Nelson
On May 4, 7:59 am, [EMAIL PROTECTED] wrote:
> On 4 ÍÁÊ, 09:08, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>
> > En Fri, 04 May 2007 01:34:20 -0300, <[EMAIL PROTECTED]> escribio:
> > > I'm not against 'dir(MyClass)'; the question is, what should I 'dir()'
> > > to get methods of 'pyuno' type instance?
> > Usually instances don't have its own methods, they get them from the
> > class. So you actually need dir(MyClass).
> > Note that dir() might not show all available methods.
>
> Let me retype my question: what I 'dir()' in case of 'pyuno' type
> instance?
> Or in case of 'dict' type instance? Or in case of any other new python
> type?

>>> class Foo:
... def f(self,x):
... print x+1
... def g(self,x):
... print x-1
...
>>> dir(Foo)
['__doc__', '__module__', 'f', 'g']

Is this not what you want?  These are the only methods in the Foo
class.

Tom

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


How safe is a set of floats?

2007-05-04 Thread Thomas Nelson
I want to generate all the fractions between 1 and limit (with
limit>1) in an orderly fashion, without duplicates.

def all_ratios(limit):
s = set()
hi = 1.0
lo = 1.0
while True:
if hi/lo not in s:
s.add(hi/lo)
yield (hi,lo)
hi += 1
if hi/lo > limit:
lo += 1
hi = lo

I use a set to keep from giving duplicates; but is this safe?  In C
they always tell you not to trust floating point equality comparisons,
since they may not work as you expect.  My code seems fine for the
limited amount I've tested, but I'm curious: is there a gaurantee
about sets of floats?  Or a warning?

Thanks,

Tom

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


Re: editing scripts on a mac

2007-04-27 Thread Thomas Nelson
On Apr 27, 11:37 am, Tommy Grav <[EMAIL PROTECTED]> wrote:
> > him> I do not have a text editor, but here are the answers to
> > him> questions 1-5.
>
> > Now, frankly, I don't think this answer is correct, since I know OS  
> > X is
> > a UNIX derivative, but I am loathe to involve a programming noob  
> > with vi
> > or something similar. So I wondered if one of the c.l.py mac users  
> > could
> > give brief instructions for firing up a visual text editor of some  
> > sort
> > and saving a file somewhere it can easily be accessed from a terminal
> > window (which I presume starts up in his home directory).
>

1) Open Finder, click "Applications", and open "TextEdit".
2) hit shift-apple-T, or select Format -> Make Plain Text,  to put you
in plaintext mode (It's .rtf by default)
3) Make sure you save in the home directory (usually a picture of a
house).

HTH,
Tom

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


Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?

2007-04-24 Thread Thomas Nelson
On Apr 23, 10:38 pm, Mel Wilson <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
> > The interpreter explains it: "A list is not a hashable object."
> > Choosing a hash table instead of some kind of balanced tree seems
> > to be just an optimization. ;)
>
> Even with a balanced tree, if a key in a node changes value, you may
> have to re-balance the tree.  Nothing in a Python list says that a
> dictionary tree would have to be re-balanced if you changed that
> particular list.
>
> Mel.

You don't have to look at any implementation.  A dictionary maps every
key to exactly one object.  If the objects were mutable, you could
change one key to another key, and then which item would the
dictionary pull?
(Imaginary code)
d = {[1,2,3]: 'hat', [1,2,4]: 'sock' }
for key in d:
key.pop()
print d[[1,2]]  #does this print hat or sock?

Sets have the same problem.  A set can't have duplicates; how could
you enforce this with mutable objects?

Tom

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


feedback on Until recipe

2007-04-24 Thread Thomas Nelson
Occasionally people post complaining about the lack of a
"repeat...until" structure in python.  I thought about it and came up
with this recipe that I like.  The only ugly thing is having to use
lambdas, otherwise it's very terse and readable.  Tell me what you
think, and if anyone besides me thinks they might use it, I'll post it
to the python cookbook.

Thanks for your time,
Tom

class Until:
"""
>>> i = 0
>>> while Until(lambda: i<3):
... print "hello"
... i += 1
hello
hello
hello
>>> while Until(lambda: i<2):
... print "hello"
hello
"""
yet = True
def __init__(self, mybool):
if self.__class__.yet or mybool():
self.__class__.yet = False
self.ans = True
else:
self.__class__.yet = True
self.ans = False

def __nonzero__(self):
return self.ans

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


Feedback on Until recipe

2007-04-24 Thread Thomas Nelson
Occasionally someone posts to this group complaining about the lack of
"repeat ... until" in python.  I too have occasionally wished for such
a construct, and after some thinking, I came up with the class below.
I'm hoping to get some feedback here, and if people besides me think
they might use it someday, I can put it on the python cookbook.  I'm
pretty happy with it, the only ugly thing is you have to use a
lambda.  Ideally i'd like to just see
while Until(i<3)
but that doesn't work.
Please tell me what you think, and thanks for your time.

Tom

class Until:
"""
>>> i = 0
>>> while Until(lambda: i<3):
... print "hello"
... i += 1
hello
hello
hello
>>> while Until(lambda: i<2):  #note i still equals 3 here
... print "hello"
hello
"""
yet = True
def __init__(self, mybool):
if self.__class__.yet or mybool():
self.__class__.yet = False
self.ans = True
else:
self.__class__.yet = True
self.ans = False

def __nonzero__(self):
return self.ans

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-03 Thread Thomas Nelson
On Apr 3, 1:49 pm, [EMAIL PROTECTED] wrote:
> On Apr 3, 1:31 pm, "Matimus" <[EMAIL PROTECTED]> wrote:
>
> > It depends on your application, but a 'set' might really be what you
> > want, as opposed to a list.
>
> > >>> s = set(["0024","haha","0024"])
> > >>> s
>
> > set(["0024","haha"])>>> s.remove("0024")
> > >>> s
>
> > set(["haha"])
>
> If you want, you can also loop over the list, like so:
>
> counter = 0
> your_list = ["0024","haha","0024"]
> for i in your_list:
> if i == '0024':
> your_list.pop(counter)
> counter += 1
>
> Mike

This method doesn't work.
>>> li = list('hello larry')
>>> count = 0
>>> for i in li:
... if i=='l':
... li.pop(count)
... coun += 1
...
'l'
'l'
>>> l
['h', 'e', 'l', 'o', ' ', 'a', 'r', 'r', 'y']

because the indexes change as you pop, it gets some of them but not
all.

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


Re: how to remove multiple occurrences of a string within a list?

2007-04-03 Thread Thomas Nelson

bahoo wrote:
> Hi,
>
> I have a list like ['0024', 'haha', '0024']
> and as output I want ['haha']
>
> If I
> myList.remove('0024')
>
> then only the first instance of '0024' is removed.
>
> It seems like regular expressions is the rescue, but I couldn't find
> the right tool.
>
> Thanks!
> bahoo

It's hard to imagine using regular expressions here.  Here's a simple
attempt:

def removeall(mylist,obj):
while obj in mylist:
mylist.remove(obj)

Or, if you don't need the changes in place:

[x for x in mylist if x!= obj]

Tom

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


Re: list/get methods/attributes of a class?

2007-02-22 Thread Thomas Nelson
Check out the dir() function.  It does what you want, I think.

Tom

On Feb 22, 9:27 am, [EMAIL PROTECTED] wrote:
> Hello,
> Sorry guys for this newbie questions. But I wonder if there is a
> standard or build-in method to know the methods of a class?
>
> I'm not originally a progrommer and I have worked with python/qt in a
> basic level. Now I work a package which has many predefined classes
> which I'm going to resue by importing them. I would like to know more
> about each imported class, what methods exists and so on. Printing the
> object or type(object) doesn't say so much.
>
> Any hint or helps is really appreciated!
> /Ben


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


Re: c++ for python programmers

2007-02-12 Thread Thomas Nelson
On Feb 12, 1:35 pm, andrew clarke <[EMAIL PROTECTED]> wrote:

> Thomas, I sent you a message off-list but it bounced due to your mailbox
> being full.
>
> Short answer: Subscribe to the c-prog@yahoogroups.com mailing list and
> ask your C/C++ questions there.
>
> Regards
> Andrew

I have to edit a large C++ project written by someone else.  My email
address
above is incorrect; replace mail with cs.  Thanks for the help.

Thomas

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


c++ for python programmers

2007-02-12 Thread Thomas Nelson
I realize I'm approaching this backwards from the direction most
people go, but does anyone know of a good c/c++ introduction for
python programmers?

Thanks,

Thomas

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


Re: Sorting a List of Lists

2007-01-30 Thread Thomas Nelson
On Jan 30, 5:55 pm, [EMAIL PROTECTED] wrote:
> I can't seem to get this nailed down and I thought I'd toss it out
> there as, by gosh, its got to be something simple I'm missing.
>
> I have two different database tables of events that use different
> schemas. I am using python to collate these records for display. I do
> this by creating a list of lists that look roughly like this:
>
> events = [['Event URL as String', 'Event Title as String ', Event Date
> as Datetime], ...]
>
> I then thought I'd just go events.sort(lambda x,y: x[2] it a day. That didn't work. But then lamda functions like to be very
> simple, maybe object subscripts aren't allowed (even though I didn't
> get an error). So I wrote a comparison function that looks much as you
> would expect:
>
> def date_compare(list1,
> list2):
> x = list1[2]
> y = list2[2]
> if
> x>y:
> return
> 1
> elif
> x==y:
> return
> 0
> else: #
> x return -1
>
> But as before sorting with this function returns None.
>
> What have I overlooked?

All sorts return None.  the sort is in place.  Check your list post-
sort.

THN

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


Re: Trouble with max() and __cmp__()

2007-01-28 Thread Thomas Nelson


On Jan 28, 3:13 pm, Wojciech Muła 
<[EMAIL PROTECTED]> wrote:
>Define method __gt__.

This works, thanks.  I was a little surprised though. is __cmp__ used 
by any builtin functions?

Thanks,
THN

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

Trouble with max() and __cmp__()

2007-01-28 Thread Thomas Nelson
My code:

class Policy(list):
def __cmp__(self,other):
return cmp(self.fitness,other.fitness)

j = Policy()
j.fitness = 3
k = Policy()
k.fitness = 1
l = Policy()
l.fitness = 5
print max([j,k,l]).fitness

prints 3, when I was expecting it to print 5.  What have I done wrong?

Thanks for the help,
THN

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


Re: newbieee

2007-01-08 Thread Thomas Nelson

lee wrote:
> I getting familiarised with python...can any one suggest me a good
> editor available for python which runs on windows xpone more
> request guys...can nyone tell me a good reference manual for python..

I think vim is a very good editor for python, and it's certainly
available for windows xp.

O'reilly has a book called Programming Python that covers much of the
standard library and how to use it for complex tasks.  It may be out of
date by now, though.  Truthfully the only python references I use
regularly are the online docs and this list.

hth,
THN

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


Re: Non greedy regex

2006-12-14 Thread Thomas Nelson
There's an optional count argument that will give what you want.  Try
re.sub('a.*b','','ababc',count=1)


Carsten Haese wrote:
> On Thu, 2006-12-14 at 06:45 -0800, [EMAIL PROTECTED] wrote:
> > Can someone please explain why these expressions both produce the same
> > result? Surely this means that non-greedy regex does not work?
> >
> > print re.sub( 'a.*b', '', 'ababc' )
> >
> > gives: 'c'
> >
> > Understandable. But
> >
> > print re.sub( 'a.*?b', '', 'ababc' )
> >
> > gives: 'c'
> >
> > NOT, understandable. Surely the answer should be: 'abc'
>
> You didn't tell re.sub to only substitute the first occurrence of the
> pattern. It non-greedily matches two occurrences of 'ab' and replaces
> each of them with ''. Try replacing with some non-empty string instead
> to observe the difference between the two behaviors.
> 
> -Carsten

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


Re: Python in sci/tech applications

2006-11-03 Thread Thomas Nelson
How hard would it be to have numpy/ scipy part of the python standard
library?
Tom


mattf wrote:
> I've discovered Python and have been trying it out lately as a possible
> replacement for computations that would ordinarily be done with a
> commercial package like Matlab or IDL. I'd like to mention a few things
> I've run across that have either surprised me or kept me from doing
> things the way I'd like to.
>
> 1) -There's a large and active sci/tech Python community out there.-
> This was something of a surprise. If you look at the python.org site
> and click down a couple of levels past the front page, there's a rather
> brief mention of scientific and numeric applications-- but I don't
> think this does justice to the current levels of activity and
> accomplishment.
>
> 2) -There's a very impressive set of libraries out there-
> NumPy, SciPy, Enthought. It's really kind of stunning how mature these
> libraries are and how much I had to poke around to figure that out.
>
> 3) -There's a problem with development under Windows.
> A typical task will entail writing a 'pure python' prototype to get the
> 'data in, data out' part of a problem straightened out, then writing a
> module in C to get adequate performance in production runs. But the C
> compiler that my employer provides (the current version of MSVS)
> doesn't produce libraries that work with the current version of Python.
> Ooops. This, in the real world, is a big problem. I -love- Python. And
> I think I could convince other people to use it. But I've got to have a
> way to produce compiled modules painlessly, i.e., without installing a
> new operating system.

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


Re: can I import the module twice (under differnet names)

2006-11-01 Thread Thomas Nelson
alf wrote:
> Hi,
>
> wonder if in the python I could treat modules imorts like classes
> instances. It means I could import it twice or more times under
> different names.
>
> --
> alfz1

You can always give any object as many names as you want:
>>> import sys
>>> s1 = sys
>>> s2 = sys
>>> s1.path
['', '/usr/local/bin', '/bin', '/sbin', '/usr/bin', '/usr/sbin',...
>>> s2.argv
['']

Or maybe you're looking for the builtin function reload?
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
...
>>> import this  #note nothing happens
>>> reload(this)  #runs again
The Zen of Python, by Tim Peters

Beautiful is better than ugly.



Neither one of these methods are too common in practice I think.  Could
you tell us why you want to import a module more than once?
-Tom

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


Re: Memory problem

2006-08-14 Thread Thomas Nelson

Yi Xing wrote:
> On a related question: how do I initialize a list or an array with a
> pre-specified number of elements, something like
> int p[100] in C? I can do append() for 100 times but this looks silly...
> 
> Thanks.
> 
> Yi Xing

Use [0]*100 for a list.

THN

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


Re: Two Classes In Two Files

2006-08-10 Thread Thomas Nelson
Perhaps __init__.py has what you're looking for?

THN


[EMAIL PROTECTED] wrote:
> I just started working with Python and ran into an annoyance. Is there
> a way to avoid having to use the "from xxx import yyy" syntax from
> files in the same directory? I'm sure it's been asked a million times,
> but I can't seem to find the answer.
>
> For example, I have two classes stored in separate files as such.
>
> File: one.py
> 
> class One:
>   def methodA(self):
> print "class One"
>   def methodB(self):
> print "class One"
>
>
> File two.py
> 
> from one import One
>
> class Two(One):
>   def methodA(self):
> print "class Two"
>
> if __name__ == "__main__":
>   x = Two()
>   x.methodA()
>   x.methodB()
>
> When I run the Two.py file, I get the expected output but I'd like to
> eliminate the from line in two.py.

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


Re: Programming newbie coming from Ruby: a few Python questions

2006-08-03 Thread Thomas Nelson
I strongly recommend trying to come up with your own projects.  Just
pick small things that reflect something you actually want to do: maybe
make a simple board game, or a few scripts to help you keep all your
files organized, etc.  Generally speaking I think it's easier to teach
yourself a language if you have a project you care about finishing.  I
was pleasantly surprised by how easy python makes it to travel from "It
would be cool if I could..." to finished product.  In my own case, I'm
a college student, and I wanted a program that could help me schedule
my next semester's classes without conflicts and with the maximum sleep
possible.  That first "project" gave me a lot of good python
experience, and I know use python all the time for "real life"
applications.

THN

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


Re: looking for a regular expression

2006-08-01 Thread Thomas Nelson
How about
my_string = "We the people of the United States, in order to form a
more perfect union, establish justice, insure domestic
tranquility,.."
print (x for x in my_string.split(",") if "justice" in x).next()

This isn't a regular expression, but it gives what you're looking for.

THN

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


Re: statistical analysis tools in python?

2006-07-18 Thread Thomas Nelson
Actually, after a little looking, the simple stats.py module at
http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html
is exactly what I needed.  It may not be as fast or as comprehensive as
scipy or R, but installation simply involves downloading the module and
importing into the code, and it has the ttests I was looking for.
Thanks,
THN

[EMAIL PROTECTED] wrote:
> And there is a python interface to R, so that you can call R routines from
> Python.  R is a free stat language that has all the tests you've mentioned,
> 
> Gerry

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


Re: execute a shell script from a python script

2006-07-18 Thread Thomas Nelson
As described in the docs I pointed to before:
subprocess.call("foo.sh",shell=True)
Is the way to do it without args.  I think it is simplest to learn the
subprocess module because (quoting from the docs) this module intends
to replace several other, older modules and functions, such as:
os.system
os.spawn*
os.popen*
popen2.*
commands.*
This way you only need to learn one thing.  Actually I would like to
see some of these older functions deprecated.

THN

Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> Simon Forman <[EMAIL PROTECTED]> wrote:
> >spec wrote:
> >> Thanks, actually there are no args, is there something even simpler?
> >>
> >> Thanks
> >> Frank
> >
> >you could try os.system()
> >
> >>From the docs:
> >
> >system(command)
>   .
>   [more detail]
>   .
>   .
> I'm concerned the follow-ups in this thread have been too subtle.
> Here is what you need to know:  use system().  A model such as
>
>   import os
>   os.system("my_script")
> 
> fulfills exactly the requirements the original poster described.

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


Re: execute a shell script from a python script

2006-07-17 Thread Thomas Nelson
If your script is foo.sh and takes args:
import subprocess
subprocess.call(["foo.sh","args"],shell=True)
Should work fine.  check out
http://www.python.org/dev/doc/maint24/lib/module-subprocess.html

Enjoy,
THN

spec wrote:
> Hi all, I know nothing about Python. What I need to do is to get a
> Python script to execute a local shell script. I do not need any
> output. What would be th eeasiest way to accomplish this?
> 
> Thanks!

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


statistical analysis tools in python?

2006-07-12 Thread Thomas Nelson
Sorry if this is a FAQ, but I couldn't find a good summary through
google.  What kinds of statistical analysis tools exist in python?  I
really just need t-tests, chi-squared test, and other such tests of
statistical significance.  A few things point to numpy and scipy, but I
was surprised to find the documentation for numpy is not freely
available, and I thought it would be wise to ask here before I download
it and start hunting through the source code for what I want.  Is numpy
the best option for my simple needs?  Also I was a little surprised to
find nothing in the builtin python modules that can find standard
deviation, quartiles, etc.  Is this for any particular reason, or
perhaps no one has shown any interest?  I'd be willing to work on a
project to make simple single-variable analysis part of the builtin
python distribution.

Thanks all,

THN

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


Re: Best command for running shell command

2006-07-11 Thread Thomas Nelson
Yes, I highly recommend the subprocess module.  subprocess.call() can
do almost anything you want to do, and the options are all pretty
intuitive  Whenever I need to write quick scripts for myself, it's what
I use.

THN


Roy Smith wrote:
> In article <[EMAIL PROTECTED]>,
>  Donald Duck <[EMAIL PROTECTED]> wrote:
>
> > I'm a little bit confused about what is the best way to run a shell command,
> > if I want to run a command like
> >
> > xx -a -b > yy
> >
> > where I'm not interested in the output, I only want to make sure that the
> > command was executed OK. How should I invoke this (in a Unix/linux
> > environment)?
>
> The most straight-forward way would be:
>
> import os
> status = os.system ("xx -a -b > yy")
> if status == 0:
>print "it worked"
> else:
>print "it failed"
> 
> You might also want to look at the new (in 2.4) subprocess module.

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


Re: how can I avoid abusing lists?

2006-07-07 Thread Thomas Nelson
Thanks to everyone who posted.  First, I don't think my question was
clear enough: Rob Cowie, Ant, Simon Forman, [EMAIL PROTECTED], and Jon
Ribbens offered solutions that don't quite work as-is, because I need
multiple values to map to a single type.  Tim Chase and Bruno
Destuilliers both offer very nice OOP solutions, and I think this is
the route I will probably go.  However, for the simplest and easiest
solution, I really like this from Peter Otten:
inflated = [0]*5
groups = [[0,1,3],[4],[2]]
for value in [1,1,0,4]:
inflated[value] += 1
print [sum(inflated[i] for i in group) for group in groups]

4 lines (one more to assign the lists to name values, but that's
minor), and intuitive.  If I had just thought of this to begin with, I
wouldn't have bothered posting.

Thanks to all for the advice.

THN

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


how can I avoid abusing lists?

2006-07-07 Thread Thomas Nelson
I have this code:
type1 = [0]
type2 = [0]
type3 = [0]
map = {0:type1, 1:type1, 2:type3, 3:type1, 4:type2}  # the real map is
longer than this

def increment(value):
map[value][0] += 1

increment(1)
increment(1)
increment(0)
increment(4)
#increment will actually be called many times through other functions
print type1[0], type2[0], type3[0]
#should print "3 1 0"

This is exactly what I want to do: every time I encounter this kind of
value in my code, increment the appropriate type by one.  Then I'd like
to go back and find out how many of each type there were.  This way
I've written seems simple enough and effective, but it's very ugly and
I don't think it's the intended use of lists.  Does anyone know a
cleaner way to have the same funtionality?

Thanks,
THN

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


Re: calling functions style question

2006-06-06 Thread Thomas Nelson
The difference becomes clear when you import your program into another
program (or the command line python editor).  __name__!='__main__' when
you import, so the functions will not be called if they're inside the
block.  This is why you see this block so often at the end of scripts;
so that the script runs its main functions when called as a standalone
program, but you can also import the code and do something with it
without setting off those functions.

THN

Brian wrote:
> I just have a basic style question here.  Suppose you have the program:
>
> def foo1():
> do something
>
> def foo2()
> do something else
>
> Assume that you want to call these functions at execution.  Is it more
> proper to call them directly like:
>
> foo1()
> foo2()
>
> or in an if __name__ == "__main__": ?
>
> Both will execute when the script is called directly, I was just
> wondering if there is a preference, and what the pros and cons to each
> method were.
> 
> Thanks,
> Brian

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


Re: print names of dictionaries

2006-04-26 Thread Thomas Nelson
I meant something like
def printdict(dictionaries=[(apps,'apps'), (dirs,'dirs'),
(sites,'sites')]):
   for dictionary,name in dictionaries:
  print name
  keys = dictionary.keys()
  keys.sort()
  for key in keys:
 print key, ":",dictionary[key]
  print '\n',



It's not really easier than what you did.  Instead of making sure every
dictionary in the dictionaries argument contains a 'name' key that does
what you expect, you must make sure the argument passed in is a list of
(dictionary, name) pairs.  It's a little better in my personal opinion,
because you don't have to modify the dictionaries themselves, and it
avoids the problem of 'name' already existing in the dictionary, as
described by Scott Daniels.  But I suppose that's only one opinion.

THN

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


Re: print names of dictionaries

2006-04-26 Thread Thomas Nelson
Here's an OO way that may do what you want:
>>> class MyD(dict):
... def __init__(self,dic,rep):
... dict.__init__(self,dic)
... self.rep = rep
... def __repr__(self):
... return self.rep
...
>>> apps = MyD({'alpha':1,'beta':2},'apps')
>>> apps
apps
>>> apps.keys()
['alpha', 'beta']

Of course, the easiest way is just to use a tuple (dict,string).

THN

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


Re: do while loop

2006-04-26 Thread Thomas Nelson
My usual way of emulating do-while is:

started = False
while (someBoolean or not started):
started = True
#whatever else

This simply assures "whatever else" happens at least once.  Is this
Pythonic?

THN

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


Re: print names of dictionaries

2006-04-26 Thread Thomas Nelson
Here's an OO way that may do what you want:
>>> class MyD(dict):
... def __init__(self,dic,rep):
... dict.__init__(self,dic)
... self.rep = rep
... def __repr__(self):
... return self.rep
...
>>> apps = MyD({'alpha':1,'beta':2},'apps')
>>> apps
apps
>>> apps.keys()
['alpha', 'beta']

Of course, the easiest way is just to use a tuple (dict,string).

As a side note, since dict is a builtin type and function, it might not
be good style to use it as a loop variable.

THN

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


Re: modifying iterator value.

2006-04-26 Thread Thomas Nelson
There is also this way:

for index in range(len(someList)):
someList[index] = 1

This is not as pretty or concise as enumerate(), but if you've never
seen that function before this may be more clear.  I assume you're
familiar with the way range and len work.

THN

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


Re: python about mobile game?

2006-04-20 Thread Thomas Nelson
What is a mobile game?  Is it a game that can be played on a mobile
phone?

THN

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


Re: "The World's Most Maintainable Programming Language"

2006-04-09 Thread Thomas Nelson
I thought the paragraph about provability was interesting.  Presumably
the author refers to proofs in the spirit of "A Discipline of
Programming" from Djikstra, 1976.  Unfortunately, I don't think anyone
has writting much about this since the 70s.  I'd be interested to learn
if anyone's tried to write "weakest precondition" style specifications
for python (builtin functions, for, lambda, etc).  Or perhaps there's
some easier to understand medium?

It's worth noting that the author makes proving correctness sound like
a trivial task, which of course it's not. Consider

def collatz(n,i=0):
if n==1:
return i
elif (n%2)==0:
return collatz(n/2,i+1)
else:
return collatz((3*n+1)/2,i+1)

It is currently unknown whether this even terminates in all cases.

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


Re: python on Mac

2006-04-06 Thread Thomas Nelson
Ok, I fixed my /usr/bin/python and added /usr/public/bin/ to my PATH in
.profile.  Everything seems ok now.
Thanks again to everyone for their help.

THN

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


Re: python on Mac

2006-04-06 Thread Thomas Nelson
Well, as I stated in post, I've already replaced the link at
/usr/bin/python.  I'm not clear why that's unhealthy.  Should I change
it back to whatever it was before?  I guess maybe it was
/System/Library/Frameworks/Python.framework/Versions/Current/bin/python
?
Thanks,
THN

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


Re: python on Mac

2006-04-05 Thread Thomas Nelson
Thanks to you both.  I downloaded the dmg suggested, and trustingly
typed:
sudo rm /usr/bin/python
sudo ln -s /usr/local/bin/python2.4 /usr/bin/python
And now my command line and scripts behave the way I expect.  Thanks
again.

THN

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


Re: python on Mac

2006-04-05 Thread Thomas Nelson
There is no 2.4 in my Versions folder, only 2.3 and current.  Should
one of the installers have created this directory?  Which one?

THN

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


python on Mac

2006-04-05 Thread Thomas Nelson
I just purchased a new macbook (os 10.4.6), and I'm trying to install
python 2.4 on it.  I downloaded and ran the two installers recommended
at http://www.python.org/download/mac/.  Now I have IDLE, which runs
2.4.1, but typing "python" at a terminal still opens 2.3.5, because it
points to /usr/bin/python.  Is there a way to run python 2.4 without
idle?  If I want to do a unix style script, something like
#!/usr/bin/python
print "hello world"
what can I put on the first line that will cause python 2.4 to
interpret my code?

Thanks a lot.
THN

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


Re: new to mac OS10

2005-04-15 Thread Thomas Nelson
The main thing I would like is to be able to use tkinter with python on 
my mac.  will the command-line-style source allow this?  Does it come 
with IDLE?  How is the fink version different from the source i can 
download at python.org?  Here's the result of the requested commands on 
my Terminal.  It would appear that these links are broken, as 
Python.framework no longer exists.  Sorry to be so much trouble,

THN

Welcome to Darwin!
~ $ ls -all /usr/bin/python*
lrwxr-xr-x  1 root  wheel9 20 Jun  2004 /usr/bin/python -> python2.3
lrwxr-xr-x  1 root  wheel   72 20 Jun  2004 /usr/bin/python2.3 -> 
../../System/Library/Frameworks/Python.framework/Versions/2.3/bin/python
lrwxr-xr-x  1 root  wheel   10 20 Jun  2004 /usr/bin/pythonw -> pythonw2.3
-rwxr-xr-x  1 root  wheel  122  8 Jun  2003 /usr/bin/pythonw2.3
~ $ ls /System/Library/Framework/Python.framework
ls: /System/Library/Framework/Python.framework: No such file or directory
~ $ cd /System/Library/Framework/Python.framwork
-bash: cd: /System/Library/Framework/Python.framwork: No such file or 
directory
~ $

Jorl Shefner wrote:
If you simply want the latest python to run from the command line, then
compiling the source code works fine on the mac.  I just installed
2.4.1 on Os 10.3.8 last week without any problems.
http://www.python.org/ftp/python/2.4.1/Python-2.4.1.tgz
"./configure"
"make"
"make install"
J.S.
--
http://mail.python.org/mailman/listinfo/python-list


Re: new to mac OS10

2005-04-14 Thread Thomas Nelson
Maurice LING wrote:
I'm using OSX 10.3.8 as well. Just wondering, how did you "destroy" it? 
What I am thinking is, it may not be as destroyed as you think it might 
have...

cheers
maurice
I was actually trying to update to the newest python version, and I had 
read something saying it would conflict with the old version, so I went 
through and deleted all the folders that had "python" in the name =]. 
clever of me, huh?  now I can't make either the new or the old work. 
Once again, any help would be terrific.

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


new to mac OS10

2005-04-14 Thread Thomas Nelson
I'm on a mac OS X (10.3.8), and I seem to have accidentally destroyed 
the default python installation.  How should I put it on?  Do I need to 
use the unix version?  any help would be greatly appreciated.

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