简体   繁体   中英

Effectively remove everything except repeating end characters

What effective way is there to just leave the repeating end characters in a given number? (like reversed strip)(I couldn't find a fast method)

For example number='184950273400000' print((number).strip('0')) The outcome is 1849502734

But I was wondering how to instead of striping the 0s, effectively strip everything before the 0s. So the outcome would be 00000.

And in this case len(number) would == 5

I was wondering if there was something like reversed strip because I am trying to find the length of repeating end numbers.

You can use the reversed function to efficiently generate the string as a sequence in reverse order, so that you can use itertools.takewhile to output only the leading characters that are equal to '0' with '0' 's equality method, and then join the characters for output:

from itertools import takewhile
''.join(takewhile('0'.__eq__, reversed(number)))

This avoids iterating through any (potentially very long) part of the string leading to the trailing zeroes.

Here's the performant option. It only requires scanning the last digits.

def count_zeros(number):

    number=str(number)
    i=0
    for digit in reversed(number): #count backwards
        if digit!=number[-1]:
            return i
        else:
            i+=1

You can use regex:

import re

number='184950273400000'

re.search(r'0+$', number).group(0)
# 00000

You can also use the function takewhile() with a reversed string:

from itertools import takewhile

''.join(takewhile(lambda x: x == '0', number[::-1]))
# 00000

Finally you can use the length of the stripped string:

number[len(number.rstrip('0')):]
# 00000

If wanting to find the number of trailing zeros of a factorial as suggested by the comments, it might not always be possible to compute the factorial to use the other methods suggested. Instead, you only need to compute the factors of 5 that go into the number. This won't be faster than the other methods if a number is already provided, but is much faster than computing the factorial.

def count_zero(n):
    return sum([n//5**(i+1) for i in range(int(math.log(n, 5)))])

If you want to process it from a string (instead of the math approach), you would probably get the best performance by using only iterators:

from itertools import takewhile
countTrailingZeroes = sum( 1 for _ in takewhile(lambda c:c=="0",reversed(number)) )

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