Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
azhai opened this issue Jul 14, 2015 · 0 comments
Open

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

azhai opened this issue Jul 14, 2015 · 0 comments

Comments

@azhai
Copy link

azhai commented Jul 14, 2015

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

    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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant