Re: Mathematica 7 compares to other languages

2008-12-10 Thread Roberto Bonvallet
Arnaud Delobelle wrote:

 def unit(v):
 return map((sum(map(lambda x:x*x, v))**0.5).__rdiv__, v)

 The hard bit was to make it less readable than the Ruby version ;)

I loved the use of __rdiv__ :)
I would have proposed the more straightforward:

def u(v):
return [x/sum(x**2 for x in v)**0.5 for x in v]

or, in order to avoid computing the norm for each element:

def u(v):
return (lambda norm: [x/norm for x in v])(sum(x**2 for x in v)
**0.5)
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-07 Thread Roberto Bonvallet
On Mar 7, 6:16 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 I believe it is one of those things that everybody (for some value of
 everybody) does because that's what they were taught to do

Actually I was never taught to, and I never learnt about it anywhere.
I started
to do it spontaneously in order to tell apart end-of-sentence periods
from abbreviation
periods.  Anyway, I don't think it's something people should be forced
to do.

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


Re: Elementary string-formatting

2008-01-12 Thread Roberto Bonvallet
On Jan 12, 10:15 pm, Odysseus [EMAIL PROTECTED] wrote:
 P.S. Is there a preferable technique for forcing floating-point division
 of two integers to that used above, multiplying by 100.0 first?

Put this at the beginning of your program:

from __future__ import division

This forces all divisions to yield floating points values:

 1/3
0
 from __future__ import division
 1/3
0.1


HTH,
--
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distinguishing attributes and methods

2007-12-08 Thread Roberto Bonvallet
On Dec 8, 4:19 am, [EMAIL PROTECTED] wrote:
 With properties, attributes and methods seem very similar.  I was
 wondering what techniques people use to give clues to end users as to
 which 'things' are methods and which are attributes.

Methods are verbs, attributes are nouns :)

--
Roberto Bonvallet


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


Re: Limit Guessing Algorithm

2007-12-02 Thread Roberto Bonvallet
On Dec 2, 5:27 pm, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:
 It will accept a few data points (x,f(x)) of a function
 that converges to some finite value when x converges to infinity. I
 need the algorithm to guess what that limit is.

Since there are an infinity of ways to estimate the limit, I suggest
sticking to the simplest one:

def guess_limit(points):
x, y = max(points)
return y

 [
 [1,8],
 [2,7.5],
 [3,7.25],
 [4,7.125]
 ]
 Then the output will be 7. Or at least something close.

For this data set, my function will return 7.125.  Is it close enough?
Finding a better estimation is more a math problem than a Python one.

Best regards,
--
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 3 number and dot..

2007-11-02 Thread Roberto Bonvallet
On 31 oct, 22:21, Paul Rubin http://[EMAIL PROTECTED] wrote:
 def convert(n):
assert type(n) in (int,long)

I'd replace this line with  n = int(n), more in the spirit of duck
typing.

--
Roberto Bonvallet

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


Re: 3 number and dot..

2007-11-02 Thread Roberto Bonvallet
On 2 nov, 14:54, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 Not necessarily. Something duck typing is too liberal in what it accepts.
 You might want convert(math.pi) to raise an exception

What I meant was that the function should not reject unnecessarily non-
numeric
things that can be converted to a number, like a string.  However,
you're right:
numeric things that are not integers should not be treated silently as
if they
were.

 although I'd suggestion an assert is the wrong test. A better test would be an
 explicit type check with raise.

I completely agree.

Cheers,
--
Roberto Bonvallet


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


Re: 3 number and dot..

2007-10-31 Thread Roberto Bonvallet
On 31 oct, 16:58, Abandoned [EMAIL PROTECTED] wrote:
 Hi..
 I want to do this:
 for examle:
 12332321 == 12.332.321

 How can i do?

 x = 12332321
 '.'.join(''.join(i for n, i in g) for k, g in 
 groupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1]
'12.332.321'


--
Roberto Bonvallet

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


Re: Iteration for Factorials

2007-10-23 Thread Roberto Bonvallet
On Oct 22, 11:45 am, Ant [EMAIL PROTECTED] wrote:
 Er, no. And neither is mine. You may want to google for the definition
 of factorial!

Don't google for the definition... google for the answer!

import urllib
import re
urllib.URLopener.version = Mozilla/4.0

def fact(x):
r = re.compile(r%d ! = (\d+) % x)
for line in urllib.urlopen(http://www.google.cl/search?q=%d%%21;
% x):
m = r.search(line)
if m:
return int(m.group(1))

--
Roberto Bonvallet

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


Re: Normalize a polish L

2007-10-23 Thread Roberto Bonvallet
On Oct 22, 7:50 pm, Mike Orr [EMAIL PROTECTED] wrote:
 Well, that gets into official vs unofficial conversions.  Does the
 Spanish Academy really say 'ü' should be converted to 'u'?

No, but it's the only conversion that makes sense.  The only Spanish
letter that doesn't have a standard common conversion by convention
is  'ñ', which is usually ASCIIfied as n, nn, gn, nh, ni, ny, ~n, n~,
or N, with all of them being frequently seen on the Internet.

 But whether that should be hardcoded
 into a blog URL library is different matter, and if it is there should
 probably be plugin tables for different preferred standards.

Actually there is a hardcoded conversion, that is dropping all
accented letters altogether, which is IMHO the worst possible
convention.  I have a gallery of pictures of Valparaíso and Viña del
Mar whose URL is .../ValparaSoViADelMar.  And if I wrote a blog entry
about pingüinos and ñandúes, it would appear probably as .../ping-inos-
and-and-es.  Ugly and off-topic :)

--
Roberto Bonvallet

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


Re: Normalize a polish L

2007-10-16 Thread Roberto Bonvallet
On Oct 15, 6:57 pm, John Machin [EMAIL PROTECTED] wrote:
 To asciify such text, you need to build a look-up table that suits
 your purpose. unicodedata.decomposition() is (accidentally) useful in
 providing *some* of the entries for such a table.

This is the only approach that can actually work, because every
language has different conventions on how to represent text without
diacritics.

For example, in Spanish, ü (u with umlaut) should be represented as
u, but in German, it should be represented as ue.

pingüino - pinguino
Frühstück - Fruehstueck

I'd like that web applications (e.g. blogs) took into account these
conventions when creating URLs from the title of an article.
--
Roberto Bonvallet

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

Re: Nested For and While Statements

2007-09-24 Thread Roberto Bonvallet
On Sep 24, 3:28 pm, [EMAIL PROTECTED] wrote:
 [...] where I start getting some errors.
 I'm hoping I won't have to post my code

Doctor, I'm feeling bad.  I hope I won't have to tell you my
symptoms.  What do I have?

Please provide the actual errors and the actual code.  It is easier,
less error prone and more useful to copy and paste them instead of
writing some pseudocode.  Maybe the repeated index i is a typo you
made when writing this post and the original code is correct, but we
don't have any way to know that.

--
Roberto Bonvallet

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


Re: subclass of integers

2007-09-15 Thread Roberto Bonvallet
On Sep 14, 10:30 am, Mark Morss [EMAIL PROTECTED] wrote:
 I would like to construct a class that includes both the integers and
 None.  I desire that if x and y are elements of this class, and both
 are integers, then arithmetic operations between them, such as x+y,
 return the same result as integer addition.  However if either x or y
 is None, these operations return None.

No need to create a new class:

try:
result = a * b
except TypeError:
result = None

--
Roberto Bonvallet

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


Re: Variable variable name or variable lvalue

2007-09-11 Thread Roberto Bonvallet
On Aug 15, 4:19 pm, Peter Otten [EMAIL PROTECTED] wrote:
 If you want to simplify things somewhat you can merge the two loops into
 one:

 numbers = [12.5, 25, 12.5]
 accu = Material(numbers[0])
 for x in numbers[1:]:
 accu += Material(x)
 period = Slab(accu)

Better to use the `sum' builtin and a generator expression:

period = Slab(sum(Material(x)) for x in numbers)

--
Roberto Bonvallet

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


Re: Speed of Python

2007-09-07 Thread Roberto Bonvallet
On Sep 7, 12:42 pm, wang frank [EMAIL PROTECTED] wrote:
 Here is the bench1.py:
 import math
 def bench1(n):
 for i in range(n):
 for j in range(1000):
 m=j+1
 z=math.log(m)
 z1=math.log(m+1)
 z2=math.log(m+2)
 z3=math.log(m+3)
 z4=math.log(m+4)
 z5=math.log(m+5)
 z6=math.log(m+6)
 z7=math.log(m+7)
 z8=math.log(m+8)
 z9=math.log(m+9)
 return z9

 Is my conclusion correct that Python is slower than matlab?

Show us your Matlab code in order to see if both are equivalent.
Your Python code creates n lists of 1000 elements, so you're not
actually
measuring only the numeric computations.

Cheers,
--
Roberto Bonvallet

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

Re: Speed of Python

2007-09-07 Thread Roberto Bonvallet
On Sep 7, 1:37 pm, wang frank [EMAIL PROTECTED] wrote:
 Hi,
 Here is the matlab code:
 function [z]=bench1(n)
 for i=1:n,
 for j=1:1000,
 z=log(j);
 z1=log(j+1);
 z2=log(j+2);
 z3=log(j+3);
 z4=log(j+4);
 z5=log(j+5);
 z6=log(j+6);
 z7=log(j+7);
 z8=log(j+8);
 z9=log(j+9);
 end
 end
 z = z9;

 I am not familiar with python, so I just simply try to reproduce the same
 code in python.
 If you think that my python script is not efficient, could you tell me how
 to make it more efficient?

   import math
   def bench1(n):
   for i in range(n):
   for j in range(1000):

The range(1000) call creates a list of 1000 elements each time it is
called.
This is expensive.  You could try something like the following:

def bench1a(n):
r = range(1000)
for i in range(n):
# reuse the list
for j in r:
...

def bench1b(n):
for i in range(n):
# don't use a list at all
j = 0
while j  1000:
...

I'm no expert on Python optimization either, so I cannot guarantee
that both are
the best way to write this algorithm.

   [...]
   m=j+1

This step also doesn't occur in the Matlab code.

Hope this helps, although maybe I'm not the right person to talk about
optimization, and I haven't measured my code.

--
Roberto Bonvallet


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

Re: Problem with extremely small real number

2007-09-03 Thread Roberto Bonvallet
On 3 sep, 10:56, Andrea [EMAIL PROTECTED] wrote:

 def binomial(n, k):
 assert n0 and isinstance(n, (int, long)) and isinstance(k,
 (int,long))

Don't use assert to check whether the parameters have the right value.
assert should be used to claim that a certain condition always hold in
your program.
Prefer the following form, which will make debugging clearer:

if n = 0:
raise ValueError(Wrong value of n)
if not isinstance(n, (int, long)):
raise TypeError(Wrong type of n)
if not isinstance(k, (int, long)):
raise TypeError(Wrong type of k)

Anyway, you shouldn't be checking the type of the parameters either.
It could be more useful if you cast to the desired type.  This way,
your function will handle gracefully the case when you accidentally
pass a string as a parameter:

n = int(n)
k = int(k)
if n = 0:
raise ValueError(Wrong value of n: %d % n)

Best regards,
--
Roberto Bonvallet

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


Re: programmatically define a new variable on the fly

2007-08-09 Thread Roberto Bonvallet
On Aug 9, 6:11 pm, Lee Sander [EMAIL PROTECTED] wrote:
 I would like to define a new variable which is not predefined by me.
 For example,
 I want to create an array called X%s where %s is to be determined
 based on the data I am processing.

Use a dictionary.

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


Re: Sorting dict keys

2007-07-20 Thread Roberto Bonvallet
On 20 jul, 18:50, Alex Popescu [EMAIL PROTECTED] wrote:
 If you just want to iterate over your dict in an ordered manner than all
 you have to do is:

 for k in my_dict.keys().sort():
   # rest of the code

sort() returns None, so this code won't work either.

--
Roberto Bonvallet

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


Re: Sorting dict keys

2007-07-20 Thread Roberto Bonvallet
On 20 jul, 19:34, [EMAIL PROTECTED] wrote:
 copy.copy returns a new object:

  copy.copy(a.keys())

 [1,2,3]

 Then why doesn't copy.copy(a.keys()).sort() work??

It works, but you don't notice it, because you don't save a reference
to the new list.
Try this:

  c = copy.copy(a.keys())
  c.sort()

--
Roberto Bonvallet

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


Re: running a random function

2007-06-07 Thread Roberto Bonvallet
On 7 jun, 11:56, David Bear [EMAIL PROTECTED] wrote:
 I would like to write some code that would randomly select a function from a
 list of functions and call it. I was looking in the globals names space and
 randomly selecting items that were of type function.. but I didn't see a
 way of actually running the function.

Try this:

def f(x):
print Calling f with arg %s % x
def g(x):
print Calling g with arg %s % x
def h(x):
print Calling h with arg %s % x

import random
functions = [f, g, h]
for i in range(10):
random.choice(functions)(25)

HTH, cheers.
--
Roberto Bonvallet

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


Re: removing spaces between 2 names

2007-05-15 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 s = jk hij ght
 print .join(s.split( ))

.join(s.split()) is enough.
--
Roberto Bonvallet

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


Re: C parsing fun

2007-02-08 Thread Roberto Bonvallet
Károly Kiripolszky [EMAIL PROTECTED] wrote:
 I've found a brute-force solution. In the preprocessing phase I simply
 strip out the comments (things inside comments won't appear in the
 result) and replace curly brackets with these symbols: #::OPEN::# and
 #::CLOSE::#.

This fails when the code already has the strings #::OPEN::# and
#::CLOSE:: in it.

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


Re: Convert from unicode chars to HTML entities

2007-02-08 Thread Roberto Bonvallet
Steven D'Aprano [EMAIL PROTECTED] wrote:
 I have a string containing Latin-1 characters:
 
 s = u© and many more...
 
 I want to convert it to HTML entities:
 
 result =
 copy; and many more...
[...[
 Is there a batteries included solution that doesn't involve
 reinventing the wheel?

recode is good for this kind of things:

$ recode latin1..html -d mytextfile

It seems that there are recode bindings for Python:

$ apt-cache search recode | grep python
python-bibtex - Python interfaces to BibTeX and the GNU Recode library

HTH, cheers.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One more regular expressions question

2007-01-18 Thread Roberto Bonvallet
Victor Polukcht wrote:
 My actual problem is i can't get how to include space, comma, slash.

Post here what you have written already, so we can tell you what the
problem is.

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


Re: DOTALL not working as expected

2007-01-18 Thread Roberto Bonvallet
Stefan Palme wrote:
 using the re module of Python (2.3 and 2.4), I tried the following:
 
   import re
   print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL)
 
 Just noticed, that it works when *compiling* the pattern:
 
  import re
  p = re.compile('X.*?Y', re.DOTALL)
  print re.sub(p, 'Z', 'Xab\ncdY')
 
 Still the question - my fault or a bug?

Your fault.  According to the documentation [1], the re.sub function takes
a count as a fourth argument, not the compilation flags.

[1] http://docs.python.org/lib/node46.html

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing a matrix (list[][]) ?

2007-01-13 Thread Roberto Bonvallet
jairodsl wrote:
 How can I find the minus element greater than zero in a matrix, my
 matrix is
 
 matrix=
 [9,8,12,15],
 [0,11,15,18],
 [0,0,10,13],
 [0,0,0,5]
 
 I dont want to use min function because each element in the matrix is
 associated to (X,Y) position.

What output are you expecting from your example matrix?  If you are expecting
it to be 5 (the smallest positive element), using min is the way to do it:

 matrix = [[9,  8, 12, 15],
...   [0, 11, 15, 18],
...   [0,  0, 10, 13],
...   [0,  0,  0,  5]]
 min(min(x for x in row if x  0) for row in matrix)
5

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


Re: parsing a file name

2007-01-12 Thread Roberto Bonvallet
CSUIDL PROGRAMMEr wrote:
 I have a filename
 cairo-2.3.4.src.rpm
 Is there any way i can only get 2.3.4 from this file name

  a = cairo-2.3.4.src.rpm
  import re
  re.compile(r\d+([.]\d+)*).search(a).group(0)
 '2.3.4'
  a.split(-)[-1][:-len(.src.rpm)]
 '2.3.4'
  ..join(map(str, range(2, 5)))
 '2.3.4'

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


Re: skip last line in loops

2006-12-15 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 do it lazily:

  last_line = None
  for line in open(file):
  if last_line:
  print last_line
  last_line = line

 or just gobble up the entire file, and slice off the last item:

  for line in list(open(file))[:-1]:
  print line

 /F
 
 hi
 would it be a problem with these methods if the file is like 20Gb in
 size...?

The second one would be a problem, since it creates a list containing all
the lines of the file.  Use the lazy approach.

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


Re: AI library

2006-12-15 Thread Roberto Bonvallet
Felix Benner wrote:
[...]
def a-star(self, nodeFrom, nodeTo):
searches the shortest path (minimal weight) from
nodeFrom to nodeTo.
pass

 def a-star(self, nodeFrom, nodeTo):
  File stdin, line 1
def a-star(self, nodeFrom, nodeTo):
 ^
SyntaxError: invalid syntax

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


Re: Restrictive APIs for Python

2006-12-15 Thread Roberto Bonvallet
Will Ware wrote:
 Python has no inherent provision for a restrictive API that blocks
 accesses to methods and variables outside an allowed set.
 Inexperienced Python programmers may fail to adhere to an agreed-upon
 API, directly accessing the private internals of a class.

Just don't document those private internals.
Or document that they must not be accessed directly.

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


Re: Conditional iteration

2006-12-14 Thread Roberto Bonvallet
at wrote:
 I think by approving
 
 a = b if condition else c
 
 used to avloind
 
 if condition:
a = b
 else:
a = c
 
 which is dealing with same psychological problem, Guido also recognizes some
 need...

GvR did not introduce the new conditional syntax because he felt it was
needed or just to avoid typing a couple of extra lines.  He did it just to
avoid people keep using the ugly and error-prone a and b or c idiom.  See
the related PEP:  http://www.python.org/dev/peps/pep-0308/

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


Re: speed of python vs matlab.

2006-12-14 Thread Roberto Bonvallet
Chao wrote:
 My Bad,  the time used by python is 0.46~0.49 sec,
 I tried xrange, but it doesn't make things better.

Actually it does:  it doesn't waste time and space to create a big list.

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


Re: Routine for prefixing '' before every line of a string

2006-12-14 Thread Roberto Bonvallet
Sanjay wrote:
 Is somewhere a routine useful to convert a string to lines of maxsize,
 each prefixed with a ''. This is a typical requirement for 'keeping
 existing text while replying to a post in a forum'.

Take a look to the textwrap module:
http://docs.python.org/lib/module-textwrap.html

Here is an example:

# the text is actually a very long line
text = '''Lorem ipsum dolor sit amet, consectetuer adipiscing [...]'''
prefix = ''

import textwrap
lines = [%s %s % (prefix, line) for line in textwrap.wrap(text, width=75)]

for line in lines:
print line

This prints:

 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam rhoncus,
 justo eget facilisis gravida, lorem elit pellentesque urna, sed imperdiet
 orci nisl sed nibh. Curabitur dignissim pretium magna. Proin nunc justo,
 luctus ut, mollis sed, bibendum vel, nibh. Morbi rutrum est in nisl. Fusce
 sagittis. Integer varius. Vivamus dapibus lectus sed nisl. Phasellus
 gravida dignissim augue. Curabitur eget orci. Nulla ante augue, adipiscing
 a, consequat ut, elementum ac, libero. Donec malesuada lacus vel quam. Ut 
a
 massa vel velit fringilla rutrum. Maecenas massa sem, vulputate non,
 lacinia eu, cursus ut, urna. Donec ultrices sollicitudin nunc. Sed vel 
arcu
 in lacus posuere faucibus. Lorem ipsum dolor sit amet, consectetuer
 adipiscing elit.

HTH.  Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuple.index()

2006-12-14 Thread Roberto Bonvallet
Glenn Hutchings wrote:
 But there are situations where you might want to treat it as a
 read-only list.  E.g., an argument to a function, so that you can
 guarantee the function won't modify it.  In that case, it makes sense
 for the non-modifying methods (index() and count()) to be available.

list(my_arg).index(...)

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


Re: Iterating over several lists at once

2006-12-13 Thread Roberto Bonvallet
Gal Diskin wrote:
 Hi,
 I am writing a code that needs to iterate over 3 lists at the same
 time, i.e something like this:
 
 for x1 in l1:
for x2 in l2:
for x3 in l3:
print do something with, x1, x2, x3

What's wrong with this?

[...]
 I'd be very happy to receive ideas about how to do this in one loop and
 with minimal initialization (if at all required).

def cartesian_product(l1, l2, l3):
for i in l1:
for j in l2:
for k in l3:
yield (i, j, k)

for (i, j, k) in cartesian_product(l1, l2, l3):
print do something with, i, j, k

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


Re: newbie - HTML character codes

2006-12-13 Thread Roberto Bonvallet
ardief wrote:
[...]
 And I want the HTML char codes to turn into their equivalent plain
 text. I've looked at the newsgroup archives, the cookbook, the web in
 general and can't manage to sort it out. I thought doing something like
 this -
 
 file = open('filename', 'r')

It's not a good idea to use 'file' as a variable name, since you are
shadowing the builtin type of the same name.

 ofile = open('otherfile', 'w')
 
 done = 0
 
 while not done:
line = file.readline()
if 'THE END' in line:
done = 1
elif 'mdash;' in line:
line.replace('mdash;', '--')

The replace method doesn't modify the 'line' string, it returns a new string.

ofile.write(line)
else:
ofile.write(line)

This should work (untested):

infile  = open('filename', 'r')
outfile = open('otherfile', 'w')

for line in infile:
outfile.write(line.replace('mdash;', '--'))

But I think the best approach is to use a existing aplication or library
that solves the problem.  recode(1) can easily convert to and from HTML
entities:

recode html..utf-8 filename

Best regards.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Conditional iteration

2006-12-13 Thread Roberto Bonvallet
at wrote:
 More pythonic in view would be:
 
 for x in [-2, -1, 0, 1, 2, 3, 4] if x  0:
... more code ...

Pythonic?  Do you realize that Python hasn't even adopted well-known
statements like 'switch' and 'do while' because they would be redundant?

This could be more convenient to you, but certainly not pythonic.
Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.has_key(x) versus 'x in dict'

2006-12-06 Thread Roberto Bonvallet
Fredrik Lundh wrote:
[...]
 this is why e.g.
 
string[:len(prefix)] == prefix
 
 is often a lot faster than
 
string.startswith(prefix)

This is interesting.  In which cases does the former form perform better?
[I won't stop using str.startswith anyway :) ]

Regards.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict.has_key(x) versus 'x in dict'

2006-12-06 Thread Roberto Bonvallet
Andy Dingley wrote:
 I need to generate a set (lots of intersections involved), but then I
 need to display it sorted
 
lstBugsChanged = [ bugId for bugId in setBugsChanged ]
lstBugsChanged.sort()

In Python  2.4:

sorted(setBugsChanged)

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


Re: dict.has_key(x) versus 'x in dict'

2006-12-06 Thread Roberto Bonvallet
I wrote:
 In Python  2.4:

lastline.replace(, =)

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


Re: dict.has_key(x) versus 'x in dict'

2006-12-06 Thread Roberto Bonvallet
Andy Dingley wrote:
 Out of interest, whats the Pythonic way to simply cast (sic) the set to
 a list, assuming I don't need it sorted?  The list comprehension?

mySet  = set(myList)
myList = list(mySet)

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


Re: Python regular expression

2006-12-05 Thread Roberto Bonvallet
Wehrdamned wrote:
 As I understand it, python uses a pcre engine to work with regular
 expression.
[...]
 My question is, then, why expressions like :
 re.compile('asd|(?-i:QWE)', re.I)
[...]
 don't work? They are ok in perl... 

From http://docs.python.org/lib/module-re.html:

This module provides regular expression matching operations
*similar* to those found in Perl.

Similar != the same.  See http://docs.python.org/lib/re-syntax.html for
details about valid syntax for regular expressions in Python.

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for i in range() anti-pattern [was Re: trouble writing results to files]

2006-11-30 Thread Roberto Bonvallet
Steven D'Aprano wrote:
 On Wed, 29 Nov 2006 17:00:30 +0100, Fredrik Lundh wrote:
 
 Neil Cerutti wrote:
 
 BTW, iterating over range(len(a)) is an anti-pattern in Python.
 
 Unless you're modifying elements of a, surely?
 
 and needs to run on a Python version that doesn't support enumerate.
 
 This isn't meant as an argument against using enumerate in the common
 case, but there are circumstances where iterating with an index variable
 is the right thing to do. Anti-pattern tends to imply that it is always
 wrong.

Right, I should have said:  iterating over range(len(a)) just to obtain the
elements of a is not the pythonic way to do it.

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PythonTidy

2006-11-30 Thread Roberto Bonvallet
Chuck Rhode wrote:
 I couldn't find a routine to clean up, regularize, and reformat Python
 code, so I wrote one:
 
  http://www.lacusveris.com/PythonTidy/PythonTidy.python
 
 Now, I'm looking for beta-testers.  Compensation is a bit on the low
 side.  In fact it's limited to the satisfaction of helping out.

$ cat test.py
#!/usr/bin/env python2.5
# vim: set fileencoding=utf-8 :

for i in xrange ( 3) :
  print   i

$ python2.5 PythonTidy.python  test.py
#!/usr/bin/python
# -*- coding: utf-8 -*-

for i in xrange(3):
print i

About changing the shebang line:  I'll take it as a bug.
About changing the encoding declaration from vim-style to emacs-style:
I'll take it as an insult :)

Both are comments, and should be left that way.  Besides, there is no
officially preferred way for each of them.  BTW, in a recent thread on
this newsgroup, most people said they preferred #!/usr/bin/env python over
#!/usb/bin/python for the shebang line. See http://tinyurl.com/yngmfr .

Best regards.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PythonTidy

2006-11-30 Thread Roberto Bonvallet
Laurent Pointal wrote:
 ...
 # vim: set fileencoding=utf-8 :
 ...
 # -*- coding: utf-8 -*-
 ...
 
 This is not emacs-style, this is Python normalized source encoding
 directive for correct interpretation of u... strings by Python
 interpreter.
 
 See http://www.python.org/dev/peps/pep-0263/

The -*- syntax is emacs-style.  The encoding directive is anything that
matches rcoding[=:]\s*([-\w.]+).  The docs recommend to use either
emacs-style or vim-style.  See http://docs.python.org/ref/encodings.html

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PythonTidy

2006-11-30 Thread Roberto Bonvallet
Chuck Rhode wrote:
[...]
 Thanks, too, for trying *PythonTidy*.

No, thanks you for writing such a tool!

 [...] nevertheless, most [options] are declared near the beginning where
 they sit just begging for end-user involvement.  See: CODING_SPEC and
 SHEBANG.

The fact that I immediately noticed them and came up with an example to
raise both issues is a indicator of how easy it would be to customize the
script :)

Cheers!
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling functions with dynamic arguments

2006-11-29 Thread Roberto Bonvallet
SeanDavis12 wrote:
 I have a dictionary like:
 
 {a:1, b:2}
 
 and I want to call a function:
 
 def func1(a=3,b=4):
print a,b
 
 so that I get a=1,b=2, how can I go about that?  

func1(**yourdict)

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


Re: trouble writing results to files

2006-11-29 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 import csv
 output = csv.writer(open('/Python25/working/output.csv', 'a'))
 a = [apple, cranberry, tart]
 for elem in range(len(a)):
output.writerow(a[elem])

output.writerow expects a sequence as an argument.  You are passing a
string, which is a sequence of characters.  By the way, what output are you
expecting to get?  Do you want a file with only one line (apple,
cranberry, tart), or each fruit in a different line?

BTW, iterating over range(len(a)) is an anti-pattern in Python.  You should
do it like this:

for item in a:
output.writerow([item])

 Second, there is a significant delay (5-10 minutes) between when the
 program finishes running and when the text actually appears in the
 file.

Try closing the file explicitly.
Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trouble writing results to files

2006-11-29 Thread Roberto Bonvallet
Neil Cerutti wrote:
 On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote:
 BTW, iterating over range(len(a)) is an anti-pattern in Python.
 
 Unless you're modifying elements of a, surely?

enumerate is your friend :)

for n, item in enumerate(a):
if f(item):
a[n] = whatever

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


Re: Overloading if object unary operator

2006-11-29 Thread Roberto Bonvallet
Sarcastic Zombie wrote:
 For example, in the code:
 
 a = A(56)
 if a:
print Hoo hah!
 
 how can I insure that the if will come back true and fire off the print
 if and only if self.id is defined? I want to do this in an overloaded,
 generic way, if possible; I know that I could test for a.id.

Define a method called __nonzero__ that returns True or False.

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


Re: How to detect what type a variable is?

2006-11-29 Thread Roberto Bonvallet
Leandro Ardissone wrote:
 And how I can compare this type 'str' output ?
 I want to decide what to do if the var is an string and what to do if
 not..
 
 Tried with:
 if type(artistList) == type 'list':
 
 and
 if type(artistList) == list:
 
 but nothing..

type() doesn't return a string, it returns a type object.
You should try this:

if isinstance(artistList, list):
...

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying every alternate element of a sequence

2006-11-28 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 I have a list of numbers and I want to build another list with every
 second element multiplied by -1.
[...]
 But is there any other better way to do this.

I think the best way is the one that uses slices, as somebody suggested
in this thread.  This is another (worse) way, just for fun:

 from itertools import cycle
 input = [1, 2, 3, 4, 5, 6]
 wanted = [x * sign for x, sign in zip(input, cycle([1, -1]))]
 wanted
[1, -2, 3, -4, 5, -6]

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simple text parsing gets difficult when line continues to next line

2006-11-28 Thread Roberto Bonvallet
Jacob Rael wrote:
[...]
 I would line to identify if a line continues (if line.endswith('_'))
 and concate with the next line:
 
 line = line + nextLine
 
 How can I get the next line when I am in a for loop using readlines?

Don't use readlines.

# NOT TESTED
program = open(fileName)
for line in program:
while line.rstrip(\n).endswith(_):
line = line.rstrip(_ \n) + program.readline()
do_the_magic()

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programmatically finding significant data points

2006-11-14 Thread Roberto Bonvallet
erikcw wrote:
 I have a collection of ordered numerical data in a list.  The numbers
 when plotted on a line chart make a low-high-low-high-high-low (random)
 pattern.  I need an algorithm to extract the significant high and low
 points from this data.

In calculus, you identify high and low points by looking where the
derivative changes its sign.  When working with discrete samples, you can
look at the sign changes in finite differences:

 data = [...]
 diff = [data[i + 1] - data[i] for i in range(len(data))]
 map(str, diff)
['0.4', '0.1', '-0.2', '-0.01', '0.11', '0.5', '-0.2', '-0.2', '0.6',
'-0.1', '0.2', '0.1', '0.1', '-0.45', '0.15', '-0.3', '-0.2', '0.1',
'-0.4', '0.05', '-0.1', '-0.25']

The high points are those where diff changes from + to -, and the low
points are those where diff changes from - to +.

HTH,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sqlite3 views, if not exists clause

2006-11-14 Thread Roberto Bonvallet
Fredrik Lundh wrote:
 Josh wrote:
 
 THIS DOES NOT WORK, but it should!
 
 Python 2.5 was released on September 19th, 2006, and support for CREATE
 VIEW IF NOT EXISTS was added to sqlite on October 9th, 2006:

So?  from __future__ import ... should have supported this!  :o)

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


Re: SyntaxError: Invalid Syntax.

2006-11-10 Thread Roberto Bonvallet
ronrsr wrote:
   return =  MySQLdb.connect (host = db91x..com,
   user = ,
passwd = x,
db = homebase_zingers
   );

return is a reserved keyword.  You cannot have a variable with that name.

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


Re: SyntaxError: Invalid Syntax.

2006-11-10 Thread Roberto Bonvallet
ronrsr wrote:
 thanks for the speedy answer.  what i meant was:
 
 return   MySQLdb.connect (host = db91b.pair.com,
   user = homebase,
passwd = Newspaper2,
db = homebase_zingers
   );
 
 
 but even when I have that, I still get the same error.

Could you please copy and paste the exact code that is triggering the
error, and the exact error message?

(BTW, in Python you don't need to end your statements with a semi-colon)
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extract text from a string

2006-11-09 Thread Roberto Bonvallet
Jon Clements wrote:
 I have a string containing: +abc_cde.fgh_jkl\n and what I need to
 become is abc_cde.fgh_jkl.  Could anybody be so kind and write me a
 code of how to extract this text from that string?
 
 [...] Going by your example, it's tempting to suggest the best method
 would be string_name[1:-1] and that you don't need a regex.

...or string_name.lstrip('+').rstrip('\n')

I bet he doesn't need a regexp!
Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why can't you assign to a list in a loop without enumerate?

2006-11-01 Thread Roberto Bonvallet
Bjoern Schliessmann wrote:
 Fredrik Lundh wrote:
 
 what's wrong with using enumerate?  or a list comprehension?  or
 some other of the many different ways you can use to build a list
 from a set of values?
 
 Shouldn't there be one -- and preferably only one -- obvious way to
 do it? 8)

The obvious one is to use enumerate.
TOOWTDI allows less obvious ways to exist.

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


Re: To remove some lines from a file

2006-10-26 Thread Roberto Bonvallet
Sebastian Busch wrote:
 The task is:
 
 Remove the first two lines that don't begin with @ from a file.

awk 'BEGIN {c = 0} c  2  !/^@/ {c += 1; next} {print}'  mybeautifulfile

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


Re: dict problem

2006-10-25 Thread Roberto Bonvallet
Alistair King wrote:
 Hi,
 
 ive been trying to update a dictionary containing a molecular formula, but 
 seem to be getting this error:
 
 
 Traceback (most recent call last):
  File DS1excessH2O.py, line 242, in ?
updateDS1v(FCas, C, XDS)
 NameError: name 'C' is not defined
 
 dictionary is: 
 
 DS1v = {'C': 6, 'H': 10, 'O': 5}

Try DS1v['C'] instead of DS1v[C].

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dict problem

2006-10-25 Thread Roberto Bonvallet
Roberto Bonvallet wrote:
 Alistair King wrote:
 DS1v = {'C': 6, 'H': 10, 'O': 5}
 
 Try DS1v['C'] instead of DS1v[C].

 updateDS1v(FCas, C, XDS)
 updateDS1v(FHas, H, XDS)
 updateDS1v(FOas, O, XDS)
 updateDS1v(FNas, N, XDS)
 updateDS1v(FSas, S, XDS)
 updateDS1v(FClas, Cl, XDS)
 updateDS1v(FBras, Br, XDS)
 updateDS1v(FZnas, Zn, XDS)
 print DS1v

Sorry, I hadn't seen this part.
Change C, H, O, ... with 'C', 'H', 'O', ...

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


Re: list comprehension (searching for onliners)

2006-10-20 Thread Roberto Bonvallet
Gerardo Herzig wrote:
[...]
 and so on...what i need to do is some list comprehension that returns me 
 something like
[...]

You don't _need_ a list comprehension, you just _want_ one :)

[...]
 Ill keeping blew off my hair and drinking more cofee while searching for 
 this damn onliner im looking for.

I know, trying to put complex logic in one line makes you do all that.

Go for the multiliner!
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: More Noob Questions

2006-10-19 Thread Roberto Bonvallet
Omar wrote:
 more to come!

Please, use a more meaningful subject next time, like Integration of
Python and Flash or Where can I find vido tutorials.  That way it will
be easier to people that knows about the subject to find your message and
answer you.

And please think of us, non-native English speakers, that don't know slang
words like noob that don't even appear in the dictionaries and don't add
anything to your question.

Cheers,
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plotting histograms

2006-10-18 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 hi, I have some values(say from -a to a) stored in a vector and I want
 to plot a histogram for those values. How can I get it done in python.
 I have installed and imported the Matplotlib package but on executing
 the code
 [N,x]=hist(eig, 10) # make a histogram
 I am getting an error saying   NameError: name 'hist' is not
 defined.
 
 Is there any other way to plot histograms over a given range?

 # create random vector
... from random import randrange
 a = 5
 v = [randrange(-a, a+1) for i in xrange(100)]

 # print histogram
... for i in range(-a, a+1):
... print %+d %s % (i, '*' * v.count(i))
...
-5 *
-4 *
-3 *
-2 **
-1 **
+0 *
+1 
+2 ***
+3 *
+4 
+5 


:)
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: matrix Multiplication

2006-10-18 Thread Roberto Bonvallet
Sssasss wrote:
 hi evrybody!
 
 I wan't to multiply two square matrixes, and i don't understand why it
 doesn't work.
 Could you explain me?
 
 def multmat(A,B):
A*B
if len(A)!=len(B): return error

Wrong validation here:  you _can_ multiply two matrices with a different
number of rows!  And instead of returning error you should raise an
exception.

[...]

I suggest using a linear algebra package, but if you insist in using lists
of lists:

 b = [[1, 2, 3,  4],
...  [4, 5, 6,  7],
...  [7, 8, 9, 10]]
 
 a = [[1, 2, 3],
...  [4, 5, 6]]
 
 ab = [[sum(i*j for i, j in zip(row, col)) for col in zip(*b)] for row in a]
 ab
[[30, 36, 42, 48], [66, 81, 96, 111]]

Straightforward from the definition of matrix multiplication.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: naming objects from string

2006-09-21 Thread Roberto Bonvallet
manstey wrote:
[...]
 bob_apple=()
 bob_orange=()
 ..
 pete_red=()
 
 I then populate the 9 tuples with data [...]

You cannot populate a tuple.  If you want to insert the values
individually, you have to use a list.  If you insert them all together,
like this:  bob_apple = (1, 2, ..., 9), you don't need to initialize
bob_apple with an empty tuple.

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


Re: Replace single character at given position

2006-09-20 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 Martin Kulas:
 Are there better (faster) ways to achieve my goal?
 I have looked through the methods of type ``string''
 but I have not found any appropriate method or function.
[...]
 A second way is to use a list of strings with len=1. Like this:
 idx = 1
 s1 = pxthon
 l1 = list(s1)
 l1[idx] = 'y'
 ... more processing on the elements of l1, then at the end:
 .join(l1)
 'python'

There is a MutableString class that would be a better approach:
http://docs.python.org/lib/module-UserString.html

Anyway, I bet that what Martin wants to do can be done by using only string
methods :)
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are Python's reserved words reserved in places they dont need?tobe?

2006-09-14 Thread Roberto Bonvallet
Delaney, Timothy (Tim) wrote:
 Antoon Pardon wrote:
 
 This is just an idea of mine, nothing I expect python to adapt.
 But just suppose the language allowed for words in bold. A word
 in bold would be considered a reserved word, a word in non bold
 would be an identifier.
 
 Exactly how am I supposed to use my text editor to make words bold? Is
 every text editor supposed to understand a python format for code?

That's easy:  bpass/b, breturn/b, ...
Hmm, that's too verbose, maybe it would be better to do it just by
appending a underscore to the word:  pass_, return_, ...

wink_
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Request for tips on my first python script.

2006-09-08 Thread Roberto Bonvallet
Lex Hider wrote:
 Any tips on the code quality and use of python would be appreciated. I've
 got a feeling the overall structure is up the creek.
[...]
for opt, arg in opts:
if opt in (-l, --latest):
latest = int(arg)
elif opt in (--notfound):
ignoreNotFound = True #add notfound files to log 

Subtle bug here:  (--notfound) is not a tuple, is just a string, so what
you are actually testing is whether opt is a substring of --not-found.
To actually build a 1-element tuple, you have to put a trailing comma:

elif opt in (--notfound, ):

but it would be clearer if you just use:

elif opt == --notfound:

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


Re: replace deepest level of nested list

2006-09-04 Thread Roberto Bonvallet
David Isaac wrote:
 I have a list of lists, N+1 deep.
 Like this (for N=2):
 [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11'
 ,'b11']]]
 
 I want to efficiently produce the same structure
 except that the utlimate lists are replaced by a chosen (by index) item.
 E.g.,
 [['r00','r01'],['r10','r11']]
 
 N is not known ahead of time.

First thing I came up with:

 l = 
 [[['r00','g00','b00'],['r01','g01','b01']],[['r10','g10','b10'],['r11','g11','b11']]]
 def get_deepest(l, n):
... if isinstance(l[0], list):
... return [get_deepest(s, n) for s in l]
... else:
... return l[n]
... 
 get_deepest(l, 0)
[['r00', 'r01'], ['r10', 'r11']]
 get_deepest(l, 1)
[['g00', 'g01'], ['g10', 'g11']]
 

n is the chosen index.
HTH.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: This seems to crash my program and gives me errors on the #include statements

2006-09-04 Thread Roberto Bonvallet
[EMAIL PROTECTED] wrote:
 It is giving errors on the import statements..  I will get an error on
 the line where I import this routine import csoundroutines and then the
 when I import the the program that tried to import csoundroutines I get
 an error and on down the chain..

Please paste here the errors you get, and paste also the relevant code (not
the whole program) that triggers that error.

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


Re: Syntax suggestion.

2006-08-31 Thread Roberto Bonvallet
samir wrote:
 Being a fond of Python, I had this idea: Why not making Python a Unix
 shell?
[...]
 So, why not making the use of parentheses when a function is one lined
 optional to have commands like this:
[...]
 Then, why not making the comma optional too when executing such
 instructions:
[...]
 And finally, why not making the string parameter -less when it is the
 only parameter:

...so finally you get something that is exactly like any Unix shell, and
completely different to Python.  If you want Python to look like bash, work
like bash and have bash-like syntax, you should really consider using bash :)

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


Re: dictionary with object's method as thier items

2006-08-30 Thread Roberto Bonvallet
noro wrote:
 Is it possible to do the following:
 
 for a certain class:
[...]
 by some way create a dictionary that look somthing like that:
 
 d= {'function one': reference to C.func1(), \
  'function two': reference to C.func2(), \
  'function three': reference to C.func3()}
 
 and so i could access every method of instances of C

Something like this?

 class C:
... def f1(self):
... print i'm one
... def f2(self):
... print i'm two
...
 obj = C()
 d = {'one': obj.f1, 'two': obj.f2}
 d['one']()
i'm one
 d['two']()
i'm two

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


Re: refering to base classes

2006-08-29 Thread Roberto Bonvallet
glenn wrote:
 [...] In this trivial example, how could I modify the voice method of
 'dog' to  call the base class 'creatures' voice method from with in it?
 
 class creature:
def __init__(self):
self.noise=
def voice(self):
return voice: + self.noise
 
 class dog(creature):
def __init__(self):
self.noise=bark
 
def voice(self):
print brace your self:

If you want dog.voice() to just print voice: bark, you just have to omit
the voice method for the dog class: it will be inherited from creature.

If you want dog.voice() to do something else, you can call superclass'
method like this:

def voice(self):
creature.voice(self)
print brace your self
any_other_magic()

HTH
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Taking data from a text file to parse html page

2006-08-24 Thread Roberto Bonvallet
DH wrote:
  I'm trying to strip the html and other useless junk from a html page..
  Id like to create something like an automated text editor, where it
  takes the keywords from a txt file and removes them from the html page
  (replace the words in the html page with blank space)
[...]
 I've looked into using BeatifulSoup but came to the conculsion that my
 idea would work better in the end.

You could use BeautifulSoup anyway for the junk-removal part and then do
your magic.  Even if it is not exactly what you want, it is a good idea to
try to reuse modules that are good at what they do.

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


Re: find, replace and save string in ascii file

2006-08-23 Thread Roberto Bonvallet
peter wrote:
 Example (one block in ascii file):
 $
 NAME='ALFA'
 CODE='x'
 $
 
 There are many similar blocks in the file with different NAMEs and
 different CODEs. What I'm looking for is a script that searchs through
 whole file and finds all strings with name ALFA and based on what CODE
 is after each ALFA (can be x, y or z) the ALFA name is replaced by
 BETAx,BETAy or BETAz and so changed file saves.

name = myfile
lines = file(name).readlines()

for i, line in enumerate(lines):
if ALFA in line:
code = lines[i + 1].split(=)[1].strip(' \n)
lines[i] = line.replace(ALFA, BETA%s % code)

file(name).writelines(lines)

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


Re: text editor suggestion?

2006-08-21 Thread Roberto Bonvallet
John Salerno wrote:
 I'd really like to learn vim, but I spent days just trying to figure out 
 how to get the syntax highlighting and indentation working, where these 
 settings are and how to edit them, and it still doesn't work for me. It 
 just feels so insurmountable that I can't even start working with it yet 
 because I don't know how to tailor the settings.

Create a vimrc file (if you use Unix: ~/.vimrc) with the following lines in
it:

syntax on
set autoindent
set smartindent

If you find that using vim is hard, try using evim (easy vim).  It is part
of the standard vim distribution (actually it's the same program).  Anyway,
I suggest learning the classic modal vim, it's really worth it.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: code is data

2006-06-18 Thread Roberto Bonvallet
Ravi Teja [EMAIL PROTECTED] said:
 I *like* 1..5 (ada, ruby) instead of range(5). If I had macros, I would
 have done it myself for *my* code.

You can write your own preprocessor to handle things like that.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mapping None values to ''

2006-06-18 Thread Roberto Bonvallet
imho [EMAIL PROTECTED]:
 map(lambda x: , [i for i in [a,b,c] if i in (None,None) ])

You don't need map when using list comprehensions:

[ for i in [a, b, c] if i in (None, None)]

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


Re: Most elegant way to generate 3-char sequence

2006-06-10 Thread Roberto Bonvallet
2006/6/10, SuperHik [EMAIL PROTECTED]:
  Not necessarily vying for winner, but David's solution is highly
  specific as it doesn't do so well for something like
 
  aaa
  aab

 Right. But that wasn't the question :p

The question was about elegance, and elegance is when someone asks do
something 4 times for 5 strings of length 3 and you solve it for do
something n times for m strings of length p :)
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Concatenating dictionary values and keys, and further operations

2006-06-07 Thread Roberto Bonvallet
Girish said, through Gerard's forwarded message:
 Thanks a lot Gerard and Roberto.but i think i should explain the exact
 thing with an example.
 Roberto what i have right now is concatenating the keys and the
 corresponding values:
 e.g {'a':[1,2],'b':[3,4,5],'c':[6,7]}  should give me
 {'ab':[1,2][3,4,5] 'ac':[1,2][6,7] 'bc':[3,4,5][6,7]}
 The order doesnt matter here.It could be 'ac' followed by 'bc' and 'ac'.
 Also order doesnt matter in a string:the pair 'ab':[1,2][3,4,5] is same as
 'ba':[3,4,5][1,2].
 This representation means 'a' corresponds to the list [1,2] and 'b'
 corresponds to the list [3,4,5].

The problem if that the two lists aren't distinguishable when
concatenated, so what you get is [1, 2, 3, 4, 5].  You have to pack
both lists in a tuple: {'ab': ([1, 2], [3, 4, 5]), ...}

 d = {'a':[1, 2], 'b':[3, 4, 5], 'c':[6, 7]}
 d2 = dict(((i + j), (d[i], d[j])) for i in d for j in d if i  j)
 d2
{'ac': ([1, 2], [6, 7]), 'ab': ([1, 2], [3, 4, 5]), 'bc': ([3, 4, 5], [6, 7])}

 Now, for each key-value pair,e.g for 'ab' i must check each feature in the
 list of 'a' i.e. [1,2] with each feature in list of 'b' i.e. [3,4,5].So I
 want to take cartesian product of ONLY the 2 lists [1,2] and [3,4,5].

You can do this without creating an additional dictionary:

 d = {'a':[1, 2], 'b':[3, 4, 5], 'c':[6, 7]}
 pairs = [i + j for i in d for j in d if i  j]
 for i, j in pairs:
... cartesian_product = [(x, y) for x in d[i] for y in d[j]]
... print i + j, cartesian_product
...
ac [(1, 6), (1, 7), (2, 6), (2, 7)]
ab [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
bc [(3, 6), (3, 7), (4, 6), (4, 7), (5, 6), (5, 7)]

You can do whatever you want with this cartesian product inside the loop.

 Finally i want to check each pair if it is present in the file,whose
 format i had specified.

I don't understand the semantics of the file format, so I leave this
as an exercise to the reader :)
Best regards.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Concatenating dictionary values and keys, and further operations

2006-06-05 Thread Roberto Bonvallet
Girish Sahani [EMAIL PROTECTED]:
 I wrote the following code to concatenate every 2 keys of a dictionary and
 their corresponding values.
 e.g if i have tiDict1 = tiDict1 = {'a':[1,2],'b':[3,4,5]} i should get
 tiDict2={'ab':[1,2][3,4,5]} and similarly for dicts with larger no. of
 features.

Note that dictionary keys are not ordered, so--if I understand your
requirement correctly--it could also result in {'ba': [3, 4, 5, 1,
2]}.

 Now i want to check each pair to see if they are connected...element of
 this pair will be one from the first list and one from the seconde.g
 for 'ab' i want to check if 1 and 3 are connected,then 1 and 4,then 1 and
 5,then 2 and 3,then 2 and 4,then 2 and 5.

According to this, I think that you shouldn't concatenate the lists,
but keep them apart instead.

 The information of this connected thing is in a text file as follows:
 1,'a',2,'b'
 3,'a',5,'a'
 3,'a',6,'a'
 3,'a',7,'b'
 8,'a',7,'b'
 .
 This means 1(type 'a') and 2(type 'b') are connected,3 and 5 are connected
 and so on.
 I am not able to figure out how to do this.Any pointers would be helpful

I don't understand very well what you want to do.  Could you explain
it more clearly, with an example?
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Storing nothing in a dictionary and passing it to a function

2006-06-05 Thread Roberto Bonvallet
[EMAIL PROTECTED]:
 I'd like to have a dictionary (actually a nested dictionary) to call
 these functions so I can avoid if-then-elsing everything.  Eath
 dictionary item has three things in it: the function to be called, a
 string to pass to the function (which is also the key to the dict), and
 a tuple to pass to the function.  In the case of the function with no
 arguments, obviously I'd like not to pass anything.
[...]
 something like this:
 alldict = \
 {'pulse': {'func': self.arbtrandef, 'args':(2,5)},\
  'sin'  : {'func': self.arbtrandef, 'args':(2,3)},\
  'exp'  : {'func': self.arbtrandef, 'args':(2,4)},\
  'pwl'  : {'func': self.pwldef, 'args': 
 (None,)},\  --- how
 do I store no arguments?
  'sffm' : {'func': self.arbtrandef, 'args':(5,0)}}

 for it in alldict.items():
 name = it[0]
 args = (name,) + it[1]['args']
 it[1]['func'](*args)

I would do it like this:

alldict = {
'pulse': (self.arbtrandef, (2, 5)),   # function and args packed in a tuple
'sin'  : (self.arbtrandef, (2, 3)),
'exp'  : (self.arbtrandef, (2, 4)),
'pwl'  : (self.pwldef, ()),# empty tuple represented by ()
'sffm' : (self.arbtrandef, (5, 0)),
}
for (fname, (func, args)) in alldict.items():  # items unpacked directly
func(fname, *args)

Best regards.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reordering elements of a list

2006-06-04 Thread Roberto Bonvallet
greenflame [EMAIL PROTECTED]:
 Roberto: I do not understand the first half of the last line of your
 code.

[mainlist[i - 1] for i in orderinglist] is a list made with the
elements of orderinglist, but instead of taking the actual value i
from the list, the value that is taken is mainlist[i - 1].

If orderinglist is [3, 4, 2, 1], then [mainlist[i - 1] for i in
orderinglist] is:

[mainlist[3 - 1], mainlist[4 - 1], mainlist[2 - 1], mainlist[1 - 1]]

Remember that indexing starts from 0.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reordering elements of a list

2006-06-03 Thread Roberto Bonvallet
3 Jun 2006 17:46:49 -0700, greenflame [EMAIL PROTECTED]:
 Suppose the main list is: mainlist = list('qwertyuiop')

 Suppose the ordering list is: orderinglist = [3, 4, 2, 1]

 Then I am looking for a function that will take mainlist and
 orderinglist as arguments and return the following list:

 ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']

 mainlist = list('qwertyuiop')
 orderinglist = [3, 4, 2, 1]
 [mainlist[i - 1] for i in orderinglist] + mainlist[len(orderinglist):]
['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']

Best regards.
-- 
Roberto Bonvallet
-- 
http://mail.python.org/mailman/listinfo/python-list