Re: [Tutor] When am I ever going to use this?

2006-08-01 Thread Jordan Greenberg
Christopher Spears wrote:
> I've been working through a tutorial:
> http://www.ibiblio.org/obp/thinkCSpy/index.htm. 
> Lately, I have been learning about abstract data types
> (linked lists, stacks, queues, trees, etc.).  While I
> do enjoy the challenge of creating these objects, I am
> not sure what they are used for.
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

They all have many uses. Priority Queues are used frequently in
operating systems for process scheduling, etc. Trees are fantastic for
most any searching application. Linked lists can be used for general
purpose storage (since unlike arrays, their size is not fixed.)

Learning data structures is really the one thing i wouldn't recommend
python for, just because the job is usually done for you. Why implement
a linked list, when we already have lists? Then Queues and Stacks are
trivial to implement once you've got lists.

If you're interested in learning more about data structures and their
uses, this looks like a good reference:
http://www.brpreiss.com/books/opus7/

-Jordan Greenberg

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] (*args, **kwargs)

2006-08-04 Thread Jordan Greenberg
Matt Williams wrote:
> Dear All,
> 
> I have learnt to do bits of python, but one of the things I cannot get 
> my head around is the *args, **kwargs syntax.
> 
> I have tried reading stuff on the web, and I have a copy of the python 
> cookbook (which uses it as a recipe early on) but I still don't 
> understand it.
> 
> Please could someone explain _very_ slowly?
> 
> Apologies for the gross stupidity,
> 
> Matt

Basically, *args and **kwargs allows you to collect arguments.
Normally, you'd do something like:
*args collects any arguments (other then the positional ones) into a
list, and **kwargs collects arguments into a dictionary.
In [6]: def foo(a, b, c):
   ...: print a, b, c
   ...:

In [7]: foo(1, 2, 3)
1 2 3

but, say you wanted to make it so it could accept any number of
arguments, you could use *args like so:
In [4]: def foo(*args):
   ...: print args
   ...: for each in args:
   ...: print each
   ...:

In [5]: foo(1, 2, 3, 4)
(1, 2, 3, 4)
1
2
3
4

Notice how all the parameters i passed to foo are collected in the list
args.

**kwargs collects arguments of the form key=value into a dictionary,
like so:

In [15]: def foo(**kwargs):
   :print kwargs
   :

In [16]: foo(name="Jordan", email="[EMAIL PROTECTED]")
{'name': 'Jordan', 'email': '[EMAIL PROTECTED]'}

Your functions can then use the list/dictionary as normal.
You can also use these in conjunction with normal positional parameters:

In [27]: def foo(a, b, c, *args, **kwargs):
   :print "Positional arguments:"
   :print a, b, c
   :print "Non-positional argument list:"
   :print args
   :for each in args:
   :print each
   :print "Keyword argument list:"
   :print kwargs
   :for key in kwargs.keys():
   :print "Key: ", key
   :print "Data: ", kwargs[key]
   :

In [28]: foo(1, "monkey", 7.5, 10, 11, 12, name="jordan",
email="[EMAIL PROTECTED]")
Positional arguments:
1 monkey 7.5
Non-positional argument list:
(10, 11, 12)
10
11
12
Keyword argument list:
{'name': 'jordan', 'email': '[EMAIL PROTECTED]'}
Key:  name
Data:  jordan
Key:  email
Data:  [EMAIL PROTECTED]

So, to summarize, *args and **kwargs are basically there so you can
build your functions so that they can accept a variable number of arguments.

We had a thread about this not terribly long ago too, and Kent Johnson
had a great explanation (as per usual) so I expect he'll be along
shortly with either a link to that thread or a better explanation then
mine!

Anyway, I hope this helps!
-Jordan Greenberg

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python for basic web-testing

