[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
rnt 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
ision
This forces all divisions to yield floating points values:
>>> 1/3
0
>>> from __future__ import division
>>> 1/3
0.33331
>>>
HTH,
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
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 n
l 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
k with raise.
I completely agree.
Cheers,
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
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
oupby(enumerate(reversed(str(x))), lambda (n, i): n//3))[::-1]
'12.332.321'
>>>
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
e 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
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
; 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
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
--
rn 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
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
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
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
:
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
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/
e new list.
Try this:
c = copy.copy(a.keys())
c.sort()
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
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.
--
R
x27;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):
[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
es 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 inte
OSE::#.
This fails when the code already has the strings "#::OPEN::#" and
"#::CLOSE::" in it.
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
e 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
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
3],
... [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
7;
>>> 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
n't document those private internals.
Or document that they must not be accessed directly.
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
o):
File "", line 1
def a-star(self, nodeFrom, nodeTo):
^
SyntaxError: invalid syntax
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
e off the last item:
>>
>> for line in list(open("file"))[:-1]:
>> print line
>>
>>
>
> 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
) to be available.
list(my_arg).index(...)
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
> 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
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
e 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
ndant?
This could be more convenient to you, but certainly not pythonic.
Cheers,
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
;ofile.write(line)
This should work (untested):
infile = open('filename', 'r')
outfile = open('otherfile', 'w')
for line in infile:
outfile.write(line.replace('—', '--'))
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
k) in cartesian_product(l1, l2, l3):
print "do something with", i, j, k
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
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
I wrote:
> In Python > 2.4:
lastline.replace(">", ">=")
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
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
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
s.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 Bo
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
interpreter.
>
> See http://www.python.org/dev/peps/pep-0263/
The -*- syntax is emacs-style. The encoding directive is anything that
matches r"coding[=:]\s*([-\w.]+)". The docs recommend to use either
emacs-style or vim-style. See http://docs.python.org/ref/encodings.html
Chee
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
ern" 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
gt; 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
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
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):
attern 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
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
ESTED
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
er (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
.." should have supported this! <:o)
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
iff)
['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
t;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 sta
turn is a reserved keyword. You cannot have a variable with that name.
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
rser know which colon terminates the
'for' in the following example:
for i in 2:3:4:
...
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
le, 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
ly 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
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
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(F
> 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
s 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
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
... [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
ange(-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
: 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
ableString 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
st by
appending a underscore to the word: pass_, return_, ...
wink_
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
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
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
gt;>> 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
bash-like syntax, you should really consider using bash :)
--
Roberto Bonvallet
--
http://mail.python.org/mailman/listinfo/python-list
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,
k", 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
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
e 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
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
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
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
> > 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
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
e
'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
;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
s 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
arguments and return the following list:
>
> ['e', 'r', 'w', 'q', 't', 'y', 'u', 'i', 'o', 'p']
>>> mainlist = list('qwertyuiop')
>>> orderinglist = [3, 4, 2, 1]
>
88 matches
Mail list logo