Count and Say in Python

The Count and Say sequence is a fascinating pattern where each term describes the previous term by counting consecutive identical digits. Let's understand how this sequence works and implement it in Python.

Understanding the Sequence

The Count and Say sequence starts with "1" and each subsequent term describes the previous term ?

  • Term 1: "1"
  • Term 2: "11" (one 1)
  • Term 3: "21" (two 1s)
  • Term 4: "1211" (one 2, one 1)
  • Term 5: "111221" (one 1, one 2, two 1s)
  • Term 6: "312211" (three 1s, two 2s, one 1)
Count and Say Sequence Visualization Term 1: 1 Term 2: 11 (one 1) Term 3: 21 (two 1s) Term 4: 1211 (one 2, one 1) Term 5: 111221 (one 1, one 2, two 1s) Term 6: 312211 (three 1s, two 2s, one 1)

Algorithm Approach

The algorithm works by iterating through each character in the current term and counting consecutive occurrences ?

  • Start with the base case "1"
  • For each iteration, count consecutive identical digits
  • Build the next term by appending count + digit
  • Repeat until we reach the nth term

Implementation

def count_and_say(n):
    """
    Generate the nth term of Count and Say sequence
    :param n: Position in sequence (1-indexed)
    :return: String representing nth term
    """
    if n == 1:
        return "1"
    
    current = "1"
    
    for i in range(2, n + 1):
        next_term = ""
        j = 0
        
        while j < len(current):
            digit = current[j]
            count = 1
            
            # Count consecutive identical digits
            while j + count < len(current) and current[j + count] == digit:
                count += 1
            
            # Append count + digit to next term
            next_term += str(count) + digit
            j += count
        
        current = next_term
    
    return current

# Test the function
for i in range(1, 7):
    result = count_and_say(i)
    print(f"Term {i}: {result}")
Term 1: 1
Term 2: 11
Term 3: 21
Term 4: 1211
Term 5: 111221
Term 6: 312211

Step-by-Step Example

Let's trace through generating the 4th term ?

def count_and_say_detailed(n):
    current = "1"
    print(f"Term 1: {current}")
    
    for i in range(2, n + 1):
        next_term = ""
        j = 0
        print(f"\nGenerating Term {i} from '{current}':")
        
        while j < len(current):
            digit = current[j]
            count = 1
            
            while j + count < len(current) and current[j + count] == digit:
                count += 1
            
            segment = str(count) + digit
            next_term += segment
            print(f"  Found {count} consecutive '{digit}'(s) ? add '{segment}'")
            j += count
        
        current = next_term
        print(f"Term {i}: {current}")
    
    return current

# Generate 4th term with detailed steps
result = count_and_say_detailed(4)
Term 1: 1

Generating Term 2 from '1':
  Found 1 consecutive '1'(s) ? add '11'
Term 2: 11

Generating Term 3 from '11':
  Found 2 consecutive '1'(s) ? add '21'
Term 3: 21

Generating Term 4 from '21':
  Found 1 consecutive '2'(s) ? add '12'
  Found 1 consecutive '1'(s) ? add '11'
Term 4: 1211

Optimized Version

Here's a more concise implementation using Python's groupby function ?

from itertools import groupby

def count_and_say_optimized(n):
    """
    Optimized version using itertools.groupby
    """
    result = "1"
    
    for _ in range(n - 1):
        result = ''.join(str(len(list(group))) + key 
                        for key, group in groupby(result))
    
    return result

# Test the optimized version
print("Using optimized approach:")
for i in range(1, 7):
    result = count_and_say_optimized(i)
    print(f"Term {i}: {result}")
Using optimized approach:
Term 1: 1
Term 2: 11
Term 3: 21
Term 4: 1211
Term 5: 111221
Term 6: 312211

Conclusion

The Count and Say sequence demonstrates pattern recognition where each term describes the previous term by counting consecutive digits. The algorithm iterates through each character, counts consecutive occurrences, and builds the next term by appending count + digit pairs.

Updated on: 2026-03-25T07:08:48+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements