Re: A struct for 2.4 that supports float's inf and nan?

2007-09-20 Thread Paul Hankin
zip(fmt, args)) Unpacking is similar: unpack doubles with 'Q' and test the long for equality with +-inf, and find nan's by checking bits 52 to 62. If the number's ok, unpack again using 'd'. You can get python values for nan, -inf and inf by using float('nan'), float('-inf'), float('inf'). I've not been able to properly test this, as struct seems to work fine in Python 2.3 and 2.4 on MacOS X. HTH -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: A struct for 2.4 that supports float's inf and nan?

2007-09-20 Thread Paul Hankin
Both str(f) should be str(a) in pack_one_safe. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: about __str__

2007-09-20 Thread Paul Hankin
is? For whatever reason, __str__ of list calls repr rather than str on its elements. You can fix your code by adding __repr__ in your class: Class CmterIDCmts: def __init__ ... def __str__ ... __repr__ = __str__ -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: I could use some help making this Python code run faster using only Python code.

2007-09-20 Thread Paul Hankin
join(chr(ord(c) & 0x7f) for c in line) def scrambleLine(line): return ''.join(chr(ord(c) | 0x80) for c in line) It's less code, more readable and faster! -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: executing list of methods (and collecting results)

2007-09-21 Thread Paul Hankin
validators(self): methods = ['is_really_a_number', 'is_even', 'is_greater_than_zero'] return (m for m in methods if getattr(self, m)()) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Converting numbers to unicode charaters

2007-09-24 Thread Paul Hankin
, 16)) for h in hexs) If you want fast, you can build a cache once that maps hex strings to unicode characters something like this: cache = dict((hex(i)[2:], unichr(i)) for i in range(256)) Then use something like your code: word = '' for h in hexs: word += cache[h] Or a list comprehension: word = ''.join([cache[h] for h in hexs]) Or a generator: word = ''.join(cache[h] for h in hexs) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Nested For and While Statements

2007-09-24 Thread Paul Hankin
>lanex.append(lane2) >lane3 = newlist1[2+Nscheme*2:2+Nscheme*3] >lanex.append(lane3) > lane4 = newlist1[2+Nscheme*3:2+Nscheme*4] >lanex.append(lane4) List comprehensions beat copy/paste: total_schemes = 2 if numlanes == 2 else 4 lanex = [newlist1[2 + i * Nscheme:2 + (i + 1) * Nscheme] for i in range(total_schemes)] HTH, and welcome to python! -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Nested For and While Statements

2007-09-24 Thread Paul Hankin
>lanex.append(lane2) >lane3 = newlist1[2+Nscheme*2:2+Nscheme*3] >lanex.append(lane3) > lane4 = newlist1[2+Nscheme*3:2+Nscheme*4] >lanex.append(lane4) List comprehensions beat copy/paste: total_schemes = 2 if numlanes == 2 else 4 lanex = [newlist1[2 + i * Nscheme:2 + (i + 1) * Nscheme] for i in range(total_schemes)] HTH, and welcome to python! -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-25 Thread Paul Hankin
anted. I don't like the integral indexing idea or the slicing: indexing and slicing are already part of python and it's bad to have different syntax for the same concept on sorteddicts. I'd say it's not an important enough for sorteddicts anyway. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Clustering text-documents in bundles

2007-09-25 Thread Paul Hankin
ou should be able to code up this sort of distance (although the details will depend just on what your text looks like). -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-25 Thread Paul Hankin
On Sep 25, 12:51 pm, Mark Summerfield <[EMAIL PROTECTED]> wrote: > On 25 Sep, 12:19, Paul Hankin <[EMAIL PROTECTED]> wrote: > > > > > Recall sorted... > > sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted > > list > > > S

Re: Script to extract text from PDF files

2007-09-25 Thread Paul Hankin
to Python (pdftotext, etc.) is not really an option > for me. If someone knows of a free native Python app that does this now, > let me know and I'll use that instead! Googling for 'pdf to text python' and following the first link gives http://pybrary.net/pyPdf/ -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-25 Thread Paul Hankin
On Sep 25, 7:58 pm, Steven Bethard <[EMAIL PROTECTED]> wrote: > > Paul Hankin wrote: > > ... > > class sorteddict(dict): > > "A sorted dictionary" > > def __init__(self, arg=None, cmp=None, key=None, reverse=False): > > if arg:

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-25 Thread Paul Hankin
ther replace with 'self.__keycache = None' or more cleanly with a call to: def __invalidate_key_cache(self): self.__keycache = None to improve the code quality. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-26 Thread Paul Hankin
tion you're probably better doing an insertion rather than a full resort. Of course, there's a few nasty cases here but it's always possible to just throw away the sorted list and reconstruct it from the dict keys when things get too hairy (eg, the user deletes a key that's in the inserted-but-not-yet- sorted set). -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-26 Thread Paul Hankin
anced tree will give you much worse performance when you're doing regular dict operations. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-26 Thread Paul Hankin
On Sep 26, 2:46 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > Paul Hankin <[EMAIL PROTECTED]> wrote: > > More flexibly, keep a set of inserted keys that haven't yet been > > included in the sorted list, and a set of deleted keys that haven't > > yet been

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-26 Thread Paul Hankin
On Sep 26, 3:24 pm, Mark Summerfield <[EMAIL PROTECTED]> wrote: > On 26 Sep, 14:59, Paul Hankin <[EMAIL PROTECTED]> wrote: > > > > > On Sep 26, 2:46 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > > > > Paul Hankin <[EMAIL PROTECTED]> wrote: &

Re: ~ bit-wise unary operator

2007-09-26 Thread Paul Hankin
at answer if a is an unsigned short on any modern architecture. But if that's what you want, try def invert(x): return ~x & 0x -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: sorteddict PEP proposal [started off as orderedict]

2007-09-26 Thread Paul Hankin
On Sep 26, 9:52 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > Paul Hankin <[EMAIL PROTECTED]> wrote: > >> So should Duncan's > > >> def __removekey(self, key): > >> if key in self.__addkeys: > >> del self.__addkeys[

Re: A question on python performance.

2007-09-26 Thread Paul Hankin
ram, per) replace with trend.(per) if you're calling getValue with a static value for param, or getattr(trend, param)(per) if param is dynamic. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Using closures and partial functions to eliminate redundant code

2007-09-27 Thread Paul Hankin
%s' % (k, kwargs[k]) for k in kwargs) send_email(subject=subject, body='\n' + email_body + '\n' def create_user(name, password, email): "Create a user by sending an email to the server" send_command_email('CREATE', USERNAME=name, USERPASSWORD=password, USEREMAIL=email) def update_user(name, password, email): "Update a user's details by sending an email to the server" send_command_email('UPDATE', USERNAME=name, USERPASSWORD=password, USEREMAIL=email) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Checking for the existence of Duplicates

2007-09-28 Thread Paul Hankin
= 0 and cell in found: return False found.add(cell) Since your elements are probably numbers 1 to 9 (or 0), you might use bitfields. I'd expect this to be faster, but you should check: found = 0 for x in self.__XRList[z]: cellbit = 1 << x[ValIndex] if cellbit != 1

Re: Bug with lists of pairs of lists and append()

2007-09-28 Thread Paul Hankin
same. But do you just want all proper partitions of lst? Then this is much simpler: lst = [0, 1, 2] s = [(lst[:i], lst[i:]) for i in range(1, len(lst))] -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: s.split() on multiple separators

2007-09-30 Thread Paul Hankin
u made a common mistake of using a loop index instead of iterating directly. Instead of: for i in xrange(len(c)): cp.extend(c[i].split(j)) Just write: for words in c: cp.extend(words.split(j)) Then you won't make a bounds mistake, and this snippet becomes a LOT more readable. (Of course, you&#

Re: Limits on search length

2007-10-01 Thread Paul Hankin
hells will expand *.txt to the list of files that match, so you'll end up with the first .txt file as your 'filePattern', and the second as the regexp. Could that be it? -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: problem with special built-in method __contains__,

2007-10-02 Thread Paul Hankin
x27;binary': '10100101', 'decimal': '1234567890', > 'hexadecimal': '1-9,a-f'} > > i got error..after execute > > >>>number._contains_("test") It's __contains__ and not _contains_. But better is just: 'test' in number -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: readline() - problem

2007-10-02 Thread Paul Hankin
) > f.close() > > Why it doesn't work ('s' contains ' ' )? You're iterating over the lines in f already, so no need to call readline. for line in f: if line[15] == '1': o.write(line) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: List Question

2007-10-02 Thread Paul Hankin
ion: if sum(1 for a in y if x == a) > 3: print x -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: List Question

2007-10-02 Thread Paul Hankin
On Oct 2, 10:20 pm, Paul Hankin <[EMAIL PROTECTED]> wrote: > On Oct 2, 10:06 pm, brad <[EMAIL PROTECTED]> wrote: > > > How is this expressed in Python? > > > If x is in y more than three times: > > print x > > > y is a Python list. > >

Re: List Question

2007-10-03 Thread Paul Hankin
On Oct 2, 11:09 pm, Paul McGuire <[EMAIL PROTECTED]> wrote: > On Oct 2, 4:20 pm, Paul Hankin <[EMAIL PROTECTED]> wrote: > > On Oct 2, 10:06 pm, brad <[EMAIL PROTECTED]> wrote: > > > > How is this expressed in Python? > > > > If x is in y more

Re: Combine two dictionary...

2007-10-04 Thread Paul Hankin
for d in self._dicts for k in d)) def keys(self): return self._keys def __getitem__(self, key): return sum(d.get(key, 0) for d in self._dicts) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Is there a nicer way to do this?

2007-10-04 Thread Paul Hankin
} If you are right that a map from indices to name is best, there's no need for a dict: the original list already provides such a mapping. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Dynamically creating class properties

2007-10-04 Thread Paul Hankin
7;item1']) a = A() a.item1 = 19 print a.item1 >> 20 You didn't say where the getters and setters (here 'getitem1', 'setitem1', etc.) come from. I've assumed from the global namespace but you probably want to change that. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Dynamically creating class properties

2007-10-04 Thread Paul Hankin
On Oct 4, 11:55 pm, Paul Hankin <[EMAIL PROTECTED]> wrote: > On Oct 4, 9:59 pm, Karlo Lozovina <[EMAIL PROTECTED]> wrote: > > > > > Hi all, > > > this is my problem: lets say I have a arbitrary long list of attributes > > that I want to attach to so

Re: Strange generator problem

2007-10-05 Thread Paul Hankin
27;re returning the same lists (with different elements) each time. Your final list looks like [(s1, s2), (s1, s2), ...] and as it happens, s1 and s2 are both [] by the end. You can fix it by copying the lists manually before yielding them, or using a better sub-list algorithm :) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: slice with negative stride

2007-10-06 Thread Paul Hankin
ed in the python documentation, http://docs.python.org/lib/typesseq.html (especially note 5 on that page). -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Variable scoping rules in Python?

2007-10-08 Thread Paul Hankin
on. def doSomethingAndOutputIt(columns = 80): ... columns = columns or len(output[0]) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Last value of yield statement

2007-10-10 Thread Paul Hankin
r than as a list. Then, something like (untested) def lookup_msgids(filename): """Yield lines from the given file, with 'msgstr' lines added after 'msgid' lines when the id is in the id dictionary.""" for line in open(filename

Re: function wrappers

2007-10-10 Thread Paul Hankin
of the function. You can see some of the gory details if you go: def f(): print 42 dir(f) ... list of attributes of the function object. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Pythonic way for handling file errors

2007-10-10 Thread Paul Hankin
27;s better to put the OK case (error 200) in an else clause to make it clearer that it's only set when no error occurs. It's also better to use constants in place of magic numbers. import httplib try: with open('afile', 'r') as f: content = f.read()

Re: for loop question

2007-10-10 Thread Paul Hankin
mple above? Thanks. > > A "works-for-me": > > >>> pairs = (test[i:i+2] for i in xrange(len(test)-1)) > >>> for a,b in pairs: > ... print a,b for a, b in zip(test, test[1:]): print a, b -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Multidimensional sort

2007-10-10 Thread Paul Hankin
wo of your data, say by defining a compare function def cmp(a, b): ... Then you can sort your list using sorted(my_list, cmp=cmp). Without knowing what your data means, and what you're planning to do with it, it's not possible for anyone to answer your question properly. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-11 Thread Paul Hankin
On Oct 11, 4:40 am, Steven D'Aprano <[EMAIL PROTECTED] cybersource.com.au> wrote: > On Wed, 10 Oct 2007 20:25:00 +0000, Paul Hankin wrote: > >> A "works-for-me": > > >> >>> pairs = (test[i:i+2] for i in xrange(len(test)-1)) > >> >

Re: Declarative properties

2007-10-11 Thread Paul Hankin
tly, his plan is to use 'X._name' internally to code in his class, but the public uses 'X.name'. Initially, one is an alias for the other, but later he writes getters and setters to customise access through the public version. [I could be totally wrong of course] -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Declarative properties

2007-10-11 Thread Paul Hankin
e use... class C(object): x = magic_attribute('_x') y = magic_attribute('_y') # Override the default set method for x def _set_x(self, value): self._x = value + ' world' # Override the default get method for y def _get_y(self): return self._y.upper() # Test it works... c = C() c.x = c.y = 'hello' print c.x print c.y # hello world # HELLO -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Last iteration?

2007-10-12 Thread Paul Hankin
print i Yes, either use enumerate or just stop the loop early and deal with the last element outside the loop. xs = [1, 2, 3] for x in xs[:-1]: print x print xs[-1] * xs[-1] -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Last iteration?

2007-10-12 Thread Paul Hankin
eversed(mylist: > if j==0: > print i*i > else: > print i Nice! A more 'readable' version is: mylist = [1,2,3] for not_last, i in reversed(list(enumerate(reversed(mylist: if not_last: print i else: print i * i -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Last iteration?

2007-10-14 Thread Paul Hankin
s empty, which Diez's solution didn't. Logically, there is no 'last' element in an empty sequence, and it's obscure to add one. Peter Otten's improvement to Diez's code looks the best to me: simple, readable and correct. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Safely dealing with arbitrary file objects

2007-10-14 Thread Paul Hankin
s.stdout, '2-':sys.stderr}): if name in special: return False, special[name] return True, open(name, 'w') def process_file(filename): should_close, outfile = open_file(filename) try: outfile.write('stuff happens') finally: if should_close: outfile.close() -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Simple Text Processing Help

2007-10-14 Thread Paul Hankin
\\chem_2.txt" input = codecs.open(path, 'r','utf8') output = codecs.open(path2, 'w', 'utf8') for line in input: tokens = line.strip().split() tokens[2:-1] = [u' '.join(tokens[2:-1])] chemical = u'|'.join(tokens) print

Re: Order of tuples in dict.items()

2007-10-14 Thread Paul Hankin
ither always true or mostly true. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Simple Text Processing Help

2007-10-15 Thread Paul Hankin
; '.join(items[:-1]), items[-1]) Maybe this is a bit more readable? def iter_elements(tokens): chem = [] for tok in tokens: if NR_RE.match(tok) and len(chem) >= 4: chem[2:-1] = [' '.join(chem[2:-1])] yield chem chem = [] chem.append(tok) yield chem -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Simple Text Processing Help

2007-10-15 Thread Paul Hankin
work if you can't get it. This code uses exactly the same algorithm as Marc's code - it's just a bit clearer (or at least, I thought so). Oh, and it returns a list rather than a tuple, but that makes no difference. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Last iteration?

2007-10-17 Thread Paul Hankin
izip(repeat(False), > lookahead)), repeat(True)), t) def lastdetector(iterable): t, u = tee(iterable) return izip(chain(imap(lambda x: False, islice(u, 1, None)), [True]), t) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Noob questions about Python

2007-10-17 Thread Paul Hankin
On Oct 17, 8:37 pm, Ixiaus <[EMAIL PROTECTED]> wrote: > I have a few questions regarding Python behavior... > as the integer 72 instead of returning 00110, why does Python do that? > (and how can I get around it?) You can do this: def bin(x): return int(x, 2) val = bin(&#

Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Paul Hankin
's not what you want here: you're using the side-effect of the append method - which modifies a. This makes using regular iteration the right idea, because by using map or a comprehension, you're also constructing a list of the return values of append (which is always None). You can

Re: Need help in updating a global variable by a thread

2007-10-17 Thread Paul Hankin
eed to wait for the threads to finish executing before you see the updated results. Have a look at threading.join to see how you might do that. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Appending a list's elements to another list using a list comprehension

2007-10-17 Thread Paul Hankin
7;s runnign too slowly. To answer your question though: a += b is *not* the same as a = a + b. The latter would create a new list and assign it to a, whereas a += b updates a in-place. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Pull Last 3 Months

2007-10-17 Thread Paul Hankin
the 'datetime' module. You can get the current month: datetime.datetime.now().month And a list of all abbreviated month names: [datetime.datetime(1900, i + 1, 1).strftime('%b') for i in range(12)] >From there, it shouldn't be too tricky to construct the list of months you want. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Noob questions about Python

2007-10-17 Thread Paul Hankin
structing the final list. Applying these to your function, and noting that n << k is nicer than n * 2 ** k, we get a one-liner: def bin2dec(val): return sum(int(i) << k for k, i in enumerate(reversed(val))) Or a slightly nicer alternative is to filter the generator usi

Re: if instance exists problem ..

2007-10-17 Thread Paul Hankin
bj.__init__(self, filename, list_values=False, write_empty_values=True) self.newlines = '\r\n' self.Section = '' self.Modified = False -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Pull Last 3 Months

2007-10-17 Thread Paul Hankin
t looks like you copied the month 2 case from the month 1 case because you forgot to edit it afterwards. Anyway, a bit of modulo-12 arithmetic avoids special cases, and allows the number of months to be generalised: import datetime months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'

Re: Last iteration?

2007-10-18 Thread Paul Hankin
On Oct 17, 11:45 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote: > [Paul Hankin] > > > def lastdetector(iterable): > > t, u = tee(iterable) > > return izip(chain(imap(lambda x: False, islice(u, 1, None)), > > [True]), t) > > Sweet! Nic

Re: Stopping a fucntion from printing its output on screen

2007-10-18 Thread Paul Hankin
arg): pass nullwriter = NullWriter() f(10, out = nullwriter) Having the output stream explicit like this is much better style than abusing sys.stdout, and it won't go wrong when errors occur. It's the same idea as avoiding global variables. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Best way to generate alternate toggling values in a loop?

2007-10-18 Thread Paul Hankin
, name)) I like this code: straightforward and pragmatic. Everyone else seems to be reinventing itertools.cycle - they should have listened to Carsten, and written something like this: import itertools clvalues = itertools.cycle(['Even', 'Odd']) for clvalue, (id, name) in iterto

Re: Appending a list's elements to another list using a list comprehension

2007-10-18 Thread Paul Hankin
On Oct 18, 10:21 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote: > Paul Hankin <[EMAIL PROTECTED]> writes: > > On Oct 17, 10:03 pm, Debajit Adhikary <[EMAIL PROTECTED]> wrote: > >> How does "a.extend(b)" compare with "a += b" when it comes to &

Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread Paul Hankin
in tuples. In fact, tuples are a bit awkward sometimes because you have to use '(a,') for a tuple with one element - (2) isn't a tuple of length one, it's the same as 2. Either cope with this special case, or use lists. Either way, you'll have to use () or [] for an empty sequence. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Organizing Sequential Data (TimeStamps) Overthinking?

2007-10-19 Thread Paul Hankin
te. If you only want the n largest (or smallest) timestamps - as suggested by your question - keep your data in a list, and use heapq.nlargest (or heapq.nsmallest). In fact, I'd try these even if you think you really need a binary tree: it might be fast enough anyway. -- Paul Hankin --

Re: how to iterate over sequence and non-sequence ?

2007-10-19 Thread Paul Hankin
On Oct 19, 5:38 pm, stef mientki <[EMAIL PROTECTED]> wrote: > ... snip hand-coded debugger > I couldn't come up with a better solution ;-) Does pdb not suffice? Even if it doesn't; you can look up variables without using exec, using locals()['x'] or globals(

Re: Dealing with "funny" characters

2007-10-20 Thread Paul Hankin
ort for varchars, so that seems a likely encoding to use. If you're stuck with ascii, you can use 'unicode_escape' if you're only accessing it from python. But first read this excellent article on 'funny' characters: http://www.joelonsoftware.com/articles/Unicode.html -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: weakref pitfall

2007-10-20 Thread Paul Hankin
sed about your event manager's API: you have register/deregister methods and are also using weakrefs to provide auto-deregistering. I don't know your code, but this looks like a mistake to me - can you justify (to yourself) that you need both ways? -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: where do I need to "tab"?

2007-10-20 Thread Paul Hankin
On Oct 20, 3:00 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > print b if ((b > a) and (b < (a * b))) else a Everyone else has already pointed out that you need 2.5. As a matter of style, the above line can be written more cleanly: print b if a < b &l

Re: what is the difference between the two kinds of brackets?

2007-10-20 Thread Paul Hankin
), use tuples. If the data is uniform (ie each element of the list/tuple has the same meaning - for example, all the filenames in a directory), use lists. If the data has a fixed length, use tuples. If the data has an unknown - possibly unbounded - length, use lists. If everything else is equal, use

Re: Anagrams

2007-10-23 Thread Paul Hankin
27;:97, 'z':101} > ... A somewhat nicer start: compute primes (naively) rather than typing out the dictionary. import string from itertools import ifilter, count def anagram_finder(): primes = ifilter(lambda p: all(p % k for k in xrange(2, p)), count(2)) primeAlpha = dict(zip(string.lowercase, primes)) ... -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Better writing in python

2007-10-24 Thread Paul Hankin
= [arg for arg in cls.dArguments in not arg] return mandatory, optional -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Better writing in python

2007-10-24 Thread Paul Hankin
= [arg for arg in cls.dArguments in not arg] return mandatory, optional -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Better writing in python

2007-10-24 Thread Paul Hankin
= [arg for arg in cls.dArguments in not arg] return mandatory, optional -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Better writing in python

2007-10-24 Thread Paul Hankin
ions, so I > may have the syntax just slightly off. Your list comprehensions are right, but 'arg is True' and 'arg is False' are better written as 'arg' and 'not arg' respectively. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Anagrams

2007-10-24 Thread Paul Hankin
On Oct 24, 5:03 pm, sandipm <[EMAIL PROTECTED]> wrote: > Is "all" inbuilt function in python? what it does? >>> help(all) Help on built-in function all in module __builtin__: all(...) all(iterable) -> bool Return True if bool(x) is True for all values x i

Re: Delete all not allowed characters..

2007-10-25 Thread Paul Hankin
ict as given doesn't work on character's that aren't allowed: it should map ints to ints rather than ints to strings. Anyway, there's no need to pay the cost of building a full mapping dict when most of the entries are the same. Something like this can work: from collections import defaultdict def clear(message): allowed = u'abc...' clear_translate = defaultdict(lambda: ord(u' ')) clear_translate.update((c, c) for c in map(ord, allowed)) return message.translate(clear_translate) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Proposal: Decimal literals in Python.

2007-10-27 Thread Paul Hankin
#x27; (zero) in uppercase, eg. > 0Q123 is clearer than 0O123 (0 oh 123), although lowercase is better, > eg. 0q123 or 0o123. Even clearer is not to allow octal literals :) Is there *any* use for them? -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: good example of C extension for Mac OS X

2007-10-27 Thread Paul Hankin
On Oct 27, 4:11 pm, chewie54 <[EMAIL PROTECTED]> wrote: > Does anyone now of a good example to use as template for a C program > extension that needs to be built on the Mac OS X. There's good, basic examples in the documentation on extending python: http://docs.python.org/ext

Re: "and" and "or" on every item in a list

2007-10-29 Thread Paul Hankin
ins 'all' and 'any' that do exactly these. If you're using python <2.5, then you can support shortcut evaluation - there's no need to check every element once you find a false in 'all' or a true in 'any'. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: 3 number and dot..

2007-10-31 Thread Paul Hankin
r i in range(0, len(x), 3))[::-1] Or more simple-mindedly... def conv(x, sep='.'): x, y = str(x), [] while x: y.append(x[-3:]) x = x[:-3] return sep.join(reversed(y)) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Method needed for skipping lines

2007-10-31 Thread Paul Hankin
in_generated: yield line in_generated = in_generated and not line.starts_with('End') And count the remaining ones... def count_lines(filename): return len(omit_generated_lines(open(filename, 'r'))) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: a few questions.

2007-10-31 Thread Paul Hankin
ge(5): hundreds = stores[i] // 100 print "Store: %i %s" % (i + 1, '*' * hundreds) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: help on dictionary

2007-11-01 Thread Paul Hankin
. > > Do you have any suggestion on how to do that? Use .get instead of [], and use sensible variable names: return max(words, key=lambda word: model.get(word, 1)) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Sub-sort after sort

2007-11-02 Thread Paul Hankin
s: > > test = [{'name': 'John Smith', 'location': 'CA',},{'name': 'John > Smith', 'location': 'AZ',},] > > I would want to sort by name first, then sub sort by location. Any > ideas? Thanks! test.sort(key=lambda x:(x['name'], x['location'])) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: problem with iteration

2007-11-03 Thread Paul Hankin
ut 'sre' and 'Match' suggests something to do with regular expressions. Given the variable name, you obviously expected a list of files, so you could look at where html_files is created (with a re.match call) to see why your expectation differs from what happened. Perhaps you could add more print statements to the loops to see what values 'files' and 'name' take. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: python newbie

2007-11-03 Thread Paul Hankin
> > """How to define a callable module""" ... > > Oh neat, thanks, I'll have to file that one away, and use it now and then. I'm intrigued - when would you want a callable module? -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Trouble with for loop

2007-11-06 Thread Paul Hankin
for f in range(1, 10): Or all the same? for a in range(1, 10): b = c = d = e = f = a Whatever you're doing though, there's almost certainly a better way. -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: List to Tuple and Tuple to List?

2007-11-06 Thread Paul Hankin
(x, from_type, to_type) for x in source) def list2tuple(source): return transform(source, list, tuple) def tuple2list(source): return transform(source, tuple, list) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Trouble with for loop

2007-11-06 Thread Paul Hankin
t?) a + 10*b == 0 (mod 2) => a is even a + 10*b + ... + 10^4*e == 0 (mod 5) => a is 0 or 5 Therefore, a is 0, so only considering digits 1-9 is a mistake. So, something like this is probably what you want... for n in range(10 ** 5, 10 ** 6): digits = map(int, str(n)) ... test digits -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: regular expressions

2007-11-06 Thread Paul Hankin
abcd What have you come up with so far? Have you looked at the 're' module? -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Need help writing coroutine

2007-11-07 Thread Paul Hankin
i in xrange(1, 6): yield i if score(i): print "%d passed!" % i def is_odd(n): return n % 2 def m(): for i in parser(is_odd): # Presumably do something here... pass -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Closure/binding problem or misunderstanding

2007-11-09 Thread Paul Hankin
nd is to add a variable with a default value. class path(object): def __init__(self, **subdirs): for name, path in subdirs.iteritems(): def getpath(path=path): return path setattr(self, name, getpath) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Avoid newline at the end

2007-11-11 Thread Paul Hankin
gs = '\n'.join('/home/%s/%s/log/%s' % (row[1], row[0], name) for row in resultSet for name in ('access.log', 'error.log')) -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: Moving from java to python.

2007-11-12 Thread Paul Hankin
or i in connections] getConnections can be much simpler... def getConnections(self): return zip(self.connected, self.weights) The 'uid' business makes me suspicious: what's it for? If you need it, you probably need to initialise with an explicit test for None rather than just 'if uid' which will be wrong if you use a uid of 0... self.id = uid if uid is not None else id(self) HTH -- Paul Hankin -- http://mail.python.org/mailman/listinfo/python-list

Re: simple question on persisting variable values in a list

2007-11-20 Thread Paul Hankin
any help,,, > > Not sure if this is what you want, but here's what I did: > > > > >>> x = 'blah\nblah\n' > >>> lst = [] > >>> templine = '' > >>> for char in x: > > if char == '\n': >

  1   2   >