Open azhai opened 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
不先用最大公约数求出外循环多少次,直接一个循环