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

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



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
Updated on: 2020-10-05T07:22:38+05:30

314 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements