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.
More Python Coding Interview Questions practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!