Skip to content

Instantly share code, notes, and snippets.

@routevegetable
Last active July 3, 2022 17:22
Show Gist options
  • Save routevegetable/fa3a806435e05d1d1b0991ca3752b40d to your computer and use it in GitHub Desktop.
Save routevegetable/fa3a806435e05d1d1b0991ca3752b40d to your computer and use it in GitHub Desktop.
def ingest(s):
counts = {}
for c in s:
if not c in counts:
counts[c] = 0
counts[c] += 1
return counts
import math
def run(count_dict, middle_char = ""):
# Sort by count
item_list = list(count_dict.items())
item_list.sort(key=lambda a: a[1], reverse=True)
# Starting from the lowest ordered (most common) pair,
# build the rest of the palindrome
output = ""
for char,count in item_list:
# Less than 2 of this char left
if count < 2:
continue
output += char * math.floor(count / 2)
# Assemble the two halves
return output[::-1] + middle_char + output
count_dict = ingest("sexytimes")
# Find the highest ordered (least common) single
# to start with as the middle character
singles = [(char,count) for (char,count) in count_dict.items() if count % 2 == 1]
singles.sort(key=lambda a: a[1])
if len(singles) > 0:
result = run(count_dict, middle_char=singles[0][0])
else:
result = run(count_dict)
result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment