Re: [Tutor] Shadowrun programs

2005-01-18 Thread Sean Perry
Jack Cruzan wrote:
I am on the other coast but I too am looking for a group to play
Shadowrun with. 

With at least three people interested think we could either --
1) Port or create a python based SRCG (useless python still has a
challenge for a collaberative effort.)
2) Make a SR rpg (I was think of in the style of Rogue or net hack but
could be something more in depth)
3) Fun and Profit! -err uhm something like it?
My time is unfortunately limited. However, I am available for reviews, 
ideas, playtesting, etc.

For the record, I am a Linux user so it would be nice if any GUIs used a 
cross-platform toolkit.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Clash of the Titans and Mundane Matters

2005-01-20 Thread Sean Perry
Michael Powe wrote:
Clash of the Titans
snip constructor discussions
Pilgrim is pedantically correct but Alan's comment matches how most of 
us think about it.


Mundane Matters
I'm having a hard time with classes in python, but it's coming
slowly.  One thing that I think is generally difficult is to parse a
task into "objects."  Here's an example:  in Java, I wrote an
application to track my travelling expenses (I'm a consultant; this
tracking of expenses is the itch I am constantly scratching.  ;-)
I've also written this application in a perl/CGI web application as
well.)  It's easy to see the outline of this task:  create an abstract
class for expense and then extend it for the particular types of
expenses -- travel, food, transportation, lodging and so forth.  In
python, I guess I'd create a class and then "subclass" it.
while that is a valid approach, it is not how most of us would do it. By 
subclassing you have to edit the code every time a new expense type is 
added. Ever used MS Money or Quicken? Imagine if the type of each item 
was a subclass. Use a string.

A similar problem occurs with my HTML-parsing routine that I brought
to the list recently.  Use of HTMLParser was suggested.  I've looked
into this and usage means subclassing HTMLParser in order to implement
the methods in the way that will accomplish my task.  Conceptually,
I'm having a hard time with the "object" here.  (The fairly poor
documentation for HTMLParser doesn't help.)  Apparently, I'm creating
a "parser" object and feeding it data.  At least, that's the closest I
can get to understanding this process.  How I'm actually feeding data
to the "parser" object and retrieving the results are matters open to
discussion.  I'll be working on that when I get another chance.
This counts the tags in a html file piped in on stdin.
#!/usr/bin/python 

import sys, HTMLParser
class TagCounter(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.tags = {}
def handle_starttag(self, tag, attrs):
self.tags[tag] = self.tags.setdefault(tag, 0) + 1
if __name__ == '__main__':
counter = TagCounter()
for line in sys.stdin.xreadlines():
counter.feed(line)
counter.close()
print counter.tags
Finally, in terms of "understanding python," the question I keep
coming up against is:  why do we have both functions and methods?
What is the rationale for making join() a string method and a os.path
function?
a method is a function bound to a class. Nothing super special.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Should this be a list comprehension or something?

2005-01-26 Thread Sean Perry
Terry Carroll wrote:
 > My goal here is not efficiency of the code, but efficiency in my Python
thinking; so I'll be thinking, for example, "ah, this should be a list 
comprehension" instead of a knee-jerk reaction to use a for loop.

as Alan says, list comprehensions, like map should be used to generate
new lists. What you should have thought was -- hmm, this looks like a
job for reduce!
def sumWater(w1, w2):
total_mass = w1.mass + w2.mass
numerator = (w1.mass * w1.temperature) + (w2.mass * w2.temperature)
return Water(total_mass, numerator / total_mass)
def CombineWater(WaterList):
return reduce(sumWater, WaterList)
if __name__ == '__main__':
w1 = Water(50,0)
w2 = Water(50,100)
w3 = Water(25,50)
print CombineWater2((w1,w2,w3))
Now, the sum_water function could also be folded into the Water class as
an __add__ method if you like as someone else suggested.
See, the problem with your old code was that the list walking and the
summation were done by the same code. By pulling sumWater out you can
test it separately. You could also pass different functions to CombineWater.
And now, for the pedant in me. I would recommend against naming
functions with initial capital letters. In many languages, this implies
a new type (like your Water class). so CombineWater should be combineWater.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Should this be a list comprehension or something?

2005-01-27 Thread Sean Perry
Brian van den Broek wrote:
Sean Perry said unto the world upon 2005-01-27 02:13:

And now, for the pedant in me. I would recommend against naming
functions with initial capital letters. In many languages, this implies
a new type (like your Water class). so CombineWater should be 
combineWater.

Do you mean implies by the dominant coding conventions, or by language 
syntax? (Indulging the curious pedant in me.)

In many OO languages, it is tradition to name types with capital letters 
 (TFoo anyone?) and functions / methods with initial small then caps 
(camelCase).

Haskell actually enforces this rule (nifty functional language). Python 
and it share a lot in common.

(As an anti-example)
Erlang enforces capital letters for variable names ONLY. A little odd 
and definitely takes some getting used to.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding

2005-01-30 Thread Sean Perry
Kim Branson wrote:
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1
Hi all,
heres a quick one for you,
I have a series of data that I am using dictionaries to build histograms 
for. I'd like to round the data to the nearest 10, i.e if the value is 
15.34  should we round down to 10? and conversely rounding say 19.30 to 
20. I'm thinking 15.5 and above would round up. Can anyone point me a at 
a quick and painless way of achieving this?

def round10s(f):
rem = f % 10
tens = int(f / 10)
if rem >= 5.5:
return (tens + 1.0) * 10.0
return tens * 10.0
if __name__ == '__main__':
tests = [15.34, 15.54, 19.65, 2.34, 8.2, 0.0, 20.0]
for i in tests:
print "%.2f: %.2f" % (i, round10s(i))
yields
15.34: 10.00
15.54: 20.00
19.65: 20.00
 2.34:  0.00
 8.20: 10.00
 0.00:  0.00
20.00: 20.00
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dividing 1 by another number ?

2005-01-30 Thread Sean Perry
Tony Meyer wrote:
Dividing two integers will give you an integer (truncated) result:
If you want '1/2' to give you 0.5 (throughout your script), you can do:
from __future__ import division
Notice that '//' (with or without the from __future__ import) will give you
the integer result.
or more simply, divide by 4.0 for rod and bore: (rod**2/4.0)
what happens if rodarea is bigger than area?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-02 Thread Sean Perry
Liam Clarke wrote:
4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!!
I'm not referring to the $ & @, I can see how they could be useful,
although with a list -
@dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], 
not $d  = $dude[1], that's counterintuitive also. 

