简体   繁体   中英

Most computationally efficient way to remove last word from string if it's less than x number of characters?

My current solution is for x=3

a = "first one is"
b = "the second forever"

def fun(input):
  if input.split()[-1] < 3:
    return ' '.join( input.split()[0:-1])
  else:
    return input

fun(a)

"first one"

fun(b)

"The second forever"

Is there something more computationally efficient?

You can try this:

def fun2(input):
  s = input.rsplit(' ', 1)
  return s[0] if len(s[1]) < 3 else input

Time profiling using %timeit :

In [25]: def fun(input):
    ...:   if len(input.split()[-1]) < 3:
    ...:     return ' '.join( input.split()[0:-1])
    ...:   else:
    ...:     return input
    ...:

In [26]: def fun2(input):
    ...:   s = input.rsplit(' ', 1)
    ...:   return s[0] if len(s[1]) < 3 else input
    ...:

In [28]: fun(a), fun2(a)
Out[28]: ('first one', 'first one')

In [29]: %timeit fun(a)
433 ns ± 0.759 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

In [30]: %timeit fun2(a)
222 ns ± 1.04 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)

fun2 is faster because rsplit is slightly faster and it avoids redundant computation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM