1
\$\begingroup\$

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, say FIRSTCHARSTRING.
Check If FIRSTCHARSTRING 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?

\$\endgroup\$
  • 1
    \$\begingroup\$ What is/are your goal/s in 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\$ – greybeard Jul 3 at 6:04
2
\$\begingroup\$

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')
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.