(I am an ex-perler gone clean. Been straight for 5 years now with only 
the occasional work forced binges.)

Perl was designed by a linguist. He wanted it to act like human language 
-- which is not very consistent.

That said, perhaps I can shed some light on the symbols.
Ever learned a Romance language? latin, spanish, french, etc? The 
dollars and at signs can be thought of in relation to plural endings.

$foo --> dog
@dog --> a group of dogs
$dog[0] --> a dog in the group
So when you mean "the whole group" use the plural spelling and when you 
want to refer to a member use the singular spelling. Likewise with other 
parts of the language.

Personally, the thing that keeps me away from Perl is nested datastructures.
Python:
my_list = []
a_dict = {.}
b_dict = {.}
my_list.append(a_dict)
my_list.append(b_dict)
if my_list[0].has_key("foo"): print "Yes"
easy. Try that in Perl.
my @my_list; # remember those semicolons
my %a_dict, %b_dict;
push @my_list, %a_dict;
push @my_list, %b_dict;
if (exists $my_list->[0], "foo") print "Yes\n";
# yes, references required, in Perl ick.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Sean Perry
[EMAIL PROTECTED] wrote:

Btw, I'm skeptical that the code below does what you want it to do.  :-)
 
that was kind of my point. In python I just type the obvious and it 
works. In Perl I have to muck with references, slashes, arrows and the 
like. Every time I have had to write a nested datastructure I have spent 
my time debugging that structure.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Ogg Tag Module recommendations

2005-02-03 Thread Sean Perry
Miles Stevenson wrote:
Can anyone recommend to me a Python module to work with ID3v2 tags in Ogg 
Vorbis files? I tried using the EyeD3 module, but it only supports mp3 right 
now, and I couldn't get the pyid3tag module to work reliably, or I'm just not 
understanding the documentation.

I just need to retrieve all of the ID3v2 tag info from a collection of ogg 
files, store them in a file, and then insert them back into different ogg 
files. Anyone have a module/library they recommend?

The Ogg guys actually made a wrapper for Python, pyvorbis I think it is 
called.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-03 Thread Sean Perry
Jeff Shannon wrote:
However, Python doesn't need lambdas to be able to write in a functional 
style.  Functions are first-class objects and can be passed around quite 
easily, and IIRC Python's list comprehensions were borrowed (though 
probably with notable modification) from Haskell.

Note, it is haskell convention to name a list of objects with a plural. 
So xs -> list of x.

haskell:
[ x | x <- xs ]
[ foo x | x <- xs, x > 2 ]
python
[ x for x in xs ]
[ foo(x) for x in xs if x > 2 ]
shaleh
still mastering haskell, but loving it. Like python for functional 
languages.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Are you allowed to shoot camels? [kinda OT]

2005-02-04 Thread Sean Perry
Alan Gauld wrote:
Sean, what book/tutor are you using for Haskell?
I learned it from "The Haskell School of Expression" which 
was OK but very graphics focused, I'd be interested in 
recommended second source on Haskell.

as with Max I am reading Haskell: Craft of Functional Programming. I am 
about half way through it (have not got to Monads yet which are the mind 
benders).

So far I really like it. Thought provoking examples and exercises. 
However there are no answers to the exercises. Which for a relative 
newbie to functional programming would have been nice.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help with HTMLParseError

2005-02-18 Thread Sean Perry
Peter Kim wrote:
I'm using HTMLParser.py to parse XHTML and invalid tag is throwing an
exception.  How do I handle this?
1. Below is the faulty markup.  Notice the missing >.  Both Firefox
and IE6 correct automatically but HTMLParser is less forgiving.  My
code has to be able to treat this gracefully because I don't have
control over the XHTML source.
###/

/###
what you want is to encapsulate check_for_whole_start_tag() in your own 
parser class. Call the parent's version, if it returns -1, do some fuzzy 
logic (well, maybe if I add a '>', now does it work?), and continue.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SubClassing

2005-02-24 Thread Sean Perry
Ismael Garrido wrote:
Hello
My code is like this:
class Parent:
   def __init__(self, bunch, of, variables):
  self.bunch, self.of, self.variables = bunch, of, variables
class Son(Parent):
   def __init__(self, bunch, of, variables, new):
  self.bunch, self.of, self.variables, self.new = bunch, of, 
variables, new

What I want to know is, is there a better way to write Son class? One in 
which I don't have to copy&paste the parent's init?

yep. call 'Parent.__init__(this, that)' then do 'self.new = new'
def __init__(self, this, that, new):
Parent.__init__(this, that)
self.new = new
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SubClassing

2005-02-25 Thread Sean Perry
Ismael Garrido wrote:
Sean Perry wrote:
yep. call 'Parent.__init__(this, that)' then do 'self.new = new'
def __init__(self, this, that, new):
Parent.__init__(this, that)
self.new = new

Thanks.
Though it should be:
def __init__(self, this, that, new):
   Parent.__init__(self, this, that)  #note self
   self.new = new
