Program to find nth sequence after following the given string sequence rules in Python

PythonServer Side ProgrammingProgramming

Suppose we have two strings s, t and another positive number n is also given, we have to find return the nth term of the sequence A where −

  • A[0] = s
  • A[1] = t
  • A[n] = A[n - 1] + A[n - 2] when n is even, otherwise A[n] = A[n - 2] + A[n - 1].

As an example, if s = "a" and t = "b", then the sequence A would be − ["a", "b", "ba" ("a" + "b"), "bba" ("b" + "ba"), "bbaba" ("bba" + "ba")]

So, if the input is like s = "pk", t = "r", n = 4, then the output will be "rrpkrpk"

To solve this, we will follow these steps −

  • if n is same as 0, then
    • return s
  • otherwise when n is same as 1, then
    • return t
  • a := s, b := t
  • for i in range 2 to n, do
    • if i mod 2 is same as 0, then
      • c := b concatenate a
    • otherwise,
      • c := a concatenate b
    • a := b
    • b := c
  • return c

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, s, t, n):
      if n == 0:
         return s
      elif n == 1:
         return t
         a = s
         b = t
      for i in range(2, n+1):
         if i%2 == 0:
            c = b + a
         else:
            c = a + b
            a = b
            b = c
      return c
ob = Solution()
print(ob.solve("pk", "r", 4))

Input

"pk", "r", 4

Output

rrpkrpk
raja
Published on 05-Oct-2020 10:51:17
Advertisements