美文网首页
Codility lesson 2(2): CyclicRota

Codility lesson 2(2): CyclicRota

作者: 波洛的汽车电子世界 | 来源:发表于2019-08-03 17:09 被阅读0次
Task description
An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).

The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

Write a function:

def solution(A, K)

that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

For example, given

    A = [3, 8, 9, 7, 6]
    K = 3
the function should return [9, 7, 6, 3, 8]. Three rotations were made:

    [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
    [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
    [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given

    A = [0, 0, 0]
    K = 1
the function should return [0, 0, 0]

Given

    A = [1, 2, 3, 4]
    K = 4
the function should return [1, 2, 3, 4]

Assume that:

N and K are integers within the range [0..100];
each element of array A is an integer within the range [−1,000..1,000].
In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

不要忘记讨论array为空的情况

def solution(A, K):
    # write your code in Python 3.6
    if(len(A) ==0): # see if the ARRAY is empty
        return A
    else:
        m = K%len(A) 
        B = A[len(A)-m:]+A[:len(A)-m]
        return B

相关文章

  • Codility lesson 2(2): CyclicRota

    不要忘记讨论array为空的情况

  • Codility lesson 2: Odd occurrenc

    method 3: 用异或来解决A xor A = 0A xor 0 = A异或List中所有的元素,看最后留下的...

  • Lesson 2

    学习内容: 课本 P9Lesson2, 学习句子拆分,将句子分成独立的单词 复习要求: 1.在家与孩子一起分别念学...

  • Lesson 2

    SCRIPT The first thing I do when I get to work each morni...

  • lesson 2~

  • Lesson 2

    课程二最终完成了计算机的编写,下图是计算器的程序: 首先看下按下enter键做了什么,构造了这么一个无参数的函数,...

  • Lesson 2

    Breakfast or lunch? 早餐还是午餐? 参考译文: 那是个星期天,而在星期天我是从来不早起的,有时...

  • Lesson 2

    每天5至10分钟,陪宝宝玩英语,在游戏中轻松学会说英语。 简要:捡起什么东西,放下什么东西。 pick up th...

  • LESSON 2

    90年代的美国,许多富豪在25年之后变得一无所有,甚至自杀;穷人中彩票之后暴富,继而又成为穷人;年薪百万的运动员在...

  • Unit 2 Lesson 2

    课程内容: 学习Unit 2 Chant: “Pancake Time!” 学习Unit 2 Graded rea...

网友评论

      本文标题:Codility lesson 2(2): CyclicRota

      本文链接:https://www.haomeiwen.com/subject/qrojdctx.html