been doing a bunch of C++ programming. C++ -> python I always forget 
about self. python -> c++ I always forget the semicolons (-:
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading from stdin

2005-03-01 Thread Sean Perry
Nick Lunt wrote:
The way I did this was to use sys.stdin.readlines() to get the output
from the pipe.
Here is the program:
[code]
import sys, glob
args = sys.stdin.readlines() # found on the net
pat = sys.argv[1]
for i in args:
if (i.find(pat) != -1):
print i,
[/code]
My question is am I getting the output from the pipe in the correct
way ? The way Im doing it works (so far) but should I be doing it
another way ?
unless you want the output for some other reason, a more idiomatic way
is:
for line in sys.stdin.readlines():
# handle the line
I tend to use xreadlines() which does not read the entire input at once. 
 For stdin this make sense, you have no idea how much data will be 
piped in.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading from stdin

2005-03-01 Thread Sean Perry
[EMAIL PROTECTED] wrote:
If I do:
$ ./produce.py | ./read.py
I get nothing for ten seconds, then I get the numbers 0 through 9, one per line.
What am I missing?
From the python man page:
-u
Force stdin, stdout and stderr to be totally unbuffered. On systems 
where it matters, also put stdin, stdout and stderr in binary mode. Note 
that there is internal buffering in xreadlines(), readlines() and 
file-object iterators ("for line in sys.stdin") which is not influenced 
by this option. To work around this, you will want to use 
"sys.stdin.readline()" inside a "while 1:" loop.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slow html generation code

2005-03-02 Thread Sean Perry
Luis N wrote:
This code seems a little slow, is there anything in particular that
jumps out as being not quite right.
The idea is that a file is opened that contains path names to other
files, that are appended and outputed into a directory of choice.
I plan to move this off the filesystem into a database when the
concept is worked out, maybe that will help.
You are reading entire file contents into memory. Once with 
f.readlines() and then again with structure.read(). If these are 
somewhat large files that could definitely be a place for slowness. If 
nothing else, Python promises garbage collection to be done, but not 
when. So many of your files could be sitting in memory.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expression question

2005-03-08 Thread Sean Perry
Mike Hall wrote:
I'd like to get a match for a position in a string preceded by a 
specified word (let's call it "Dog"), unless that spot in the string 
(after "Dog") is directly followed by a specific word(let's say "Cat"), 
in which case I want my match to occur directly after "Cat", and not "Dog."

I can easily get the spot after "Dog," and I can also get it to ignore 
this spot if "Dog" is followed by "Cat." But what I'm having trouble 
with is how to match the spot after "Cat" if this word does indeed exist 
in the string.


. >>> import re
. >>> my_re = re.compile(r'(dog)(cat)?') # the ? means "find one or zero 
of these, in other words cat is optional.
. >>> m = my_re.search("This is a nice dog is it not?")
. >>> dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 
'groups', 'span', 'start']
. >>> m.span()
(15, 18)
. >>> m = my_re.search("This is a nice dogcat is it not?")
. >>> m.span()
(15, 21)

If m is None then no match was found. span returns the locations in the 
string where the match occured. So in the dogcat sentence the last char 
is 21.

. >>> "This is a nice dogcat is it not?"[21:]
' is it not?'
Hope that helps.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] regular expression question

2005-03-08 Thread Sean Perry
Mike Hall wrote:
First, thanks for the response. Using your re:
my_re = re.compile(r'(dog)(cat)?')

...I seem to simply be matching the pattern "Dog".  Example:
 >>> str1 = "The dog chased the car"
 >>> str2 = "The dog cat parade was under way"
 >>> x1 = re.compile(r'(dog)(cat)?')
 >>> rep1 = x1.sub("REPLACE", str1)
 >>> rep2 = x2.sub("REPLACE", str2)
 >>> print rep1
The REPLACE chased the car
 >>> print rep2
The REPLACE cat parade was under way
...what I'm looking for is a match for the position in front of "Cat", 
should it exist.

Because my regex says 'look for the word "dog" and remember where you 
found it. If you also find the word "cat", remember that too'. Nowhere 
does it say "watch out for whitespace".

r'(dog)\s*(cat)?' says match 'dog' followed by zero or more whitespace 
(spaces, tabs, etc.) and maybe 'cat'.

There is a wonderful O'Reilly book called "Mastering Regular 
Expressions" or as Danny points out the AMK howto is good.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] working with new classes

2005-03-09 Thread Sean Perry
C Smith wrote:
###
class Ring(list):
def __init__(self, l):
self[:] = l
self._zero = 0
   
def turn(self, incr=1):
self._zero+=incr

def __getitem__(self, i):
return self[(i-self._zero)%len(self)]
l=Ring(range(10))
print l
l.turn(5)
print l#same as original
print l[0] #crashes python
###
This is a classic mistake. l[0] --> l.__getitem__(l, 0), which you 
understand. However in __getitem__ you then call self[] which will just 
call __getitem__ again. and again. and again. 

The way out is to explicitly call the parent's __getitem__.
def __getitem__(self, i):
# list is out parent, call its method
return list.__getitem__(self, (i - self._zero) % len(self))
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Whats so good about OOP ?

2005-03-12 Thread Sean Perry
Brian van den Broek wrote:
1) Namespace issues
With procedural (or imperative -- don't know which is the right terms
for non-OOP code which employs functions) code, you can have issues
caused by namespaces. Just yesterday, someone on the main python
list/newsgroup had code something like:
procedural v. OO
imperative v. functional
In an imperative language you tell the computer what to do (imperative):
"put 5 in X, use X in function foo, store foo's result in blah". The 
base component is an imperative statement. If you have not had an 
English grammar class recently imperative sentences are things like 
"You, bring me my supper".

In a functional language, the base item is a function.
foo(X(blah())) or for the lispy people (foo (x (blah))).
You could do OO in a functional language. Haskell for instance has a 
concept of classes, user defined types, polymorphism, etc.

The point is, these are two axes on the programming language chart.
procedural, imperative -> C
OO, functional -> OCaml (close enough anyways)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Whats so good about OOP ?

2005-03-12 Thread Sean Perry
Mark Kels wrote:
Hi list !
I want to know whats so great in OOP...
I have learned some of it, but I don't understand why everybody like
it so much...
Can anyone give me an example for a task that could be done only with
OOP or will be much simpler to do with it ?
Thanks in advance.
Other commenters on this thread have covered OO fairly well. I have one 
clarification detail to add.

In procedural code, you spend a lot of time micromanaging:
put that there
blah + quz is bar
etc
In OO code, you tell each object how to handle its data. Then your 
actual program just becomes a bunch of requests for objects to talk to 
each other. I know, you are thinking that is how your procedural code 
works today. But as you program, look at how much time you are telling 
the pieces what their jobs are and how much time you spend telling 
pieces to do their jobs.

For further knowledge, read the Design Patterns book. It will seem like 
obvious, simple ideas you already know. It did for me. It is not until 
you start talking to other people that you realize what you learned. I 
am currently reading Holub's "On Patterns". He hammers OO ideas home 
pretty well.

As Alan Gauld said, OO does not really start to shine until you reach a 
certain level of complexity. It takes most people quite a while to 
really get into the mindset. Take it slow, get it wrong, do it again (-: 
We all have.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes

2005-03-17 Thread Sean Perry
Danny Yoo wrote:
Here is one that's traduced... er... adapted from material from the
classic textbook "Structure and Interpretation of Computer Programs":
##
from itertools import ifilter, count
def notDivisibleBy(n):
... def f(x):
... return x % n != 0
... return f
...
def sieve(iterable):
... nextPrime = iterable.next()
... yield nextPrime
... restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable))
... for prime in restOfPrimes:
... yield prime
...
primes = sieve(count(2))
primes.next()

which is cool, until you try to use it (-:
It dies at 999 primes due to an overloaded stack. Bummer. It is such a 
nifty implementation.

I modified this version to follow it better.
from itertools import ifilter, count
def notDivisibleBy(n):
def f(x):
return x % n != 0
return f
def sieve(iterable):
nextPrime = iterable.next()
print 'x', nextPrime
yield nextPrime
restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable))
for prime in restOfPrimes:
print 'p', prime
yield prime
primes = sieve(count(2))
current = primes.next()
count = 1
while current <= 20:
print 'Prime:', current
current = primes.next()
count += 1
The output is (note this is each prime < 20):
x 2
Prime: 2
x 3
p 3
Prime: 3
x 5
p 5
p 5
Prime: 5
x 7
p 7
p 7
p 7
Prime: 7
x 11
p 11
p 11
p 11
p 11
Prime: 11
x 13
p 13
p 13
p 13
p 13
p 13
Prime: 13
x 17
p 17
p 17
p 17
p 17
p 17
p 17
Prime: 17
x 19
p 19
p 19
p 19
p 19
p 19
p 19
p 19
Prime: 19
x 23
p 23
p 23
p 23
p 23
p 23
p 23
p 23
p 23
Not exactly efficient.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes

2005-03-18 Thread Sean Perry
Pierre Barbier de Reuille wrote:
def sieve( max ):
  max_val = int( sqrt( max ) )
  s = Set(xrange( 4, max, 2 ))
  for i in xrange( 3, max_val, 2 ):
s.update( xrange( 2*i, max, i ) )
  return [ i for i in xrange( 2, max ) if i not in s ]
just for grins, here is the same (mostly) code in haskell
import Data.Set(elems, fromList, member, union)
primeSieve :: Int -> [Int]
primeSieve n = [ prime | prime <- [ 2 .. n ], not $ prime `member` 
nonPrimes ]
  where
evenSet = fromList [4, 6 .. n ]
xIncrements x   = [ 2 * x, (2 * x) + x .. n ]
maxVal  = floor . sqrt $ fromIntegral n
oddSet  = fromList . concat $ map xIncrements [ 3, 5 .. 
maxVal ]
nonPrimes   = union evenSet oddSet

fromList makes a list into a Set. [ x | x <- y, pred ] is analogous to 
Python's [ x for x in y if pred x ]. The '$' operator removes the need 
for parens.

foo $ bar baz --> foo (bar baz)
oh and '.' is the function composition operator.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Prepend to a list?

2005-03-19 Thread Sean Perry
Jay Loden wrote:
How can I prepend something to a list? I thought that I could do
list.prepend()  since you can do list.append() but apparently not.  Any way to 
add something to a list at the beginning, or do I just have to make a new 
list? 

>>> a = []
help(a.insert) 
insert(...)
L.insert(index, object) -- insert object before index
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why is this not an error?

2005-03-20 Thread Sean Perry
Hameed U. Khan wrote:
This else is the part of the for loop. And the statements in this else will be 
executed if your for loop will complete all of its iterations. if you want 
this else with 'if' statement then remove the for loop.

for instance:
looking_for = 11
for i in range(0,10):
if i == looking_for:
handle_it(i)
break
else:
print "Did not find", looking_for
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes (generator)

2005-03-20 Thread Sean Perry
Gregor Lingl wrote:
The following variation of your sieve, using
extended slice assignment  seems to
be sgnificantly faster. Try it out, if you like.
Here are the numbers:
Primes 1 - 1,000,000 timing:
   extendedSliceSieve: 0.708388 seconds
   listPrimes: 0.998758 seconds
karlSieve: 1.703553 seconds
primeConciseOptimized: 5.133922 seconds
 setSieve: 7.564576 seconds
 primeConcise: 1644.683214 seconds --> 27 minutes 24 seconds
if __name__ == '__main__':
# setup timers as a list of tuples (name, timeit instance)
results = []
longest = 0
for t in timers:
result = t[1].timeit(1)
longest = max(longest, len(t[0]))
results.append((t[0], result))
results.sort(lambda x, y: cmp(x[1], y[1]))
print "Primes 1 - 1,000,000 timing:"
format_str = "%%%ds: %%f seconds" % longest
for i in results:
print format_str % i
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Filtering a String

2005-03-20 Thread Sean Perry
Matt Williams wrote:
Dear List,
I'm trying to filter a file, to get rid of some characters I don't want
in it.
I've got the "Python Cookbook", which handily seems to do what I want,
but:
a) doesn't quite and 
b) I don't understand it

I'm trying to use the string.maketrans() and string.translate(). From
what I've read (in the book and the Python Docs), I need to make a
translation table, (using maketrans) and then pass the table, plus and
optional set of characters to be deleted, to the translate() function.
I've tried:
#!/usr/bin/python
import string 
test="1,2,3,bob,%,)"
allchar=string.maketrans('','')
#This aiming to delete the % and ):
x=''.translate(test,allchar,"%,)")

but get:
TypeError: translate expected at most 2 arguments, got 3
Please could someone explain this to me (slowly).
Here is an updated version.
#!/usr/bin/python 

