educative.io

More intuitive solution (I think)

from collections import deque


class AbbreviatedWord():
  def __init__(self, str, count):
    self.str = str
    self.count = count


def generate_generalized_abbreviation(word):
  results = []
  wordsq = deque()
  wordsq.append(AbbreviatedWord("", 0))
  for char in word:
    lenq = len(wordsq)
    for _ in range(lenq):
      w = wordsq.popleft()
      wordsq.append(AbbreviatedWord(w.str, w.count + 1))
      if w.count > 0:
        wordsq.append(AbbreviatedWord(w.str + str(w.count) + char, 0))
      else:
        wordsq.append(AbbreviatedWord(w.str + char, 0))
  for w in wordsq:
    if w.count > 0:
      results.append(w.str + str(w.count))
    else:
      results.append(w.str)
  return results

Type your question above this line.

Course: https://www.educative.io/collection/5668639101419520/5671464854355968
Lesson: https://www.educative.io/collection/page/5668639101419520/5671464854355968/5646748928180224

Hi @Andres_Parra,

Yeah, it also looks great. Thank you for sharing this :slight_smile:

1 Like