习题12:Reverse or rotate?

是倒置呢还是错位

The input is a string str of digits. Cut the string into chunks of size sz (ignore the last chunk if its size is less than sz).

If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse it; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.
Examples:
revrot("123456987654", 6) --> "234561876549"
revrot("123456987653", 6) --> "234561356789"
revrot("66443875", 4) --> "44668753"
revrot("66443875", 8) --> "64438756"
revrot("664438769", 8) --> "67834466"
revrot("123456779", 8) --> "23456771"
revrot("", 8) --> ""
revrot("123456779", 0) --> ""
def revrot(strng, sz):
    # your code
    # slice to chunks e.g strng[(n-1)*sz: n*sz]
    if sz <= 0:
        return ''
    r = ''
    for k in range(len(strng)//sz):
        chunk = strng[k*sz:(k+1)*sz]
        if sum(int(i) for i in chunk)%2 == 0:
            chunk = chunk[::-1]
        else:
            chunk = chunk[1:]+chunk[0]
        r += chunk
    return r
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容