import string
test = "1,2,3,bob,%,)"
allchar = string.maketrans('','')
#This aiming to delete the % and ): 

x = test.translate(allchar,"%,)")
print x
# end
x = test.translate() rather than x = ''.translate() is the key. You want 
to call the translate method of the test string. Your code could have 
worked by doing 'x = string.translate(test, allchar, "blah")' which uses 
the translate function in the module named 'string'. Confusing because 
the names are the same.

You received an error because ''.translate() only needs the table and 
the deletechars string. I personally avoid empty string methods 
(''.translate, ''.join, etc) because they can be visually confusing and 
definitely confound the new python programmers.

A comment on style. Use spaces around assignments -- x=5 should be x = 5.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] import statements in functions?

2005-03-21 Thread Sean Perry
Marcus Goldfish wrote:
Is there a convention to be considered for deciding if import
statements should be included in a function body?  For example, which
of these two module layouts would be preferable:
imports are cached. So once it is imported, it stays imported.

The reason I consider the second form is that the module foo_special
is only used by the code in specialFunction(), and detracts (IMHO)
from understanding the rest of the code in the module.
and this is a good reason why you would perform the import inside the 
function.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT - SQL methodology.

2005-03-21 Thread Sean Perry
Liam Clarke wrote:
Hi, 

This is a SQL query for the advanced db gurus among you (I'm looking at Kent...)
After I've run an insert statement, should I get the new primary key
(it's autoincrementing) by using PySQLite's cursor.lastrowid in a
select statement, or is there a more SQLish way to do this?
In the SQL books I've got, they always seem to have an optional select
statement on the end of inserts/updates, and I was thinking maybe I
could do it that way also, but I can't figure out a logical way of
putting
'select primary_key from foo where primary_key value > every other
primary_key value'
select max(primary_key) from foo?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for a Pythonic way to pass variable number of lists to zip()

2005-03-21 Thread Sean Perry
Tony Cappellini wrote:

I have a program which currently passes 6 lists as arguments to zip(), 
but this could easily change to a larger number of arguments.
Would someone suggest a way to pass a variable number of lists to zip() ?

well, I would have said "apply(zip, (l1, l2, l3, ...))" but apply has 
been deprecated in 2.3.

So how about this?
arg_list = []
# fill up arg_list
zipped = zip(*arg_list)
?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for a Pythonic way to pass variable

2005-03-22 Thread Sean Perry
Shidai Liu wrote:
On Tue, 22 Mar 2005 15:27:02 -0500, Bill Mill <[EMAIL PROTECTED]> wrote:
zip(K, *L)
[(100, 1, 3), (200, 2, 4)]

Any idea why zip(*L, K) fails?
I believe the *'ed item needs to be the last argument.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] iterating through large dictionary

2005-03-22 Thread Sean Perry
D:\Python24>ad-attr.py
Traceback (most recent call last):
 File "D:\Python24\ad-attr.py", line 32, in ?
   for k, v in ad_dict(user):
ValueError: too many values to unpack

Try this instead ... I think it should help:

for k,v in ad_dict(user).items():

in 2.3 and newer, the preferred function is 'iteritems()' instead of 
'items()'. Faster, less mem use, etc.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Apology

2005-03-22 Thread Sean Perry
gerardo arnaez wrote:
I apologize to the group for the dupes and not cutting the extended
tail of my previous messages
apology accepted. Your penance is to rewrite one of your python programs 
in Perl.

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


Re: [Tutor] What does Python gain by having immutable types?

2005-03-22 Thread Sean Perry
Tony C wrote:
The list variable is the same object, and contains the sorted list, so
why bother with the complexity of immutable types at all?
* only immutable objects can be dictionary keys
* specifically immutable strings are a performance optimization
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List comprehensions

2005-03-23 Thread Sean Perry
Liam Clarke wrote:
Is there any guides to this (possibly obtuse) tool?
Think of it this way. A list comprehension generates a new list. So, you 
should think about list comps whenever you have old_list -> new_list 
style behavior.

There are two advantages to list comps over map:
1) a list comp can use a predicate to filter results
[ x for x in mylist if is Prime(x) ] for instance. that would be 
map(lambda x: x, filter(isPrime, mylist)) which is a little more dense.

2) usually there is no need for a lambda. Not that there is anything 
wrong with lambdas mind you (-:

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


Re: [Tutor] Unique elements mapping

2005-03-25 Thread Sean Perry
Srinivas Iyyer wrote:
Hi all:
I have a question and I request groups help please.
My list has two columns:
NameState
DrewVirginia
NoelMaryland
NikiVirginia
Adams   Maryland
JoseFlorida
Monica  Virginia
Andrews Maryland
I would like to have my ouput like this:
Virginia :  Drew,Niki,Monica
Maryland:   Noel,Adams, Andrews
Florida:  Jose
Can you help how should I code :
for line in my_list:
key = line.split('\t')[0]
val = line.split('\t')[1]


dict = dict(zip(key,val))
this was my strategy ... but I could not make it
work.. 
You have the right idea. Just bad implementation (-:
uniques = {} # never name them 'dict', that is a type name in python
for line in my_list:
key, val = line.split('\t')
uniques.setdefault(val, []).append(key)
# in Python 2.4 the following two lines can be shortened to
# sorted_keys = sorted(unique.keys())
sorted_keys = unique.keys()
sorted_keys.sort()
for item in sort_keys:
print "%s: %s" % (item, ",".join(unique[item]))
So what we are doing is making a dict for which each element is a list 
of names. The setdefault trick above is a neater way of saying:

if not uniques.has_key(val):
uniques[val] = []
uniques[val].append(key)
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a shorter way to write this

2005-03-25 Thread Sean Perry
jrlen balane wrote:
basically, i'm going to create a list with 96 members but with only one value:
list1[1,1,1,1...,1]
is there a shorter way to write this one???
def generateN(n):
while 1:
yield n
I'll leave the actual list creation up to you (-:
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] a shorter way to write this

2005-03-25 Thread Sean Perry
Smith, Jeff wrote:
For all the talk of Python only having one way to do something which is
why it's so much better than Perl, I've counted about 10 ways to do this
:-)
Knowing you said this at least half in jest, I still feel the need to 
comment.

In any programming language, you have flexibility in how to define an 
algorithm. Think about how many different ways you can ask "is this 
string a in that string b?".

The Python motto is actually better stated: there is one obvious way and 
it is often the right one.

In the Python 1.5 days, choices were much fewer. With the new versions 
have come a more rich selection of features.

Python's "only one way" is often brought up as a counterpoint to Perls 
TIMTOWTDI. Remembering which Perl idiom is the right one, for the right 
situation *AND* matches the rest of the project can be a real nightmare. 
Not to mention that choosing the wrong one often kills your performance 
(-: This is a big reason why I stick to Python. We may have choices, but 
they are often clear and obvious once you know the language.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dates and databases, and blobs and Python.

2005-03-26 Thread Sean Perry
Liam Clarke wrote:
And then there's the overall question -
What would be the least fiddly & least error prone way of working with
dates and times? Python or SQL?
Liam, SQL is another language. You need to learn it like you are 
learning Python. It has pretty decent support for dates and times as 
part of the ANSI SQL spec.

There are defined types, SQL functions, etc.
week(date) = week(mydate) for instance.
I tend to prefer to write programming language agnostic databases 
because that way I can interact with them from any random language I 
need to. Sometimes things go bad and a quick little script which does:

rows = exec("select * from table")
exec("begin transaction")
for row in rows:
row[3] = row[2] + row[4] - 5 # we decided on a new value
exec("update fields in table")
can be handy.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] primes - sieve of odds

2005-03-26 Thread Sean Perry
John Miller wrote:
How does one actually use this module? For example:
 >>> import eratosthenes
 >>> eratosthenes.primes()

 >>> eratosthenes.primes().next()
2
 >>> eratosthenes.primes().next()
2
 >>> eratosthenes.primes().next()
2
How does one get beyond the first prime?
it = eratosthenes.primes()
it.next()
it.next()
or
# 'it' is shorthand for iterator
def primesToN(n):
it = eratosthenes.primes()
return [ x for x in it if x <= n ]
You were running into problems because the primes() function returns a 
new generator. The values are in the generator not the function primes().
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How and where to use pass and continue

2005-03-27 Thread Sean Perry
Kevin wrote:
I am having lot of trouble learning where and when to use pass and
continue. The two books that I use don't explian these very good. Is
there a website the explains these is great detail?
I have also looked at the python tutorial as well.
language idioms are one of the hardest things to learn and only really 
come after having written code and then coming back to it later.

My thoughts on the subject.
continue is a common idiom in I/O routines.
for line in fp.xreadlines():
line = line.strip()
if not line: continue
# process line data here
pass is an odd one. I tend to use it while prototyping to set up the 
bones of control statements to be.

def func(one, two):
if sometest(one):
pass # need to actually do something here
# work with one and two
pass can also be used in multi-catch functions / control statements
if input == 'something':
handle_something(input)
elif input == 'other':
pass
else:
# do stuff here
We want to ignore 'other' for some reason, so just use pass. Also handy 
if a value could be one of N choices but we only handle a few cases. 
This way someone else reading the code does not think "hey wait, they do 
not check for 'foo'!".
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How and where to use pass and continue

2005-03-27 Thread Sean Perry
Kevin wrote:
Ok I have another question now I noticed that at the tope of a while
loop there will be somthing like this:
test = None
while test != "enter":
 test = raw_input("Type a word: ")
 if test == "enter":
  break
what is the purpose of test = None ?
'test' must be given a value before Python will use it.
Without the first assignment, the program will fail to execute the first 
time it reaches the unknown variable.

Think of it as riming the pump.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If elif not working in comparison

2005-03-28 Thread Sean Perry
gerardo arnaez wrote:
On Mon, 28 Mar 2005 09:27:11 -0500, orbitz <[EMAIL PROTECTED]> wrote:
Floats are inherintly inprecise.  So if thigns arn't working like you
expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same
number than you think.

Are you telling me that I cant expect 2 digit preceision?
Not without using round. Have *NO* faith in floating points. This is 
especially true when you are creating the decimals via division and the 
like.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If elif not working in comparison

2005-03-29 Thread Sean Perry
Kent Johnson wrote:
Not without using round. Have *NO* faith in floating points. This is 
especially true when you are creating the decimals via division and 
the like.

What?!?!
OK, floats don't necessarily have the exact values you expect (they may 
have errors after many decimal places), and comparing floats for 
equality is risky business (you should compare for close, not equal). 
But the errors are well past the two-digit place. See the FAQ for more 
info on one kind of error:
http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate 

Note that the original poster was looking at ranges, not looking for 
exact matches!

Can you be more specific about what kinds of problems you have had?
sure, what is 2/3? 0.66? 0.67?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] If elif not working in comparison

2005-03-29 Thread Sean Perry
Smith, Jeff wrote:
Which is just what you'd expect.
It's absolutey absurd to tell someone to have *NO* faith in floating
numbers.  It's like anything else in programming: you have to understand
what you are doing.
Unless a float that has been through a round function I do not trus it. 
That is what I mean by no faith.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class and methods?

2005-03-30 Thread Sean Perry
Kevin wrote:
In a class is every def called a method and the def __init__(self) is
called the constructor method? This class stuff is a little confusing.
I don't have a problem writting a def I am still not clear on how to
use a constructor. Is there a site that explains the constructor in
great detail?
a method is simply a function attached to an object which acts on that 
object. Nothing fancy.

You can think of __init__ as a constructor. I have seen Python people 
refer to it as an initializer as well.

All __init__ is doing is preparing the object for use. Give initial 
values to any variables, setup any datastructures, and/or maybe call a 
few other functions / classes.

thing = MyClass(a,b)
the call to MyClass above gets mapped to MyClass.__init__(a,b). 
Logically the flow is:

Python makes an instance of the object (MyClass)
Python calls __init__ if it is defined
when __init__ returns Python assigns the object to the waiting variable
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I am puzzled - help needed

2005-03-30 Thread Sean Perry
John Carmona wrote:
I am not sure that it is possible to ask that question please feel free 
to turn me down if it is going against the forum rules.

I have going through Josh Cogliati tutorial, I am stuck on one of the 
exercise. I need to rewrite the high_low.py program (see below) to use 
the last two digits of time at that moment to be the "random number". 
This is using the import time module.

I just can't work out how to do that, I have been looking at it for the 
past 2,5 hours but can't break it. Has anyone done it in order for me to 
study it.

Many thanks in advance for any help
It helps to know what you are having prolems with. Can you not get the 
time from the time module? Is getting the last two digits causing you fits?

We do not mind helping people learn or even do their homework. We just 
don't like to give out the answers (-:

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


Re: [Tutor] sorting a list of dictionaries

2005-04-12 Thread Sean Perry
Gooch, John wrote:
I am working on a dictionary sorting problem just like the one in the email
thread at the bottom of this message. My question about their solution is:
In these lines:
lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
where field is either 'name' or 'size'.
What is "n:" and what is "lambda m" ? 

#!/usr/bin/python 

lst = [{"foo": 6, "bar": 10}, {"foo": 1, "bar": 2}]
field = "foo"
sort_func = lambda m, n: cmp(m.get(field), n.get(field))
lst.sort(sort_func)
print sort_func(lst[0], lst[1])
print lst
lambda creates a nameless function.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Has anyone ever tried to convert the textual output of the dis module to another language

2005-04-17 Thread Sean Perry
R. Alan Monroe wrote:
Just curious. Googling for 'python "dis module" convert "another
language" ' only got two hits. So maybe no one is trying it? I was
just daydreaming about a native python compiler, and wondered how
feasible it would be.
There is already a python -> exe converter. Comes up on the list now and 
then. What would your idea change?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Has anyone ever tried to convert the textual output of the dis module to another language

2005-04-17 Thread Sean Perry
R. Alan Monroe wrote:
The main things about it that would make it appealing to me:
#1 - MUCH MUCH MUCH smaller exes. Speed is not an issue to me, but
filesize is. Have you ever compiled "Hello world" in a new language,
and found that the exe was 100K+, when it really only needs to be less
than 1K? And py2exe... I am not averse to using it, but 800 - 1000K+
exes, well, it's just my pet peeve.
#2 - Love of classic hacking wizardry. :^)
The problem is Python is a dynamic language so you HAVE to ship a 
runtime with it. That hello world bin may be small, but you will still 
have the Python runtime (at least a meg or so). Consider also module 
imports. Do they get compiled into the program? Shipped as a dynamic 
linked library?

Personally, it sounds like a nifty learning project. Realistically that 
seems to be the only benefit.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] OT self-implementation?

2005-07-01 Thread Sean Perry
Brian van den Broek wrote:
> Now's not the time in my life to start a comp. sci. degree. So, my 
> questions are:
> 
> 1) What would be good terms to google for to find an explanation of 
> how the seeming magic doesn't violate all reason?
> 
> 2) Much harder, so please pass unless you've a link you know of 
> off-hand: any recommendations of particular things that I could read?
> 

try a book on compiler design. If you have programmed for any length of 
time, the ideas will be easy enough to follow even if you do not follow 
the data structures and algorithms side.

As for the lisp people, they insist everyone has been reimplementing 
lisp - badly. That is the advantage of being one of the first languages.

To directly answer them, the lisp language was originally a mathematics 
theory. It was not meant to be run, you were supposed to apply logic to 
the thing. Then someone noticed that if you ran (eval myprog) suddenly 
your script could execute itself and the interpreter was born.

How do you build tools without tools? That is the basis of your 
question. Ponder that. If you wanted to start your own blacksmith shop a 
thousand years or so ago, how would you do it? How do you make a framing 
square actually be square without using another square?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] dictionary

2005-10-24 Thread Sean Perry
Shi Mu wrote:
> I typed:
> landUse = {'res': 1, 'com': 2, 'ind': 3, "other" :[4,5,6,7]}
> and when i checked landUse, I found it become:
> {'ind': 3, 'res': 1, 'other': [4, 5, 6, 7], 'com': 2}
> why the order is changed?

the docs warn you about this.

A dictionary stores its values based on the keys. Internally Python 
sorts the keys to make the lookup meet performance expectations.

You can not expect a dictionary to return keys in the other you added 
them. If you want that, store the items as tuples in a list.

landUse = [('res', 1), ('com', 2), ('ind', 3), ("other", [4,5,6,7])]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Percentage

2005-11-11 Thread Sean Perry
Johan Geldenhuys wrote:
> Hi all,
> 
> What is the syntax if I want to work out what percentage 42 is out of 250?
> 

42 is x percent of 250.

(is / of) = (x / 100)

one of those formulas from school I will always remember.

(42 / 250) = (x / 100.0)
250x = 4200.0
x = 4200.0 / 250
x = 16.8%
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] lunch.py

2006-02-07 Thread Sean Perry
Christopher Spears wrote:
> I'm working on a program where a Customer orders Food
> from an Employee.  Here is what I have so far:
> 
> class Food:
>   def __init__(self, name):
>   Food.foodName = name
> 

what you want here is 'self.name = name' then in your code later you can do:

protein = Food("hamburger")
lipid = Food("olive oil")
print protein.name
print lipid.name

> class Customer:
>   def __init__(self,name):
>   Customer.name = name
>   def placeOrder(self, employee, food):
>   print "%s, I want, %s please! " % Employee.name,
> food.foodName
> 
> class Employee:
>   def __init__(self, name):
>   Employee.name = name
>

same for these, use self.name.

'self' is the item you are constructing. in my example above the Food 
class is instantiated with the name 'hamburger' and assigned to protein. 
When your code assigned to Food.foodName you were making *ALL* instances 
of Food be the same food. Observe:
 >>> class Food:
...   def __init__(self, name):
... Food.foodName = name
...
 >>> protein = Food('hamburger')
 >>> protein.foodName
'hamburger'
 >>> lipid = Food('olive oil')
 >>> lipid.foodName
