julycoding / The-Art-Of-Programming-By-July-2nd

本项目曾冲到全球第一,干货集锦见本页面最底部,另完整精致的纸质版《编程之法:面试和算法心得》已在京东/当当上销售
21.34k stars 7.1k forks source link

1.1:字符的移动.py 思路四 #423

Open azhai opened 9 years ago

azhai commented 9 years ago

不先用最大公约数求出外循环多少次,直接一个循环

    def rotate(word, offset = 3):
        """ 
        将字符列表的前n位移到最后
        一共需要gcd(offset, size)轮,offset趟
        """
        if isinstance(word, basestring):
            word = [x for x in word]  #字符串转为字符列表
        size = len(word)
        assert offset < size
        i = p1 = 0
        temp = word[i]
        times = offset #总共n趟
        while times > 0:
            p2 = p1
            p1 += offset
            if p1 >= size: #越界
                p1 %= size
                times -= 1 #完成一趟
            if p1 == i: #回到本轮起点
                word[p2] = temp
                i = p1 = i + 1 #下一轮
                temp = word[i]
            else:
                word[p2] = word[p1]
        return word