aboutsummaryrefslogtreecommitdiff
path: root/challenge-094/paulo-custodio/python/ch-1.py
blob: be80772501297b5a55358827f3d064081672679d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python

# Challenge 094
#
# TASK #1 > Group Anagrams
# Submitted by: Mohammad S Anwar
# You are given an array of strings @S.
#
# Write a script to group Anagrams together in any random order.
#
# An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
#
# Example 1:
#     Input: ("opt", "bat", "saw", "tab", "pot", "top", "was")
#     Output: [ ("bat", "tab"),
#               ("saw", "was"),
#               ("top", "pot", "opt") ]
# Example 2:
#     Input: ("x")
#     Output: [ ("x") ]

import sys

def make_key(str):
    return ''.join(sorted(str))

def print_map(map):
    output = "[ "
    for value in map.values():
        output += "("
        for word in value:
            output += '"' + word + '", '
        output = output[:-2] + "),\n  "
    output = output[:-4] + " ]"
    print(output)

def solve():
    map = {}

    for arg in sys.argv[1:]:
        key = make_key(arg)
        if key not in map:
            map[key] = []
        map[key] += [arg]

    print_map(map)

solve()