'olive oil'
 >>> protein.foodName
'olive oil'

So to recap, use the class name when you want all instances to share a 
variable i.e. a count of the number of items. Use 'self' when you want 
each instance to have its own version of the variable, like your 'name'.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Why None?

2006-02-07 Thread Sean Perry
Hey Chris, check out this version.

class Food:
 def __init__(self, name):
 self.name = name

class Customer:
 def __init__(self,name):
 self.name = name
 self.food = None # 0 is for numbers
 def placeOrder(self, foodName, employee):
 print "%s: Hi %s!" % (self.name, employee.name)
 print "%s: I want %s please! " % (self.name, foodName)
 self.food = employee.takeOrder(foodName)
 def foodOrdered(self):
 return self.food.name

class Employee:
 def __init__(self, name):
 self.name = name
 def takeOrder(self, foodName):
 print "%s: %s coming up!" % (self.name, foodName)
 return Food(foodName)

class MealOrder:
 def __init__(self, employee, customer):
 self.employee = employee
 self.customer = customer
 def set(self, foodName):
 self.customer.placeOrder(foodName, self.employee)
 def result(self):
 print "%s has %s" % (self.customer.name,
  self.customer.foodOrdered())

if __name__ == '__main__':
 order = MealOrder(Employee('Dave'), Customer('Chris'))
 order.set('spam')
 order.result()
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Does casting exist in Python?

2006-02-22 Thread Sean Perry
Edgar Antonio Rodriguez Velazco wrote:
> Does it?
> Thanks,
> 

not exactly.

new_list = list(my_tuple)

In general Python works without having to nudge the type system.

For char -> int style conversions there is a builtin function called 'ord'.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Repeating a routine

2006-02-22 Thread Sean Perry
Jumping to the middle of a book or movie will lead to similar confusion.

Give a look at Dive Into Python. Available as either a book or online.

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


Re: [Tutor] list packing

2006-02-26 Thread Sean Perry
John Fouhy wrote:
> On 27/02/06, kevin parks <[EMAIL PROTECTED]> wrote:
> 
>>snd = [f for f in os.listdir('/Users/kevin/snd/') if f.endswith('.aif')]
> 
> 
> If this is all you need, then you could do something like:
> 
> snd = ['/Users/kevin/snd/%s' % f for f in
> os.listdir('/Users/kevin/snd/') if f.endswith('.aif')]
> 
> Or, slightly more robustly (?),
> 
> snd = [os.path.join('/Users/kevin/snd', f) for f in
> os.listdir('/Users/kevin/snd/') if f.endswith('.aif')]
> 

os.path.join() is self-documenting. I find this to be a better reason to 
use it than anything else. But then my code only ever runs on Unix of 
some flavor.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python challenge

2006-05-15 Thread Sean Perry
David Holland wrote:
> I looked at this and got stuck on the first one :-

Thanks for this. I missed it the first time it showed up on this list. 
Kinda fun and reminds me why I love python. Four lines in the 
interactive interpreter and most of the challenges are solved.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] understanding __import__()

2006-07-25 Thread Sean Perry
Ok, this may be slightly above tutor's level, but hey, never hurts to 
ask (-:

I am playing with __import__().  Here is my code:
[code]
import os.path

app_path = '/tmp/my/settings'
app_path2 = 'my/settings'

if os.path.exists(app_path + '.py'):
 print "Found", app_path

try:
 f = __import__(app_path, globals(), locals(), [])
 print f.__name__, f.__file__
except Exception, e:
 print e

if os.path.exists(app_path2 + '.py'):
 print "Found", app_path2

try:
 f = __import__(app_path2, globals(), locals(), [])
 print f.__name__, f.__file__
except Exception, e:
 print e
[/code]

The result is the first import fails and the second one works. Even 
though they are the same file.

$ pwd
/tmp
$ ls
importer.py my/
$ ls my
settings.py
$ ./importer.py
Found /tmp/my/settings
No module named /tmp/my/settings
Found my/settings
my/settings /tmp/my/settings.py

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


Re: [Tutor] understanding __import__()

2006-07-26 Thread Sean Perry
Kent Johnson wrote:
> The first argument to __import__ should be a module or package name, not 
> a file path, e.g. "my.settings". Python will look for the module in the 
> current sys.path the same as if you used a normal import. Apparently the 
> / is being interpreted as a . and I guess you have a file my/__init__.py so
>   import my.settings
> will work but
>   import .tmp.my.settings
> doesn't.
> 

as I mention in another email, if I do:

import sys
sys.path.insert(0, '')

It all just works. Very confused.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python decorator

2006-08-31 Thread Sean Perry
János Juhász wrote:
> Hi,
> 
> I have just started to play with TurboGears - it is really nice - and I 
> couldn't understand the decorators used by it.
> I have tried to interpret the http://wiki.python.org/moin/PythonDecorators 
> about decorators, but it is too difficult for me.
> 
> May someone explain decorators in very sortly, what is it for and why ?
> Do I need it anyway ?
> 

A decorator is a function that takes a function and returns a new, 
modified function.

In Django (a similar framework) there are a few places where decorators 
are used.

@login_required
def foo_view(args):
   # a view that must be authenticated
   # more code here

This means that before foo_view() is ran the function login_required is 
run. Which in this case will redirect to a login screen if the user is 
not currently authenticated.

here's the Django code:
def user_passes_test(test_func, login_url=LOGIN_URL):
 """
 Decorator for views that checks that the user passes the given test,
 redirecting to the log-in page if necessary. The test should be a 
callable
 that takes the user object and returns True if the user passes.
 """
 def _dec(view_func):
 def _checklogin(request, *args, **kwargs):
 if test_func(request.user):
 return view_func(request, *args, **kwargs)
 return HttpResponseRedirect('%s?%s=%s' % (login_url, 
REDIRECT_FIELD_
NAME, quote(request.get_full_path(
 _checklogin.__doc__ = view_func.__doc__
 _checklogin.__dict__ = view_func.__dict__

 return _checklogin
 return _dec

login_required = user_passes_test(lambda u: u.is_authenticated())


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