Left Rotation on an Array Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How do I check if an array includes an object in JavaScript?How do you split a list into evenly sized chunks?How can you profile a Python script?How do I sort a dictionary by value?“Least Astonishment” and the Mutable Default ArgumentHow to define a two-dimensional array in PythonImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow to find time complexity of an algorithmHow to pair socks from a pile efficiently?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?

Generate an RGB colour grid

How to write the following sign?

Why does the remaining Rebel fleet at the end of Rogue One seem dramatically larger than the one in A New Hope?

What is this clumpy 20-30cm high yellow-flowered plant?

Effects on objects due to a brief relocation of massive amounts of mass

What is a fractional matching?

Why wasn't DOSKEY integrated with COMMAND.COM?

Using audio cues to encourage good posture

Did Deadpool rescue all of the X-Force?

Can a new player join a group only when a new campaign starts?

Is a ledger board required if the side of my house is wood?

What is the appropriate index architecture when forced to implement IsDeleted (soft deletes)?

Question about debouncing - delay of state change

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

ArcGIS Pro Python arcpy.CreatePersonalGDB_management

How come Sam didn't become Lord of Horn Hill?

How does light 'choose' between wave and particle behaviour?

The code below, is it ill-formed NDR or is it well formed?

Putting class ranking in CV, but against dept guidelines

What initially awakened the Balrog?

Can the Great Weapon Master feat's damage bonus and accuracy penalty apply to attacks from the Spiritual Weapon spell?

Morning, Afternoon, Night Kanji

How to compare two different files line by line in unix?

Illegal assignment from sObject to Id



Left Rotation on an Array



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How do I check if an array includes an object in JavaScript?How do you split a list into evenly sized chunks?How can you profile a Python script?How do I sort a dictionary by value?“Least Astonishment” and the Mutable Default ArgumentHow to define a two-dimensional array in PythonImage Processing: Algorithm Improvement for 'Coca-Cola Can' RecognitionHow to find time complexity of an algorithmHow to pair socks from a pile efficiently?Why is “1000000000000000 in range(1000000000000001)” so fast in Python 3?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








5















I have a question where I need to rotate an array left k times.



i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]



So, my code is:



def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t

return a


where n = length of the array.



I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1.



What is wrong with my solution?










share|improve this question






















  • This problem almost surely can be easier solved with slicing.

    – DYZ
    Mar 24 '18 at 7:11











  • Consider the case when i==0 and k==1 (the shift of the first element by one position to the right). a[i] = a[(i+n-1+k)%n] becomes a[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]. Is this right?

    – DYZ
    Mar 24 '18 at 7:13











  • Have you tried printing the value of (i+n-1+k)%n so as to verify that the elements that get swapped are the ones you expect to get swapped? Have you tried simulating the process with physical objects, to verify that swapping things in this manner produces the desired result?

    – Karl Knechtel
    Mar 24 '18 at 7:58

















5















I have a question where I need to rotate an array left k times.



i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]



So, my code is:



def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t

return a


where n = length of the array.



I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1.



What is wrong with my solution?










share|improve this question






















  • This problem almost surely can be easier solved with slicing.

    – DYZ
    Mar 24 '18 at 7:11











  • Consider the case when i==0 and k==1 (the shift of the first element by one position to the right). a[i] = a[(i+n-1+k)%n] becomes a[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]. Is this right?

    – DYZ
    Mar 24 '18 at 7:13











  • Have you tried printing the value of (i+n-1+k)%n so as to verify that the elements that get swapped are the ones you expect to get swapped? Have you tried simulating the process with physical objects, to verify that swapping things in this manner produces the desired result?

    – Karl Knechtel
    Mar 24 '18 at 7:58













5












5








5








I have a question where I need to rotate an array left k times.



i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]



So, my code is:



def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t

return a


where n = length of the array.



I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1.



What is wrong with my solution?










share|improve this question














I have a question where I need to rotate an array left k times.



i.e. if k = 2, [1, 2, 3, 4, 5] . -> [3, 4, 5, 1, 2]



So, my code is:



def array_left_rotation(a, n, k):
for i in range(n):
t = a[i]
a[i] = a[(i+n-1+k)%n]
a[(i+n-1+k)%n] = t

return a


where n = length of the array.



I think the problem is a mapping problem, a[0] -> a[n-1] if k = 1.



What is wrong with my solution?







python algorithm data-structures






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 '18 at 7:08









mourinhomourinho

300412




300412












  • This problem almost surely can be easier solved with slicing.

    – DYZ
    Mar 24 '18 at 7:11











  • Consider the case when i==0 and k==1 (the shift of the first element by one position to the right). a[i] = a[(i+n-1+k)%n] becomes a[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]. Is this right?

    – DYZ
    Mar 24 '18 at 7:13











  • Have you tried printing the value of (i+n-1+k)%n so as to verify that the elements that get swapped are the ones you expect to get swapped? Have you tried simulating the process with physical objects, to verify that swapping things in this manner produces the desired result?

    – Karl Knechtel
    Mar 24 '18 at 7:58

















  • This problem almost surely can be easier solved with slicing.

    – DYZ
    Mar 24 '18 at 7:11











  • Consider the case when i==0 and k==1 (the shift of the first element by one position to the right). a[i] = a[(i+n-1+k)%n] becomes a[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]. Is this right?

    – DYZ
    Mar 24 '18 at 7:13











  • Have you tried printing the value of (i+n-1+k)%n so as to verify that the elements that get swapped are the ones you expect to get swapped? Have you tried simulating the process with physical objects, to verify that swapping things in this manner produces the desired result?

    – Karl Knechtel
    Mar 24 '18 at 7:58
















This problem almost surely can be easier solved with slicing.

– DYZ
Mar 24 '18 at 7:11





This problem almost surely can be easier solved with slicing.

– DYZ
Mar 24 '18 at 7:11













Consider the case when i==0 and k==1 (the shift of the first element by one position to the right). a[i] = a[(i+n-1+k)%n] becomes a[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]. Is this right?

– DYZ
Mar 24 '18 at 7:13





Consider the case when i==0 and k==1 (the shift of the first element by one position to the right). a[i] = a[(i+n-1+k)%n] becomes a[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]. Is this right?

– DYZ
Mar 24 '18 at 7:13













Have you tried printing the value of (i+n-1+k)%n so as to verify that the elements that get swapped are the ones you expect to get swapped? Have you tried simulating the process with physical objects, to verify that swapping things in this manner produces the desired result?

– Karl Knechtel
Mar 24 '18 at 7:58





Have you tried printing the value of (i+n-1+k)%n so as to verify that the elements that get swapped are the ones you expect to get swapped? Have you tried simulating the process with physical objects, to verify that swapping things in this manner produces the desired result?

– Karl Knechtel
Mar 24 '18 at 7:58












7 Answers
7






active

oldest

votes


















5














Another way to do this with the help of indexing is shown below..



def rotate(l, n):
return l[n:] + l[:n]

print(rotate([1, 2, 3, 4, 5], 2))

#output : [3, 4, 5, 1, 2]


This will only return the original list if n is outside the range [-len(l), len(l)]. To make it work for all values of n, use:



def rotate(l, n):
return l[-n % len(l):] + l[:-n % len(l)]





