Teaching Kids Programming – Recursive Algorithm to Count and Say a Number String | ninjasquad

**Teaching Kids Programming**: Videos on **Data Structures and Algorithms**

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

countAndSay(1) = “1”

countAndSay(n) is the way you would “say” the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you “say” a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.For example, the saying and conversion for digit string “3322251”:

Given a positive integer n, return the nth term of the count-and-say sequence.

Example 1:

Input: n = 1

Output: “1”

Explanation: This is the base case.Example 2:

Input: n = 4

Output: “1211”

Explanation:

countAndSay(1) = “1”

countAndSay(2) = say “1” = one 1 = “11”

countAndSay(3) = say “11” = two 1’s = “21”

countAndSay(4) = say “21” = one 2 + one 1 = “12” + “11” = “1211”Constraints:

1 <= n <= 30

### Recursive Algorithm to Count and Say a Number String

In order to compute the F(N), we need to know the value of F(N-1) and then we can count and say based on it. Thus, the problem is intuitively solvable via Recursion.

We can use the itertools.groupby function to group the digits and then we can count and say them.

The @cache (memoization) is optional, and it does not directly benefit the computation in this case, i.e. each F(N) value is computed once.

1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Solution: def countAndSay(self, n): @cache def f(n): if n == 1: return "1" a = f(n - 1) ans = [] for i, j in itertools.groupby(a): ans.append(str(len(list(j)))) ans.append(i) return "".join(ans) return f(n) |

class Solution: def countAndSay(self, n): @cache def f(n): if n == 1: return "1" a = f(n - 1) ans = [] for i, j in itertools.groupby(a): ans.append(str(len(list(j)))) ans.append(i) return "".join(ans) return f(n)

The time/space complexity is .

if the last digit of S is not the same as the first digit of T.

–EOF (The Ultimate Computing & Technology Blog) —

**GD Star Rating***loading…*

616 words

**Last Post**: C#: How to Create, Update, Delete and Check (If Exists) an Azure Resource Group in .NET?

Source: Internet