- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

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

# 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

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

Let us see the following implementation to get better understanding −

## Example

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

- Related Articles
- Program to find nth term in Look and Say Sequence in Python
- Program to find last digit of the given sequence for given n in Python
- Program to find sum of given sequence in C++
- Program to find number of ways we can select sequence from Ajob Sequence in Python
- Program to find nth term of a sequence which are divisible by a, b, c in Python
- 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 out the distinct elements in a given sequence
- How to find longest repetitive sequence in a string in Python?
- Program to find length of longest consecutive sequence in Python
- Program to find removed term from arithmetic sequence in Python
- C++ Program to Find the Longest Prefix Matching of a Given Sequence
- C++ Program to Find the Longest Increasing Subsequence of a Given Sequence
- Program to Find Out a Sequence with Equivalent Frequencies in Python

Advertisements