share|improve this answer
































    2














    One way you can do is by using collections.deque



    from collections import deque
    k = 2
    l = [1, 2, 3, 4, 5]
    dl = deque(l)
    dl.rotate(k+1)
    list(dl)
    #[3, 4, 5, 1, 2]





    share|improve this answer























    • Just a side note: Although your solution returns the specific result required in the question, according to the python doc deque.rotate() has to be called with a negative argument in order to rotate the items to left. The Left rotation was also part of the required behavior in the question.

      – 0x51ba
      Mar 24 '18 at 13:51












    • btw. rotating [1,2,3,4] with your code returns [2, 3, 4, 1] which is not the behavior asked for in the question. changing dl.rotate(k+1) into dl.rotate(-1*k) should fix your code

      – 0x51ba
      Mar 24 '18 at 14:10



















    0














    This solution requires constant extra memory, and runs in O(nk).



    If the array has zero length, or there are zero rotations, skip the loop and return arr.



    For every rotation we store the first element, then shift every other element to the left, finally placing the first element at the back of the list. We save some work for large values of k by recognizing that every rotation after the nth is a repeat solution -> k % n.



    def array_left_rotation(arr, n, k):
    for _ in range(0 if 0 in [n, k] else k % n):
    temp = arr[0]
    for idx in range(n - 1):
    arr[idx] = arr[idx + 1]
    arr[-1] = temp
    return arr





    share|improve this answer

























    • generally in Python you try to use the tools provided by the standard lib. This looks like an attempt to write low-level code in Python. It's rarely a good idea: It is hard to guess the memory requirement of an algorithm in Python (much harder than C), and I am not sure OP cares that much about "constant extra memory". Also, a consequence is that readability is low, which is considered important in Python.

      – Cédric Van Rompay
      Mar 24 '18 at 8:44











    • This question is tagged data structures and algorithms, so I provided time and space complexity. If asked this question in an interview, space and runtime trade offs need to be addressed. This algorithm is O(1) time and runs in O(nk). The question was not “give me the most pythonic”. If you can’t read this, you need more practice.

      – RYS
      Mar 24 '18 at 8:57


















    0














    N, d = map(int, input().split()) #taking length N and no. of rotations d
    a = list(input().split()) #taking input array as list
    r = a[d % N : N] + a[0 : d % N] #rotating the array(list)
    print(r)

    5 2 #giving N,D as input
    1 2 3 4 5 #giving input array
    ['3', '4', '5', '1', '2'] #output





    share|improve this answer






























      0














      def leftRotation(a, d, n):
      i=0
      while i < n:
      print (a[(i+d)%n], end = ' ')
      i+=1
      return i

      if __name__ == '__main__':
      a =[1, 2, 3, 4, 5, 6, 7]
      d = 4
      n = 7 or len(a)
      leftRotation(a, d, n)


      This is how I solved my hackerrank left rotation challenge






      share|improve this answer
































        -1














        def rotate_left3(nums):
        temp=[]
        for i in range(len(nums)-1):
        temp=nums[i]
        nums[i]=nums[i+1]
        nums[i+1]=temp

        return nums





        share|improve this answer























        • An ingenious solution! Please fix your indentation. Why is the function called rotate_left3? How would you deal with OP wanting to rotate the list k times?

          – Rob Bricheno
          Nov 29 '18 at 15:21











        • Could you give an explanation of why the code works?

          – Joe
          Nov 29 '18 at 21:25


















        -2














        This is how I did it:



        def rotate_left3(nums):
        return [ nums[1] , nums[2] , nums[0] ]


        It worked perfect 100%, but if you add more sums, you'd have to add its just set for the 3 that the problem specified.






        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49462195%2fleft-rotation-on-an-array%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          7 Answers
          7






          active

          oldest

          votes








          7 Answers
          7






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          5














          Another way to do this with the help of indexing is shown below..



          def rotate(l, n):
          return l[n:] + l[:n]

          print(rotate([1, 2, 3, 4, 5], 2))

          #output : [3, 4, 5, 1, 2]


          This will only return the original list if n is outside the range [-len(l), len(l)]. To make it work for all values of n, use:



          def rotate(l, n):
          return l[-n % len(l):] + l[:-n % len(l)]





          share|improve this answer





























            5














            Another way to do this with the help of indexing is shown below..



            def rotate(l, n):
            return l[n:] + l[:n]

            print(rotate([1, 2, 3, 4, 5], 2))

            #output : [3, 4, 5, 1, 2]


            This will only return the original list if n is outside the range [-len(l), len(l)]. To make it work for all values of n, use:



            def rotate(l, n):
            return l[-n % len(l):] + l[:-n % len(l)]





            share|improve this answer



























              5












              5








              5







              Another way to do this with the help of indexing is shown below..



              def rotate(l, n):
              return l[n:] + l[:n]

              print(rotate([1, 2, 3, 4, 5], 2))

              #output : [3, 4, 5, 1, 2]


              This will only return the original list if n is outside the range [-len(l), len(l)]. To make it work for all values of n, use:



              def rotate(l, n):
              return l[-n % len(l):] + l[:-n % len(l)]





              share|improve this answer















              Another way to do this with the help of indexing is shown below..



              def rotate(l, n):
              return l[n:] + l[:n]

              print(rotate([1, 2, 3, 4, 5], 2))

              #output : [3, 4, 5, 1, 2]


              This will only return the original list if n is outside the range [-len(l), len(l)]. To make it work for all values of n, use:



              def rotate(l, n):
              return l[-n % len(l):] + l[:-n % len(l)]






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 16 '18 at 4:25

























              answered Mar 24 '18 at 7:36









              Sreeram TPSreeram TP

              3,67131442




              3,67131442























                  2














                  One way you can do is by using collections.deque



                  from collections import deque
                  k = 2
                  l = [1, 2, 3, 4, 5]
                  dl = deque(l)
                  dl.rotate(k+1)
                  list(dl)
                  #[3, 4, 5, 1, 2]





                  share|improve this answer























                  • Just a side note: Although your solution returns the specific result required in the question, according to the python doc deque.rotate() has to be called with a negative argument in order to rotate the items to left. The Left rotation was also part of the required behavior in the question.

                    – 0x51ba
                    Mar 24 '18 at 13:51












                  • btw. rotating [1,2,3,4] with your code returns [2, 3, 4, 1] which is not the behavior asked for in the question. changing dl.rotate(k+1) into dl.rotate(-1*k) should fix your code

                    – 0x51ba
                    Mar 24 '18 at 14:10
















                  2














                  One way you can do is by using collections.deque



                  from collections import deque
                  k = 2
                  l = [1, 2, 3, 4, 5]
                  dl = deque(l)
                  dl.rotate(k+1)
                  list(dl)
                  #[3, 4, 5, 1, 2]





                  share|improve this answer























                  • Just a side note: Although your solution returns the specific result required in the question, according to the python doc deque.rotate() has to be called with a negative argument in order to rotate the items to left. The Left rotation was also part of the required behavior in the question.

                    – 0x51ba
                    Mar 24 '18 at 13:51












                  • btw. rotating [1,2,3,4] with your code returns [2, 3, 4, 1] which is not the behavior asked for in the question. changing dl.rotate(k+1) into dl.rotate(-1*k) should fix your code

                    – 0x51ba
                    Mar 24 '18 at 14:10














                  2












                  2








                  2







                  One way you can do is by using collections.deque



                  from collections import deque
                  k = 2
                  l = [1, 2, 3, 4, 5]
                  dl = deque(l)
                  dl.rotate(k+1)
                  list(dl)
                  #[3, 4, 5, 1, 2]





                  share|improve this answer













                  One way you can do is by using collections.deque



                  from collections import deque
                  k = 2
                  l = [1, 2, 3, 4, 5]
                  dl = deque(l)
                  dl.rotate(k+1)
                  list(dl)
                  #[3, 4, 5, 1, 2]






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 24 '18 at 7:28









                  TranshumanTranshuman

                  2,8261412




                  2,8261412












                  • Just a side note: Although your solution returns the specific result required in the question, according to the python doc deque.rotate() has to be called with a negative argument in order to rotate the items to left. The Left rotation was also part of the required behavior in the question.

                    – 0x51ba
                    Mar 24 '18 at 13:51












                  • btw. rotating [1,2,3,4] with your code returns [2, 3, 4, 1] which is not the behavior asked for in the question. changing dl.rotate(k+1) into dl.rotate(-1*k) should fix your code

                    – 0x51ba
                    Mar 24 '18 at 14:10


















                  • Just a side note: Although your solution returns the specific result required in the question, according to the python doc deque.rotate() has to be called with a negative argument in order to rotate the items to left. The Left rotation was also part of the required behavior in the question.

                    – 0x51ba
                    Mar 24 '18 at 13:51












                  • btw. rotating [1,2,3,4] with your code returns [2, 3, 4, 1] which is not the behavior asked for in the question. changing dl.rotate(k+1) into dl.rotate(-1*k) should fix your code

                    – 0x51ba
                    Mar 24 '18 at 14:10

















                  Just a side note: Although your solution returns the specific result required in the question, according to the python doc deque.rotate() has to be called with a negative argument in order to rotate the items to left. The Left rotation was also part of the required behavior in the question.

                  – 0x51ba
                  Mar 24 '18 at 13:51






                  Just a side note: Although your solution returns the specific result required in the question, according to the python doc deque.rotate() has to be called with a negative argument in order to rotate the items to left. The Left rotation was also part of the required behavior in the question.

                  – 0x51ba
                  Mar 24 '18 at 13:51














                  btw. rotating [1,2,3,4] with your code returns [2, 3, 4, 1] which is not the behavior asked for in the question. changing dl.rotate(k+1) into dl.rotate(-1*k) should fix your code

                  – 0x51ba
                  Mar 24 '18 at 14:10






                  btw. rotating [1,2,3,4] with your code returns [2, 3, 4, 1] which is not the behavior asked for in the question. changing dl.rotate(k+1) into dl.rotate(-1*k) should fix your code

                  – 0x51ba
                  Mar 24 '18 at 14:10












                  0














                  This solution requires constant extra memory, and runs in O(nk).



                  If the array has zero length, or there are zero rotations, skip the loop and return arr.



                  For every rotation we store the first element, then shift every other element to the left, finally placing the first element at the back of the list. We save some work for large values of k by recognizing that every rotation after the nth is a repeat solution -> k % n.



                  def array_left_rotation(arr, n, k):
                  for _ in range(0 if 0 in [n, k] else k % n):
                  temp = arr[0]
                  for idx in range(n - 1):
                  arr[idx] = arr[idx + 1]
                  arr[-1] = temp
                  return arr





                  share|improve this answer

























                  • generally in Python you try to use the tools provided by the standard lib. This looks like an attempt to write low-level code in Python. It's rarely a good idea: It is hard to guess the memory requirement of an algorithm in Python (much harder than C), and I am not sure OP cares that much about "constant extra memory". Also, a consequence is that readability is low, which is considered important in Python.

                    – Cédric Van Rompay
                    Mar 24 '18 at 8:44











                  • This question is tagged data structures and algorithms, so I provided time and space complexity. If asked this question in an interview, space and runtime trade offs need to be addressed. This algorithm is O(1) time and runs in O(nk). The question was not “give me the most pythonic”. If you can’t read this, you need more practice.

                    – RYS
                    Mar 24 '18 at 8:57















                  0














                  This solution requires constant extra memory, and runs in O(nk).



                  If the array has zero length, or there are zero rotations, skip the loop and return arr.



                  For every rotation we store the first element, then shift every other element to the left, finally placing the first element at the back of the list. We save some work for large values of k by recognizing that every rotation after the nth is a repeat solution -> k % n.



                  def array_left_rotation(arr, n, k):
                  for _ in range(0 if 0 in [n, k] else k % n):
                  temp = arr[0]
                  for idx in range(n - 1):
                  arr[idx] = arr[idx + 1]
                  arr[-1] = temp
                  return arr





                  share|improve this answer

























                  • generally in Python you try to use the tools provided by the standard lib. This looks like an attempt to write low-level code in Python. It's rarely a good idea: It is hard to guess the memory requirement of an algorithm in Python (much harder than C), and I am not sure OP cares that much about "constant extra memory". Also, a consequence is that readability is low, which is considered important in Python.

                    – Cédric Van Rompay
                    Mar 24 '18 at 8:44











                  • This question is tagged data structures and algorithms, so I provided time and space complexity. If asked this question in an interview, space and runtime trade offs need to be addressed. This algorithm is O(1) time and runs in O(nk). The question was not “give me the most pythonic”. If you can’t read this, you need more practice.

                    – RYS
                    Mar 24 '18 at 8:57













                  0












                  0








                  0







                  This solution requires constant extra memory, and runs in O(nk).



                  If the array has zero length, or there are zero rotations, skip the loop and return arr.



                  For every rotation we store the first element, then shift every other element to the left, finally placing the first element at the back of the list. We save some work for large values of k by recognizing that every rotation after the nth is a repeat solution -> k % n.



                  def array_left_rotation(arr, n, k):
                  for _ in range(0 if 0 in [n, k] else k % n):
                  temp = arr[0]
                  for idx in range(n - 1):
                  arr[idx] = arr[idx + 1]
                  arr[-1] = temp
                  return arr





                  share|improve this answer















                  This solution requires constant extra memory, and runs in O(nk).



                  If the array has zero length, or there are zero rotations, skip the loop and return arr.



                  For every rotation we store the first element, then shift every other element to the left, finally placing the first element at the back of the list. We save some work for large values of k by recognizing that every rotation after the nth is a repeat solution -> k % n.



                  def array_left_rotation(arr, n, k):
                  for _ in range(0 if 0 in [n, k] else k % n):
                  temp = arr[0]
                  for idx in range(n - 1):
                  arr[idx] = arr[idx + 1]
                  arr[-1] = temp
                  return arr






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 24 '18 at 9:05

























                  answered Mar 24 '18 at 7:18









                  RYSRYS

                  259215




                  259215












                  • generally in Python you try to use the tools provided by the standard lib. This looks like an attempt to write low-level code in Python. It's rarely a good idea: It is hard to guess the memory requirement of an algorithm in Python (much harder than C), and I am not sure OP cares that much about "constant extra memory". Also, a consequence is that readability is low, which is considered important in Python.

                    – Cédric Van Rompay
                    Mar 24 '18 at 8:44











                  • This question is tagged data structures and algorithms, so I provided time and space complexity. If asked this question in an interview, space and runtime trade offs need to be addressed. This algorithm is O(1) time and runs in O(nk). The question was not “give me the most pythonic”. If you can’t read this, you need more practice.

                    – RYS
                    Mar 24 '18 at 8:57

















                  • generally in Python you try to use the tools provided by the standard lib. This looks like an attempt to write low-level code in Python. It's rarely a good idea: It is hard to guess the memory requirement of an algorithm in Python (much harder than C), and I am not sure OP cares that much about "constant extra memory". Also, a consequence is that readability is low, which is considered important in Python.

                    – Cédric Van Rompay
                    Mar 24 '18 at 8:44











                  • This question is tagged data structures and algorithms, so I provided time and space complexity. If asked this question in an interview, space and runtime trade offs need to be addressed. This algorithm is O(1) time and runs in O(nk). The question was not “give me the most pythonic”. If you can’t read this, you need more practice.

                    – RYS
                    Mar 24 '18 at 8:57
















                  generally in Python you try to use the tools provided by the standard lib. This looks like an attempt to write low-level code in Python. It's rarely a good idea: It is hard to guess the memory requirement of an algorithm in Python (much harder than C), and I am not sure OP cares that much about "constant extra memory". Also, a consequence is that readability is low, which is considered important in Python.

                  – Cédric Van Rompay
                  Mar 24 '18 at 8:44





                  generally in Python you try to use the tools provided by the standard lib. This looks like an attempt to write low-level code in Python. It's rarely a good idea: It is hard to guess the memory requirement of an algorithm in Python (much harder than C), and I am not sure OP cares that much about "constant extra memory". Also, a consequence is that readability is low, which is considered important in Python.

                  – Cédric Van Rompay
                  Mar 24 '18 at 8:44













                  This question is tagged data structures and algorithms, so I provided time and space complexity. If asked this question in an interview, space and runtime trade offs need to be addressed. This algorithm is O(1) time and runs in O(nk). The question was not “give me the most pythonic”. If you can’t read this, you need more practice.

                  – RYS
                  Mar 24 '18 at 8:57





                  This question is tagged data structures and algorithms, so I provided time and space complexity. If asked this question in an interview, space and runtime trade offs need to be addressed. This algorithm is O(1) time and runs in O(nk). The question was not “give me the most pythonic”. If you can’t read this, you need more practice.

                  – RYS
                  Mar 24 '18 at 8:57











                  0














                  N, d = map(int, input().split()) #taking length N and no. of rotations d
                  a = list(input().split()) #taking input array as list
                  r = a[d % N : N] + a[0 : d % N] #rotating the array(list)
                  print(r)

                  5 2 #giving N,D as input
                  1 2 3 4 5 #giving input array
                  ['3', '4', '5', '1', '2'] #output





                  share|improve this answer



























                    0














                    N, d = map(int, input().split()) #taking length N and no. of rotations d
                    a = list(input().split()) #taking input array as list
                    r = a[d % N : N] + a[0 : d % N] #rotating the array(list)
                    print(r)

                    5 2 #giving N,D as input
                    1 2 3 4 5 #giving input array
                    ['3', '4', '5', '1', '2'] #output





                    share|improve this answer

























                      0












                      0








                      0







                      N, d = map(int, input().split()) #taking length N and no. of rotations d
                      a = list(input().split()) #taking input array as list
                      r = a[d % N : N] + a[0 : d % N] #rotating the array(list)
                      print(r)

                      5 2 #giving N,D as input
                      1 2 3 4 5 #giving input array
                      ['3', '4', '5', '1', '2'] #output





                      share|improve this answer













                      N, d = map(int, input().split()) #taking length N and no. of rotations d
                      a = list(input().split()) #taking input array as list
                      r = a[d % N : N] + a[0 : d % N] #rotating the array(list)
                      print(r)

                      5 2 #giving N,D as input
                      1 2 3 4 5 #giving input array
                      ['3', '4', '5', '1', '2'] #output






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jun 22 '18 at 3:19









                      classicdude7classicdude7

                      88117




                      88117





















                          0














                          def leftRotation(a, d, n):
                          i=0
                          while i < n:
                          print (a[(i+d)%n], end = ' ')
                          i+=1
                          return i

                          if __name__ == '__main__':
                          a =[1, 2, 3, 4, 5, 6, 7]
                          d = 4
                          n = 7 or len(a)
                          leftRotation(a, d, n)


                          This is how I solved my hackerrank left rotation challenge






                          share|improve this answer





























                            0














                            def leftRotation(a, d, n):
                            i=0
                            while i < n:
                            print (a[(i+d)%n], end = ' ')
                            i+=1
                            return i

                            if __name__ == '__main__':
                            a =[1, 2, 3, 4, 5, 6, 7]
                            d = 4
                            n = 7 or len(a)
                            leftRotation(a, d, n)


                            This is how I solved my hackerrank left rotation challenge






                            share|improve this answer



























                              0












                              0








                              0







                              def leftRotation(a, d, n):
                              i=0
                              while i < n:
                              print (a[(i+d)%n], end = ' ')
                              i+=1
                              return i

                              if __name__ == '__main__':
                              a =[1, 2, 3, 4, 5, 6, 7]
                              d = 4
                              n = 7 or len(a)
                              leftRotation(a, d, n)


                              This is how I solved my hackerrank left rotation challenge






                              share|improve this answer















                              def leftRotation(a, d, n):
                              i=0
                              while i < n:
                              print (a[(i+d)%n], end = ' ')
                              i+=1
                              return i

                              if __name__ == '__main__':
                              a =[1, 2, 3, 4, 5, 6, 7]
                              d = 4
                              n = 7 or len(a)
                              leftRotation(a, d, n)


                              This is how I solved my hackerrank left rotation challenge







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 23 at 13:51

























                              answered Mar 22 at 10:12









                              Ken MbogoKen Mbogo

                              112




                              112





















                                  -1














                                  def rotate_left3(nums):
                                  temp=[]
                                  for i in range(len(nums)-1):
                                  temp=nums[i]
                                  nums[i]=nums[i+1]
                                  nums[i+1]=temp

                                  return nums





                                  share|improve this answer























                                  • An ingenious solution! Please fix your indentation. Why is the function called rotate_left3? How would you deal with OP wanting to rotate the list k times?

                                    – Rob Bricheno
                                    Nov 29 '18 at 15:21











                                  • Could you give an explanation of why the code works?

                                    – Joe
                                    Nov 29 '18 at 21:25















                                  -1














                                  def rotate_left3(nums):
                                  temp=[]
                                  for i in range(len(nums)-1):
                                  temp=nums[i]
                                  nums[i]=nums[i+1]
                                  nums[i+1]=temp

                                  return nums





                                  share|improve this answer























                                  • An ingenious solution! Please fix your indentation. Why is the function called rotate_left3? How would you deal with OP wanting to rotate the list k times?

                                    – Rob Bricheno
                                    Nov 29 '18 at 15:21











                                  • Could you give an explanation of why the code works?

                                    – Joe
                                    Nov 29 '18 at 21:25













                                  -1












                                  -1








                                  -1







                                  def rotate_left3(nums):
                                  temp=[]
                                  for i in range(len(nums)-1):
                                  temp=nums[i]
                                  nums[i]=nums[i+1]
                                  nums[i+1]=temp

                                  return nums





                                  share|improve this answer













                                  def rotate_left3(nums):
                                  temp=[]
                                  for i in range(len(nums)-1):
                                  temp=nums[i]
                                  nums[i]=nums[i+1]
                                  nums[i+1]=temp

                                  return nums






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 29 '18 at 11:16









                                  Harun OzHarun Oz

                                  15




                                  15












                                  • An ingenious solution! Please fix your indentation. Why is the function called rotate_left3? How would you deal with OP wanting to rotate the list k times?

                                    – Rob Bricheno
                                    Nov 29 '18 at 15:21











                                  • Could you give an explanation of why the code works?

                                    – Joe
                                    Nov 29 '18 at 21:25

















                                  • An ingenious solution! Please fix your indentation. Why is the function called rotate_left3? How would you deal with OP wanting to rotate the list k times?

                                    – Rob Bricheno
                                    Nov 29 '18 at 15:21











                                  • Could you give an explanation of why the code works?

                                    – Joe
                                    Nov 29 '18 at 21:25
















                                  An ingenious solution! Please fix your indentation. Why is the function called rotate_left3? How would you deal with OP wanting to rotate the list k times?

                                  – Rob Bricheno
                                  Nov 29 '18 at 15:21





                                  An ingenious solution! Please fix your indentation. Why is the function called rotate_left3? How would you deal with OP wanting to rotate the list k times?

                                  – Rob Bricheno
                                  Nov 29 '18 at 15:21













                                  Could you give an explanation of why the code works?

                                  – Joe
                                  Nov 29 '18 at 21:25





                                  Could you give an explanation of why the code works?

                                  – Joe
                                  Nov 29 '18 at 21:25











                                  -2














                                  This is how I did it:



                                  def rotate_left3(nums):
                                  return [ nums[1] , nums[2] , nums[0] ]


                                  It worked perfect 100%, but if you add more sums, you'd have to add its just set for the 3 that the problem specified.






                                  share|improve this answer





























                                    -2














                                    This is how I did it:



                                    def rotate_left3(nums):
                                    return [ nums[1] , nums[2] , nums[0] ]


                                    It worked perfect 100%, but if you add more sums, you'd have to add its just set for the 3 that the problem specified.






                                    share|improve this answer



























                                      -2












                                      -2








                                      -2







                                      This is how I did it:



                                      def rotate_left3(nums):
                                      return [ nums[1] , nums[2] , nums[0] ]


                                      It worked perfect 100%, but if you add more sums, you'd have to add its just set for the 3 that the problem specified.






                                      share|improve this answer















                                      This is how I did it:



                                      def rotate_left3(nums):
                                      return [ nums[1] , nums[2] , nums[0] ]


                                      It worked perfect 100%, but if you add more sums, you'd have to add its just set for the 3 that the problem specified.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Sep 2 '18 at 0:50









                                      Grant Miller

                                      6,697133458




                                      6,697133458










                                      answered Sep 1 '18 at 22:28









                                      kaponekapone

                                      1




                                      1



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49462195%2fleft-rotation-on-an-array%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현