[Tutor] Avoiding repetetive pattern match in re module
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Thu Jan 5 20:38:09 CET 2006
> >From a technical standpoint, it has "quadratic" complexity in terms of
> what work the computer is doing. It's related to the mathematical idea
> that 1 + 2 + 3 + 4 + ... + n = n(n+1).
>
> http://en.wikipedia.org/wiki/Triangle_number
Gaa, where did my division sign go? *grin*
Sorry, that equation should be:
1 + 2 + ... + n = n(n+1)/2
We can see this:
###############################################
>>> import operator
>>> def sumUpTo(n):
... return reduce(operator.add, range(n+1))
...
>>> for i in range(10):
... print sumUpTo(i), 'vs', i*(i+1) / 2
...
0 vs 0
1 vs 1
3 vs 3
6 vs 6
10 vs 10
15 vs 15
21 vs 21
28 vs 28
36 vs 36
45 vs 45
###############################################
> If you do end up having to concatenate a lot of strings together, use the
> join() method of lists instead.
I should clarify this. I meant to say we should use the string method of
join() on lists. For example, if we didn't have file1.read(), we could
still do:
###
ans = ''.join(file1.readlines())
###
which takes the lines of the file and joins them altogether at once.
Good luck!
More information about the Tutor
mailing list