- Related Questions & Answers
- Program to find nth term in Look and Say Sequence in Python
- Program to find sum of given sequence in C++
- Find nth term of the Dragon Curve Sequence in C++
- Find element position in given monotonic sequence in Python
- Find bitonic point in given bitonic sequence in Python
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- C++ Program to Find the Longest Prefix Matching of a Given Sequence
- Program to find length of longest consecutive sequence in Python
- Program to find nth term of a sequence which are divisible by a, b, c in Python
- How to find longest repetitive sequence in a string in Python?
- C# Program to find the sum of a sequence
- Program to find number of swaps required to sort the sequence in python
- Python Sequence Types
- Find maximum length Snake sequence in Python
- Program to Find Out a Sequence with Equivalent Frequencies in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

- if i mod 2 is same as 0, then
- return c

Let us see the following implementation to get better understanding −

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))

"pk", "r", 4

rrpkrpk

Advertisements