CodeWars打卡(08)

2018-07-05  本文已影响0人  影醉阏轩窗

Details:

#Reverse or rotate?

The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) 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 that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string.

If
    sz is <= 0 or if str is empty return ""
    sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return "".

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) --> "" 
revrot("563000655734469485", 4) --> "0365065073456944"

中文大概含义:

输入是一个数字字符串str。 将字符串剪切为大小为sz的块(这里的块是初始字符串的子串)(如果它的大小小于sz,则忽略最后一个块)。 如果一个块表示一个整数,例如其数字的多维数据集的总和可以被2整除,则反转该块; 否则将其向左旋转一个位置。 将这些修改后的块放在一起并将结果作为字符串返回。

我自己的代码如下:

def revrot(string, sz):
    """
    :param string:
    :param sz:
    :return:
    """
    List = [int(i) for i in list(string)]
    if len(List)==0 or sz==0:
        return ''
    div,mod = divmod(len(List),int(sz))
    result = {}
    keep = []
    for i in range(div):
        result[i] = List[i*sz:sz*(i+1)]
        result[i] = reversed(result[i]) if sum(result[i]) % 2==0 else result[i][1:]+[result[i][0]]
        '''
        if sum(result[i]) % 2==0:
            result[i] = reversed(result[i])
        else:
            result[i] = result[i][1:]+[result[i][0]]
        '''
        keep+=result[i]
    return ''.join(map(str,keep))

第一名代码:

def revrot(s, n, res=""):
    if not s or n < 1 or n > len(s):
        return ""
    
    while len(s) >= n:
        group = s[:n]
        if sum([int(d)**3 for d in group]) % 2 == 0:
            res += group[::-1]
        else:
            res += group[1:] + group[0]
        s = s[n:]
    
    return res

第二名代码:

def revrot(strng, sz):
    func = lambda x : x[1:] + x[0] if sum(int(i) for i in x) % 2 else x[::-1]
    return "" if sz <= 0 or sz > len(strng) else "".join(func(strng[i:i+sz]) for i in xrange(0, len(strng) - sz + 1, sz))
  1. 我的方法和第一名思路类似.
  2. 第一名的思路比我的清晰,我写的代码显得冗余,他使用了递归的思想,s=s[n:],意思很简单,但是如果用i去控制就显得很乱.值的学习的代码编写风格.
  3. 第二名代码有点问题,感觉他喂了代码行数变少刻意把很多数据写在一起了,严谨性值的学习,但是可读性太差了.
上一篇下一篇

猜你喜欢

热点阅读