I am new to hackerrank and programming, the left rotate question from the data structure section is my third question I am trying to complete. My code as follow:
#!/bin/python3
import math
import os
import random
import re
import sys
def rotateLeft(d, arr, n):
# Write your code here
x=0
while x<d:
tmp=arr[0]
for i in range(n):
if i==(n-1):
arr[i]=tmp
break
arr[i]=arr[i+1]
x+=1
return arr
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
first_multiple_input = input().rstrip().split()
n = int(first_multiple_input[0])
d = int(first_multiple_input[1])
arr = list(map(int, input().rstrip().split()))
result = rotateLeft(d, arr, n)
fptr.write(' '.join(map(str, result)))
fptr.write('\n')
fptr.close()
After i submitted my question, hackerrank indicated that the time limit exceeded and i should optimize the code. Hence, I tried using the n variable provided instead of using len(arr), hoping to quicken it, but i guess it doesn't help. Hope you guys can give me some tips on optimizing the code. Thanks a lot!
2 Answers 2
Simply Use this rotLeft Function:
def rotLeft(a, d):
return a[d:]+a[:d]
Comments
You could simply use the list slicing for this problem.
def rotateLeft(d, arr, n):
return arr[d:]+arr[:d]
Comments
Explore related questions
See similar questions with these tags.
dis much greater than the size of the list. Do you really want to rotate and rotate and rotate... with steps of one? Or do you see a shortcut?