Michael Spencer wrote:
Bengt Richter wrote:
 > I think this will be worth it if your string to modify is _very_ long:


>>> def some_func(s, letters, table=''.join([chr(i) for i in xrange(256)])):
... return s.translate(table,
... ''.join([chr(i) for i in xrange(256) if chr(i) not in letters]))
...
>>> some_func("Bob Carol Ted Alice", 'adB')
'Bad'


According to my measurements the string doesn't have to be long at all before your method is faster - cool use of str.translate:

...and here's a version that appears faster than "".join across all lengths of strings:
>>> import string
>>> def some_func1(s, letters, table=string.maketrans("","")):
... return s.translate(table, table.translate(table, letters))
...
>>> some_func1("Bob Carol Ted Alice", "adB")
'Bad'
>>>


Timings follow:

>>> def some_func(s, letters, table=''.join([chr(i) for i in xrange(256)])):
... return s.translate(table,
... ''.join([chr(i) for i in xrange(256) if chr(i) not in letters]))
...
>>> def some_func1(s, letters, table=string.maketrans("","")):
... return s.translate(table, table.translate(table, letters))
...
>>> for multiplier in (1, 10, 100, 1000, 10000):
... print "List multiplier: %s" % multiplier
... print shell.timefunc(some_func, "Bob Carol Ted Alice" * multiplier, 'adB')
... print shell.timefunc(some_func1, "Bob Carol Ted Alice" * multiplier, 'adB')
...
List multiplier: 1
some_func(...) 1224 iterations, 408.57usec per call
some_func1(...) 61035 iterations, 8.19usec per call
List multiplier: 10
some_func(...) 1223 iterations, 408.95usec per call
some_func1(...) 54420 iterations, 9.19usec per call
List multiplier: 100
some_func(...) 1190 iterations, 420.48usec per call
some_func1(...) 23436 iterations, 21.34usec per call
List multiplier: 1000
some_func(...) 951 iterations, 0.53msec per call
some_func1(...) 3870 iterations, 129.21usec per call
List multiplier: 10000
some_func(...) 309 iterations, 1.62msec per call
some_func1(...) 417 iterations, 1.20msec per call
>>>


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

Reply via email to