2006-08-06 Thread Jordan Greenberg
Hans Dushanthakumar wrote:
> Hi,
>How do I use python for basic web-tasks like inputting data or
> clicking buttons on web-pages. For eg, how do I enter my username and
> password and click on the "OK" button on the yahoo mail page?
> I had a look at the webbrowser module documentation
> (http://www.python.org/doc/current/lib/module-webbrowser.html), but it
> doesnt seem to support clicking buttons or sending data.
> Thanks,
> Hans
>  

Hi Hans,
I'm sure its possible, though i haven't a clue how you'd go about doing
it. If its just for testing and you don't need it integrated with
python, you might want to check out Greasemonkey
(http://greasemonkey.mozdev.org/) or Chickenfoot
(http://groups.csail.mit.edu/uid/chickenfoot/) which make those kinds of
tasks absurdly easy.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] quick OO pointer

2006-08-07 Thread Jordan Greenberg
shawn bright wrote:
> Hello there,
> 
> a while back i wrote a module called DbConnector.py that allowed me to run
> different types of SQL queries. Cool enough.
> i did it mostly to handle the open and close of a db connection so i
> wouldn't have to worry about 'too many connection' errors.
> it makes a connection, runs a query, then closes the connection.
> The reason i write this, is that i know how the module works to make a
> connection 'object'
> now, i have a few functions in some scripts that i would like to reuse
> across the board. But, they dont really fit the "object" thing, i dont
> thing. Basically, i have a bunch of functions that do different things
> and i
> would like one script to hold them all.
> do i need to define a class for this, or can you import a function from
> another script ?
> 
> like if i have
> 
> def write_something_to_log(logfile, something)
>f = open(logfile, 'a')
>f.write('%s\n' % something)
>f.close()
>return 'success'
> 
> and i wanted to use this same function in about four different scripts,
> do i
> need a class ? Do i need to just create a script full of common functions
> that i can access ? and if so, how ?
> usually in the tutorials i read, they deal with OO and classes. Most
> commonly a class called Person. Then person has different attributes. But
> these functions are just bits of code that i want to reuse
> what is the cleanest way to do something like this ?
> 
> thanks
> 
> sk

If your function write_something_to_log is in file myfunctions.py you
can just do:
from myfunctions import write_something_to_log

and then use write_something_to_log() just like it was defined in that file.

Example:
#file: test1.py
def spam():
print "Spam, eggs, and toast"

#file: myscript.py
from test1 import spam
spam()
#prints "Spam, eggs, and toast"

Hope this helps!
-Jordan Greenberg

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Rock, Paper, Scissors

2006-08-07 Thread Jordan Greenberg
Christopher Spears wrote:

> This looks like a fun project to work on.  From
> reading the description, I feel this would be pretty
> straight forward game to program.  However, I have no
> idea how the computer would decide if it wanted a
> rock, paper, or a pair of scissors.  Any hints?


Since theres no real strategy to rock paper scissors, just generate a
random number from 0-2 like this:

import random

random.seed()

choice=random.randint(0, 2)
if choice==0:
#do whatever for rock
elif choice==1:
#do whatever for paper
else:
#do whatever for scissors

That'll take care of the basics for ya. Later you could try and keep
frequency counts over a bunch of trials, see if the human has a
preference, and then weight your response appropriately to try and beat
them ;)

-Jordan Greenberg

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] foreach loops

2006-09-11 Thread Jordan Greenberg
Christopher Spears wrote:
> Hmmm...Perl is probably a bad example.  My apologies. 
> I was thinking more along the lines of this:
> 
> A C++ for loop:
> 
> #include 
> 
> using std::cout;
> 
> int main() {
>   
>   for (int i = 0; i < 10; i++) {
>   cout << i << "\n";
>   }
>   
>   return 0; 
> }
> 
The same functionality can be provided using python for and the range()
function, like:

for i in range(0, 10):
print i


Though because of the way python works you don't need to use this type
of loop anywhere near as often as in other languages. For example in
java (and c++, but my c++ is so rusty I'm not going embarrass myself
trying to write an example) you're constantly doing things like looping
over an array:

