Array of Chars to String

Michael Spencer mahs at telcopartners.com
Tue Apr 19 19:28:07 EDT 2005


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:

  >>> 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'

  >>> def func_join(s, letters):
  ...     return "".join(letter for letter in s if letter in set(letters))
  ...
  >>> def func_join1(s, letters):
  ...     return "".join(letter for letter in s if letter in letters)


  >>> for multiplier in (1, 10, 100, 1000, 10000):
  ...     print "List multiplier: %s" % multiplier
  ...     print shell.timefunc(func_join, "Bob Carol Ted Alice" * multiplier, 'adB')
  ...     print shell.timefunc(func_join1, "Bob Carol Ted Alice" * multiplier, 
'adB')
  ...     print shell.timefunc(some_func, "Bob Carol Ted Alice" * multiplier, 'adB')
  ...
  List multiplier: 1
  func_join(...)  11267 iterations, 44.38usec per call
  func_join1(...)  38371 iterations, 13.03usec per call
  some_func(...)  1230 iterations, 406.69usec per call
  List multiplier: 10
  func_join(...)  1381 iterations, 362.40usec per call
  func_join1(...)  7984 iterations, 62.63usec per call
  some_func(...)  1226 iterations, 407.94usec per call
  List multiplier: 100
  func_join(...)  140 iterations, 3.59msec per call
  func_join1(...)  873 iterations, 0.57msec per call
  some_func(...)  1184 iterations, 422.42usec per call
  List multiplier: 1000
  func_join(...)  15 iterations, 35.50msec per call
  func_join1(...)  90 iterations, 5.57msec per call
  some_func(...)  949 iterations, 0.53msec per call
  List multiplier: 10000
  func_join(...)  2 iterations, 356.53msec per call
  func_join1(...)  9 iterations, 55.59msec per call
  some_func(...)  313 iterations, 1.60msec per call
  >>>

Michael




More information about the Python-list mailing list