DEV Community

Discussion on: Daily Challenge #167 - Return String As Sorted Blocks

Collapse
 
candidateplanet profile image
lusen / they / them 🏳️‍🌈🥑 • Edited

in python

def blocks(str):
  # const - reference for extracting blocks
  order = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

  # count occurences of characters in str
  mapping = {}
  # build mapping
  for s in str:
    if s not in mapping:
      mapping[s] = 0
    mapping[s] += 1

  # iterate through mapping to create each block, decrementing the counts
  # with each pass. when the count is 0, delete the key,value pair.
  # stop iterating when there are no more values to create blocks from
  blocks = []
  while mapping.values():
    block = []
    for o in order:
      if o in mapping:
        block.append(o)
        mapping[o] -= 1
        if mapping[o] == 0:
          del mapping[o]
    blocks.append(''.join(block))

  return '-'.join(blocks)

print(blocks("21AxBz"), "xzAB12")
print(blocks("abacad"), "abcd-a-a")
print(blocks(""), "")
print(blocks("21BxAzAasfdaXZas"), "adfsxzABXZ12-asA-a")