public void main(String[] args) {
int[] foo;

/* then later after foo has been initialized to whatever: */

for (int i=0; ihttp://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Overloading the assignment operator in a class

2006-09-20 Thread Jordan Greenberg
Carroll, Barry wrote:
> Greetings:
> 
> I have a class that implements a die (singular or dice).  Here is the class 
> definition:

> How do I overload the '=' operator to give the desired behavior?
> 
> Regards,
>  
> Barry

AFAIK, you can't. Unlike, say, Java or C++, the assignment operator is
not operating on an object, but instead a name. Consider:

in C++ we define variables to a type:

int myInt;
Die myDie;

etc, etc. We don't do this is python. Instead we assign an *object* to
an *name*

myInt=5
myDie=Die(6, 3)

so that myDie is a name for the Die object you've just created.
But you can also do this in python:

myDie="Some string"

Its not assigning to the myDie object, just the name myDie, so that now
myDie is a name for a string containing "Some String"
In other languages, its reasonable to think of variables as containers.
That thinking isn't valid in Python. In Python, what you'd think of as
'variables' are just names for objects. (If you know C++, think
pointers, sort of. myDie isn't the Die Object, its just a reference as
to where the object is. Assigning to a pointer doesn't change the
object, but what the pointer is pointing to.)

Hope this helps,
Jordan Greenberg
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Overloading the assignment operator in a class

2006-09-20 Thread Jordan Greenberg
Alan Gauld wrote:
>> This all seems to work okay.  
>>
>> I want the assignment operator ('=') 
> 
> There is no assignment operator in Python, assignment is a 
> binding of an object to a name.
> 
>> to call the 
>> set method transparently on Die instances, 
>> as in this fictitious example:
> 
> @BCARROLL[Python]|6> mydie = 5
> @BCARROLL[Python]|7> mydie
>  <7> 5
> 
> But you can fake this by coercing the integer into a new 
> Die object. As if you had actually done
> 
> 
> mydie = Die(mydie.n,5)
> 
> And I believe you can do that by implementing the __coerce__ 
> method. - but I've never tried it...
> 
> HTH,
> 
> Alan G.
>

If you can do that with __coerce__, I'm not clever enough to figure out
how. IIRC, Python only calls __coerce__ if you're using arithmetic
operators on different types, and only if the operator in question isn't
overloaded to handle this case.

Ex:
In [1]: class coerceTest:
   ...: def __init__(self, val):
   ...: self.val=val
   ...:
   ...: def __coerce__(self, other):
   ...: return self.val, other

In [2]: test=coerceTest(5)

In [3]: test
Out[3]: <__main__.coerceTest instance at 0x00E29620>

In [4]: result=test+10

In [5]: result
Out[5]: 15

In [6]: test=5

In [7]: test
Out[7]: 5

(I could've written a test to show that __coerce__ is only called when
no __add__ is defined, but I'm lazy and its time to leave work!)

-Jordan Greenberg
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Trying to extract the last line of a text file

2006-10-19 Thread Jordan Greenberg
Chris Hengge wrote:
> Not to hijack the thread, but what stops you from just putting a
> file.close()
> after your example line?

Because file is a class.
file(filename) creates a file object, but he's not saving the object to
a variable, so its lost. file.close() takes a file object as a
parameter, but theres no object left to pass it.

HTH.
-Jordan Greenberg

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hardware specs from python on OSX

2006-11-08 Thread Jordan Greenberg
Yi Qiang wrote:
> Hi,
> I am trying to get some basic information about the computer's
> hardware specs in OSX in python.  In linux I can get most of what I
> need from the /proc filesystem.  Is there an equivalent in OSX?  If
> not, where else can I get information about the system from?  I need
> CPU model, # of cpus, cpu speed, physical memory, etc.
> 
> Thanks,
> Yi

Somewhat unsurprisingly, a quick google for "python system information
osx" turned up this recipe in the ActiveState cookbook:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303063
which should help.
Looking into the sysctl command might also be useful.

HTH, keep in mind that I'm *NOT* a Mac guy, at all.
Jordan
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Test

2006-11-28 Thread Jordan Greenberg
Hey, my messages don't seem to be showing up on the list...
So if this one works, sorry for the test message, everybody!
My school just decided not to allow any outgoing email to any SMTP
server but their own *grumble* So I've been sending my tutor messages
through that server but with this address munged into the headers.
Seems to send messages through fine, but I guess the list doesn't like
it for some reason. If this message works, it'll be proof of that
(since this is from the gmail web interface) and I'll re-subscribe to
the list from my other address ([EMAIL PROTECTED]) so my messages
will come from there from now on.

Sorry again for the test,
Jordan Greenberg
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Best Known Method for Filtering redundant list items.

2006-11-30 Thread Jordan Greenberg
Chris Hengge wrote:
> Anyone point me to something more efficient then
> 
> for item in list1:
> if item not in list2:
>   list2.append()
> 
> This just seems to take a bit a time when there are thousands or dozens of
> thousands of records just to filter out the dozen or so copies..
> 
> Thanks.

somewhat unsurprisingly, the first thing google lists for "python list
duplicates" is a quite good ASPN recipe to do just what you want.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Getting the directory the program is in

2006-12-11 Thread Jordan Greenberg
Toon Pieton wrote:
> Hey friedly users!
> 
> I was wondering: how can I get the directory the program is in? For example
> "C:\Python Programs\Calculator\".
> 
> Thanks in advance for reading,
> Toon Pieton
> 

Slightly hackish and nasty, but seems to do the trick. Someone'll
probably suggest a better way, this is just the first thing I could come
up with:


from os.path import abspath
from sys import argv

print abspath(argv[0])
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Getting the directory the program is in

2006-12-11 Thread Jordan Greenberg
Tor Hildrum wrote:
> The full pathname is in sys.argv[0]
At least on my system, it only includes the filename if executed from
the current directory.

Example:

[EMAIL PROTECTED]:/$ cd ~
[EMAIL PROTECTED]:~$ cat > test.py
from sys import argv
print argv[0]
[EMAIL PROTECTED]:~$ python test.py
test.py
[EMAIL PROTECTED]:~$ cd /
[EMAIL PROTECTED]:/$ python test.py
/home/jordan/test.py
[EMAIL PROTECTED]:/$

So, if you _ALWAYS_ need an absolute path, just using sys.argv[0] might
not work.

Jordan Greenberg


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Yet another list comprehension question

2007-03-02 Thread Jordan Greenberg
Smith, Jeff wrote:
> I find a common thing to do is
> 
> l = list()
> for i in some-iterator:
> if somefum(i) != list:
>   l.append(somefun(i))

How about using the same condition you do in the if? Like:
l=[somefun(i) for i in some-iterator if not type(somefun(i)) is list]

HTH
Jordan
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Addressing a variable whose name is the value of a string

2007-04-09 Thread Jordan Greenberg
Andreas Pfrengle wrote:
> Bob Gailer wrote:
> 
>> Andreas Pfrengle wrote:
>>
>>> Hello,
>>>
>>> I want to change the value of a variable whose name I don't know, but
>>> this name is stored as a string in another variable, like:
>>>
>>> x = 1
>>> var = 'x'
>>>
>>> Now I want to change the value of x, but address it via var. 
>> exec is the statement for doing this, but the need to do this can 
>> always be met better by using a dictionary instead of global variables.
>>
> Thanks Bob, the 'exec' saved me. But I'm not sure how I could solve my 
> specific problem with a dict, since my 'var' variable is a string I'm 
> getting from a database-field, that refers to the name of another field, 
> which should be changed. So I see no other way than resolving the string 
> in some instance - or is there?

Sure, you do something like:
mydict={'x':1, 'y':2}
var='x'
mydict[var]=5
and then you just access it like mydict['x'] instead of just x.
Jordan

-- 
I prefer encrypted mail. My key is available at:
http://myweb.wit.edu/greenbergj/publickey.txt
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Programming Tools

2008-04-14 Thread Jordan Greenberg
bhaaluu wrote:
 > A (mainly Java) programmer on a LUG mailing list asks:
 >
 > What is a good IDE [for Python] that has Python tools for:
 >
 > library management,
 > code completion,
 > debugging,
 > documentation,
 > help
 >
 > Since I'm not familiar with Java at all, I'm not sure how many
 > of the things he is asking for, are even relevant for Python?
 > I'm presuming he is working with a team, and is developing
 > complex programs.
 >
 > What do _you use?

Personally, I use Emacs for more or less everything. As far as a more 
complete IDE solution goes, PyDev for the Eclipse platform is pretty 
popular. If you're willing to spend some $$$, then PyDev Extensions 
(also for Eclipse) are good, or ActiveState's Komodo IDE. They seem to 
be the gold standard.

-Jordan Greenberg
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dollarize.py

2008-06-21 Thread Jordan Greenberg

Martin Walsh wrote:
> def addcommas(f):
>   """
>   This amounts to reversing everything left
>   of the decimal, grouping by 3s, joining
>   with commas, reversing and reassembling.
>   """
>   # assumes type(f) == float
>   left, right = ('%0.2f' % f).split('.')
>   rleft = [left[::-1][i:i+3] for i in range(0, len(left), 3)]
>   return ','.join(rleft)[::-1] + '.' + right

def addcommas(s): # assumes type(s)==str
b=[]
l=len(s)
for i,v in enumerate(s):
i+=1 # easier to understand w/ 1-based indexing, i think.
b.append(v)

if (l-i)%3==0 and not i==l:
b.append(',')
return ''.join(b)


or, somewhat more tersely:


def addcommas2(s):
l=len(s)
return ''.join(v+',' if (l-(i+1))%3==0 and not i+1-l==0
else v for i,v in enumerate(s))

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Alter print action for objects

2008-07-23 Thread Jordan Greenberg

Shrutarshi Basu wrote:

I'm working on a graph class to become more familiar with graphs in
general. I'd like to be able to do something like 'print gr'  and get
something intelligible like a list of vertices. But using print on a
Graph class instance simply returns 
Is there someway I can change what print prints?



print will print the string returned by an object's __str__ method.
Try something like this:

In [1]: class Example(object):
   ...: def __init__(self, x):
   ...: self.x=x
   ...: def __str__(self):
   ...: return "x is: %s"%(self.x)
   ...:

In [3]: ex=Example(5)

In [4]: print ex
x is: 5

The "basic customization" page in the Python Reference Manual may be of 
use as well: http://docs.python.org/ref/customization.html


HTH,
JordanG
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor