Re: counting items

2005-01-12 Thread Michael Hartl
There's a great function called "walk" at that iterates over arbitrary
data (and is recursion-proof) at

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/118845

It also supplies a recursion-proof way to flatten a list.  (Once you
can iterate over an arbitrary sequence, the flattened version is just
[element for element in walk(sequence)].)  I use both functions all the
time.

Adding a flatten function (along with walk) to Python sounds like a
good idea to me.  Having used Mathematica for many years, which uses
Flatten[] all over the place, I was actually quite surprised to find
that Python didn't have it.

Michael

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


Re: counting items

2005-01-12 Thread Michael Hartl
That's cool!  Of course, walk returns a generator, so using a list
comprehension to turn it into a list seems natural, but I didn't
realize that list() does the same thing (and neither, apparently, did
the original implementor) -- although, with a little reflection, it
obviously must!

Michael

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


Re: a sequence question

2005-01-28 Thread Michael Hartl
For problems like this I use a partition function defined in a utils.py
file that I use (based on Peter Norvig's utils file at
http://aima.cs.berkeley.edu/python/utils.py).  Using partition, the
problem you posed can be solved by writing

#for a, b in partition([1, 2, 3, 4], 2):
#print a, b

The implementation of partition I use is simple-minded; the previous
posts in this thread suggest some more sophisticated ways to attack it
using generators.

#def partition(seq, partsize):
#"""Partition a sequence into subsequences of length partsize."""
#ls = len(seq)
#assert ls % partsize == 0, ('length %s, partition size %s\n'
#% (ls, partsize))
#return [seq[i:(i+partsize)] for i in range(0, ls, partsize)]
Michael

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


Re: naive doc question

2005-01-29 Thread Michael Hartl
i.e., http://docs.python.org/lib/typesmapping.html

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


Re: How do I convert arithemtic string (like "2+2") to a number?

2005-02-05 Thread Michael Hartl
Use the eval function:

>>> eval("30/(6+9)")
2

Michael

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


Re: How do I convert arithemtic string (like "2+2") to a number?

2005-02-05 Thread Michael Hartl
Adam brings up a good point: eval is a very general function which
evaluates an arbitrary Python expression.  As a result, it (and its
close cousin exec) should be used with caution if security is an issue.

Michael

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


Re: check if object is number

2005-02-11 Thread Michael Hartl
As luck would have it, isnumber is a built-in Python function:

>>> isnumber(1)
True
>>> isnumber(1.0)
True
>>> isnumber('1')
False

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

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


Re: check if object is number

2005-02-12 Thread Michael Hartl
As I mention below, I mistook the function from my utilities file for a
Python built-in; here's the implementation:

#def isnumber(x):
#"Is x a number? We say it is if it has an __int__ method."
#return hasattr(x, '__int__')

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


Re: check if object is number

2005-02-12 Thread Michael Hartl
Oops, my bad.  The utilities file I use gets loaded automatically when
I start my interpreter, so I mistook isnumber for a built-in function.
A battle-tested isnumber function is defined in Peter Norvig's utils.py
(http://aima.cs.berkeley.edu/python/utils.py):

#def isnumber(x):
#"Is x a number? We say it is if it has an __int__ method."
#return hasattr(x, '__int__')

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

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


Re: builtin functions for and and or?

2005-02-13 Thread Michael Hartl
I warmly recommend downloading Peter Norvig's Python utilities file
(http://aima.cs.berkeley.edu/python/utils.py) and putting it on your
Python path.  (E.g., in bash, put a line like

export PYTHONPATH="/path/to/utilities_directory"

in your .bashrc file.)  The utils.py file defines many useful
functions, including the ones you want:

# def every(predicate, seq):
# """True if every element of seq satisfies predicate.
# Ex: every(callable, [min, max]) ==> 1; every(callable, [min, 3])
==> 0
# """
# for x in seq:
# if not predicate(x): return False
# return True
#
# def some(predicate, seq):
# """If some element x of seq satisfies predicate(x), return
predicate(x).
# Ex: some(callable, [min, 3]) ==> 1; some(callable, [2, 3]) ==> 0
# """
# for x in seq:
# px = predicate(x)
# if px: return px
# return False

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

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


Re: Newbie help

2005-02-13 Thread Michael Hartl
You need to put the "You guessed it..." block inside a conditional (if
guess == number) so that it only executes if the guess is right.  (You
also need to break out of the loop in that case.)  As written, the "You
guessed it..." block executes the first time through the loop
regardless of the guess.  Also, if the initial guess is right, then the
while guess != number block never executes, and the message is never
displayed.

What you need is an infinite loop that breaks on a correct guess or
upon reaching the maximum number of tries.

Here's a corrected version:

# import random
#
# print "\tWelcome to 'Guess My Number'!"
# print "\nI'm thinking of a number between 1 and 100."
# print "You Only Have Five Guesses.\n"
#
# # set the initial values
# number = random.randrange(100) + 1
# guess = int(raw_input("Go Ahead and Take a guess: "))
# tries = 1
# max_tries = 5
#
# # guessing loop
# while True:
# if guess == number:
# # Guess is right!
# print "You guessed it!  The number was", number
# print "And it only took you", tries, "tries!\n"
# break
# elif tries == max_tries:
# print "Sorry You Lose"
# print "The Number was ", number
# break
# elif guess > number:
# print "Guess Lower..."
# elif guess < number:
# print "Guess Higher..."
# guess = int(raw_input("Take Another guess: "))
# tries += 1
#
# raw_input("\n\nPress the enter key to exit.")

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

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


Re: Newbie help

2005-02-13 Thread Michael Hartl
Sorry about the code: Google Groups screwed up the formatting, but I
hope you get the picture.

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


Re: Test for structure

2005-02-16 Thread Michael Hartl
I use a function isListLike in cases such as this one:

# def isListLike(L):
# """Return True if L is list-like, False otherwise."""
# try:
# L + []
# return True
# except:
# return False

Then you can use a standard if-else construct:

# if isListLike(myvar):
# 
# else:
# 

Michael

--
Michael D. Hartl, Ph.D.
Chief Technology Officer
http://quarksports.com/

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


Re: Tuple index

2005-02-21 Thread Michael Hartl
I actually find it strange that tuples don't have an index function,
since finding the index doesn't involve any mutation.  Anyone know why
Python doesn't allow a statement like t.index('foo')?

In any case, you can use the index method of list objects if you
convert your tuple to a list first:

>>> t = ("fred", "barney", "foo")
>>> list(t).index("foo")
2
>>> def index(a_tuple, element):
... return list(a_tuple).index(element)
...
>>> t[index(t, "foo")]
'foo'

(By the way, 'tuple' is a Python built-in type, so it's probably best
to avoid using it as a variable name.)


Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: rounding problem

2005-02-23 Thread Michael Hartl
> Is it normal?

Yes.  The interpreter prints back the repr of a, which reflects the
imprecision inherent in floats.  If you want '1.1', use the string
returned by the str function.

>>> a = 1.1
>>> a
1.1001
>>> repr(a)
'1.1001'
>>> str(a)
'1.1'

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Which module is "set " in?

2005-02-25 Thread Michael Hartl
It's good that you're using Python 2.3, which does have sets available,
as a previous poster mentioned.  Users of Python 2.2 or earlier can get
most of the Set functionality using the following class (from Peter
Norvig's utils.py file):

# class Set:
# """This implements the Set class from PEP 218, except it does not
# overload the infix operators.
# Ex: s = Set([1,2,3]); 1 in s ==> True; 4 in s ==> False
# s.add(4); 4 in s ==> True; len(s) ==> 4
# s.discard(999); s.remove(4); 4 in s ==> False
# s2 = Set([3,4,5]); s.union(s2) ==> Set([1,2,3,4,5])
# s.intersection(s2) ==> Set([3])
# Set([1,2,3]) ==> Set([3,2,1]); repr(s) ==> '{1, 2, 3}'
# for e in s: pass"""
#
# def __init__(self, elements=[]):
# self.dict = {}
# for e in elements:
# self.dict[e] = 1
#
# def __contains__(self, element):
# return element in self.dict
#
# def __getitem__(self, i):
# return self.dict.items()[i]
#
# def add(self, element):
# self.dict[element] = 1
#
# def remove(self, element):
# del self.dict[element]
#
# def discard(self, element):
# if element in self.dict:
# del self.dict[element]
#
# def pop(self):
# key, val = self.dict.popitem()
# return key
#
# def clear(self):
# self.dict.clear()
#
# def union(self, other):
# return Set(self).union_update(other)
#
# def intersection(self, other):
# return Set(self).intersection_update(other)
#
# def union_update(self, other):
# for e in other:
# self.add(e)
# return self
#
# def intersection_update(self, other):
# for e in self.dict.keys():
# if e not in other:
# self.remove(e)
# return self
#
# def issubset(self, other):
# for e in self.dict.keys():
# if e not in other:
# return False
# return True
#
# def __iter__(self):
# for e in self.dict:
# yield e
#
# def __len__(self):
# return len(self.dict)
#
# def __cmp__(self, other):
# if self is other: return False
# if not isinstance(other, Set): return id(self) - id(other)
# return cmp(self.dict, other.dict)
#
# def __repr__(self):
# return "{%s}" % ", ".join([str(e) for e in self.dict.keys()])

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Calling external text-files (newb)

2005-02-28 Thread Michael Hartl
There are two problems: (1) by quoting 'source', you refer to a string
literal, not the variable you defined via raw_input; (2) you have not
defined the variable 'input', so there's no way to call the 'read'
method on it.

Try this instead:

source_path = raw_input('file path: ')
s = open(source_path).read()
print s

The default behavior of 'open' includes 'r' implicitly.

You can also use the function 'file', which is a synonym for 'open':

s = file(source).read()

Be warned that using the same syntax when writing files is dangerous;
in that case you should create a file object and explicitly close it.

f = file('a_copy', 'w')
f.write(s)
f.close()

HTH,

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Calling external text-files (newb)

2005-02-28 Thread Michael Hartl
There are two problems: (1) by quoting 'source', you refer to a string
literal, not the variable you defined via raw_input; (2) you have not
defined the variable 'input', so there's no way to call the 'read'
method on it.

Try this instead:

source_path = raw_input('file path: ')
s = open(source_path).read()
print s

The default behavior of 'open' includes 'r' implicitly.

You can also use the function 'file', which is a synonym for 'open':

s = file(source).read()

Be warned that using the same syntax when writing files is dangerous;
in that case you should create a file object and explicitly close it.

f = file('a_copy', 'w')
f.write(s)
f.close()

HTH,

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Whats the best Python Book for me

2005-05-01 Thread Michael Hartl
I'd like to second the recommendation for the Python Cookbook.  As an
experienced programmer, you'll learn a lot by osmosis.

Michael

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


Re: Need a little parse help

2005-05-10 Thread Michael Hartl
I'd also like to note that both the inputfiles variable and the
readlines() method are superfluous; to iterate through the file line by
line, use either

for line in open(inputfilename):
# do something with line

or (my personal preference, since I like to think of the file as a
thing rather than an action)

for line in file(inputfilename):
# do something with line

(Note also that the 'r' argument to open/file is the default and so can
be omitted.)

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Need a little parse help

2005-05-10 Thread Michael Hartl
Mike mentions an important point, and I've been bitten by the
phenomenon Mike mentions---but only when *writing* to files.  They
should always be closed explicitly, as in

f = file(filename, 'w')
f.write(somestring)
f.close()

On the other hand,  I've never encountered a problem with the "for line
in file(filename)" idiom.  A similar time-saver is writing something
like

s = file(filename).read()

which puts the entire file as a string in the variable s.  In this
case, as in the file iteration case, we save two lines of code and one
variable.  It may not sound like much, but

f = file(filename)
s = f.read()
f.close()

seems much more cumbersome to me, especially when doing a lot of file
reads.

In short, my experience is that explicitly closing a file is
unnecessary when reading.  I could be wrong, though, and I'd be very
interested to see an example of either idiom above leading to problems.

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: can someone tell me why this doesn't work please python 3

2009-01-14 Thread Michael Hartl

garywood schrieb:

def ask_ok(prompt, retries=4, complaint="Yes or no, please!"):
while True:
password = input("enter something")
if password in ('y', 'ye', 'yes'): return True
if password in ('n', 'no', 'nope'): return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print(complaint)


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

What's your problem, anyway? It seems to work perfectly fine, except that
you ignore the prompt variable.
--
http://mail.python.org/mailman/listinfo/python-list


Re: lazy evaluation is sometimes too lazy... help please.

2009-01-16 Thread Michael Hartl

James Stroud schrieb:

Ken Pu wrote:

Hi,  below is the code I thought should create two generates, it[0] =
0,1,2,3,4,5, and it[1] = 0,10,20,30,..., but they turn out to be the
same!!!

from itertools import *
itlist = [0,0]
for i in range(2):
  itlist[i] = (x+(i*10) for x in count())

print "what's in the bags:"
print list(islice(itlist[0], 5))
print list(islice(itlist[1], 5))

The output is:
[10, 11, 12, 13, 14]
[10, 11, 12, 13, 14]

I see what Python is doing -- lazy evaluation doesn't evaluate
(x+(i*10) for x in count()) until the end.


It doesn't evaluate it until you ask it to, which is the right 
behavior. However, when evaluated, it evaluates "i" also, which is the 
last value to which "i" was assigned, namely the integer 1. I'm going 
to get flamed pretty hard for this, but it doesn't seem to be the 
intuitive behavior to me either. However, in a purely functional 
language, you wouldn't be able to construct a list of generators in 
this way.


With python, you have to remember to adopt a purely functional design 
and then pray for best results. You can store generators in a list, 
but they need to be constructed properly. I can't perfectly 
transmogrify your code into functional code because I don't think 
making the particular anonymous generator you want is possible in 
python. However this is how I would make a close approximation:



from itertools import *

def make_gen(i):
  for x in count():
yield x + (i * 10)

itlist = [make_gen(i) for i in xrange(2)]

print "what's in the bags:"
print list(islice(itlist[0], 5))
print list(islice(itlist[1], 5))


James


You could just as well use the original expression in make_gen, too:

from itertools import *
def make_gen(i):
 return (x + (i*10) for x in count())

itlist = [make_gen(i) for i in xrange(2)]

print "what's in the bags:"
print list(islice(itlist[0], 5))
print list(islice(itlist[1], 5))

what's in the bags:
[0, 1, 2, 3, 4]
[10, 11, 12, 13, 14]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can I run an operation on an object's attribute when reading?

2009-01-19 Thread Michael Hartl

Phillip B Oldham schrieb:

On Mon, Jan 19, 2009 at 12:15 PM, Chris Rebert  wrote:
  

Assuming I'm interpreting you correctly (you're going to have to use
something like a getter):



Thanks, but I'm looking for a way to do it *without* using a getter as
I don't have easy access to the class (its being generated for me
elsewhere). Essentially I'd like to overwrite (if possible) the
default behavior when returning certain attributes on certain objects.
--
http://mail.python.org/mailman/listinfo/python-list
  
You could still add the getter to the class after it has been defined if 
that's your only problem with

using a getter:

class Item(object):
 tags = ['default','item']   


@property
def tags(self):
   return ' '.join(self.tags)

setattr(Item, "Tags", tags)

print Item().Tags #==> default item


But I don't think there's a way to do it without a different name (here 
"tags" - "Tags"), is there?

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