from typing import List, Dict
# Groups a list of strings into sublists of anagrams.
def group_anagrams(words: List[str]) -> List[List[str]]:
# Validate input
if not isinstance(words, list):
raise TypeError("Input must be a list of strings.")
map: Dict[str, List[str]] = {}
for word in words:
if not isinstance(word, str):
raise TypeError("All elements in the list must be strings.")
# Sort characters
sortword = ''.join(sorted(word))
# Group words by their sorted key
if sortword not in map:
map[sortword] = []
map[sortword].append(word)
# Return grouped anagrams as a list of lists
return list(map.values())
if __name__ == "__main__":
try:
lst = ["eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"]
result = group_anagrams(lst)
# Print result
print("[")
for group in result:
print(" [ " + ", ".join(f"'{w}'" for w in group) + " ]")
print("]")
except Exception as error:
print(error)
'''
run:
[
[ 'eat', 'tea', 'ate' ],
[ 'rop', 'orp', 'pro' ],
[ 'nat', 'tan' ],
[ 'bat' ]
]
'''