LearnFrenzy
Sign in Take a free test

Python Coding Interview Questions · Coding Problems – Arrays and Strings · Question 9

Count-and-say sequence with run-length grouping in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Generate the first 6 terms of the count-and-say sequence: 1, 11 ("one 1"), 21 ("two 1s"), 1211, …

Solution
main.py Run
from itertools import groupby

def next_term(s):
    return "".join(f"{len(list(group))}{digit}" for digit, group in groupby(s))

term = "1"
terms = [term]
for _ in range(5):
    term = next_term(term)
    terms.append(term)
print(terms)

Output Verified by running it on Python 3

['1', '11', '21', '1211', '111221', '312211']

groupby splits a string into runs of equal characters; each run becomes its length followed by the digit.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links