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?

asked Jul 3, 2019 at 5:48
\$\endgroup\$
1
  • 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\$ Commented Jul 3, 2019 at 6:04

1 Answer 1

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')
answered Jul 3, 2019 at 23:09
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.