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


[Tutor] understanding __import__()

2006-07-26 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 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


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] 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] 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] 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] 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] 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] 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] 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] 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] 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] 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()
generator object at 0x640d0
  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] 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] 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] 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:\Python24ad-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:
code
for k,v in ad_dict(user).items():
/code
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] 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] 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] 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] 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] 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] 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] 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] 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 copypaste 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] 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] 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] 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] 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:
SNIP
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] 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] 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