# Pattern After Double, Reverse, and Swap in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a number n, we have ot find the nth value from the sequence. The sequence is like below −

• xxy
• xxyxxy
• yxxyxx
• xyyxyy
• xyyxyyxyyxyy
• ...

To generate the next value, we have to follow these rules, starting with xxy as the first term −

• When we are at the start of the pattern, double it(concatenate the string with itself).

• When the last operation was doubling, reverse it.

• When the last operation was reversing, exchange all xs with ys and vice versa.

• Repeat these steps.

So, if the input is like n = 5, then the output will be "yyxyyxyyxyyx"

To solve this, we will follow these steps −

• i := 0
• ret := "xxy"
• while i < n, do
• if i mod 3 is same as 0, then
• ret := ret + ret
• otherwise when i mod 3 is same as 1, then
• ret := subarray of ret from index 0 to end-1
• otherwise,
• new_stringy := blank string
• for each c in ret, do
• if c is same as "x", then
• new_stringy := new_stringy concatenate "y"
• otherwise,
• new_stringy := new_stringy concatenate "x"
• ret := new_stringy
• i := i + 1
• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, s):
i = 0
ret = "xxy"
while i < s:
if i % 3 == 0:
ret += ret
elif i % 3 == 1:
ret = ret[::-1]
else:
new_stringy = ""
for c in ret:
if c == "x":
new_stringy += "y"
else:
new_stringy += "x"
ret = new_stringy
i += 1
return ret
ob = Solution()
print(ob.solve(5))

## Input

5

## Output

yyxyyxyyxyyx
Updated on 22-Sep-2020 11:30:12