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;
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
add a comment |
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
This problem almost surely can be easier solved with slicing.
– DYZ
Mar 24 '18 at 7:11
Consider the case wheni==0
andk==1
(the shift of the first element by one position to the right).a[i] = a[(i+n-1+k)%n]
becomesa[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]
. Is this right?
– DYZ
Mar 24 '18 at 7:13
Have you triedprint
ing 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
add a comment |
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
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
python algorithm data-structures
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 wheni==0
andk==1
(the shift of the first element by one position to the right).a[i] = a[(i+n-1+k)%n]
becomesa[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]
. Is this right?
– DYZ
Mar 24 '18 at 7:13
Have you triedprint
ing 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
add a comment |
This problem almost surely can be easier solved with slicing.
– DYZ
Mar 24 '18 at 7:11
Consider the case wheni==0
andk==1
(the shift of the first element by one position to the right).a[i] = a[(i+n-1+k)%n]
becomesa[0] = a[(0+n-1+1)%n]=a[n%n]=a[0]
. Is this right?
– DYZ
Mar 24 '18 at 7:13
Have you triedprint
ing 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
print
ing 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
print
ing 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
add a comment |
7 Answers
7
active
oldest
votes
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)]
add a comment |
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]
Just a side note: Although your solution returns the specific result required in the question, according to the python docdeque.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. changingdl.rotate(k+1)
intodl.rotate(-1*k)
should fix your code
– 0x51ba
Mar 24 '18 at 14:10
add a comment |
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
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
add a comment |
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
add a comment |
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
add a comment |
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
An ingenious solution! Please fix your indentation. Why is the function calledrotate_left3
? How would you deal with OP wanting to rotate the listk
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
add a comment |
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.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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)]
add a comment |
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)]
add a comment |
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)]
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)]
edited Oct 16 '18 at 4:25
answered Mar 24 '18 at 7:36
Sreeram TPSreeram TP
3,67131442
3,67131442
add a comment |
add a comment |
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]
Just a side note: Although your solution returns the specific result required in the question, according to the python docdeque.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. changingdl.rotate(k+1)
intodl.rotate(-1*k)
should fix your code
– 0x51ba
Mar 24 '18 at 14:10
add a comment |
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]
Just a side note: Although your solution returns the specific result required in the question, according to the python docdeque.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. changingdl.rotate(k+1)
intodl.rotate(-1*k)
should fix your code
– 0x51ba
Mar 24 '18 at 14:10
add a comment |
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]
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]
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 docdeque.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. changingdl.rotate(k+1)
intodl.rotate(-1*k)
should fix your code
– 0x51ba
Mar 24 '18 at 14:10
add a comment |
Just a side note: Although your solution returns the specific result required in the question, according to the python docdeque.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. changingdl.rotate(k+1)
intodl.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
add a comment |
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
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
add a comment |
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
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
add a comment |
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
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
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
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Jun 22 '18 at 3:19
classicdude7classicdude7
88117
88117
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Mar 23 at 13:51
answered Mar 22 at 10:12
Ken MbogoKen Mbogo
112
112
add a comment |
add a comment |
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
An ingenious solution! Please fix your indentation. Why is the function calledrotate_left3
? How would you deal with OP wanting to rotate the listk
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
add a comment |
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
An ingenious solution! Please fix your indentation. Why is the function calledrotate_left3
? How would you deal with OP wanting to rotate the listk
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
add a comment |
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
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
answered Nov 29 '18 at 11:16
Harun OzHarun Oz
15
15
An ingenious solution! Please fix your indentation. Why is the function calledrotate_left3
? How would you deal with OP wanting to rotate the listk
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
add a comment |
An ingenious solution! Please fix your indentation. Why is the function calledrotate_left3
? How would you deal with OP wanting to rotate the listk
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Sep 2 '18 at 0:50
Grant Miller
6,697133458
6,697133458
answered Sep 1 '18 at 22:28
kaponekapone
1
1
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
This problem almost surely can be easier solved with slicing.
– DYZ
Mar 24 '18 at 7:11
Consider the case when
i==0
andk==1
(the shift of the first element by one position to the right).a[i] = a[(i+n-1+k)%n]
becomesa[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
print
ing 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