I have solved a previous year question of 2018 codevita (link) in Python.
Problem Description:
Rotate a given String in the specified direction by specified magnitude.
After each rotation make a note of the first character of the rotated String, After all rotation are performed the accumulated first character as noted previously will form another string, sayFIRSTCHARSTRING
.
Check IfFIRSTCHARSTRING
is an Anagram of any substring of the Original string.
If yes print "YES" otherwise "NO".
Here is the code:
from collections import Counter
def lrotate(input,d):
Lfirst = input[0 : d]
Lsecond = input[d :]
return (Lsecond + Lfirst)
def rrotate(input,d):
Rfirst = input[0 : len(input)-d]
Rsecond = input[len(input)-d : ]
return (Rsecond + Rfirst)
s=input()
n=int(input())
c='FIRSTCHARSTRING'
l=[]
for _ in range(n):
w,v=input().split()
v=int(v)
if w == 'L':
p=lrotate(c,v)
if w == 'R':
p=rrotate(c,v)
l.append(p[0])
if Counter(l) == Counter(s) :
print("Yes")
else:
print("No")
What can I do to optimize my code?
1 Answer 1
You can use python deque
function to rotate string.
word = 'FIRSTCHARSTRING'
commands = [
('L', 2),
('R', 3),
('L', 1),
]
from collections import deque
q = deque(word)
for direction, magnitude in commands:
if direction == 'L':
q.rotate(-magnitude)
else:
q.rotate(magnitude)
if ''.join(q) == word:
print('Yes')
else:
print('No')
Explore related questions
See similar questions with these tags.
optimize my code
? Your implementation tries to stick to the letter of the task description (which is a good thing at least for a reference for correctness) - you might go for readability, maintainability, acceptable result using least resources (including coder time) or exact result using least machine resources or... \$\endgroup\$