Problem : Given a list of strings, some of which may be anagrams amongst themselves, print the permutations which can be so constructed
so that each permutation has set of strings which is completely
unique.
This is an atrocious spec. IMO you needed to spend more time on requirements gathering before starting to code. As it is, we're forced to try to reverse engineer the requirements from two test cases.
input : “asda”, “daas”, “dand”, “nadd”
output : {“asda”, “dand”}, {“daas”, “dand”}, {“asda”, “nadd”}, {“daas”, “nadd”}
Since {"asda", "dand"}
is included in the output but {"dand", "asda"}
is not, clearly permutation is the wrong word.
As for "uniqueness", it appears from the examples that what this really means is that none of the output sets should contain two words which are anagrams of each other.
Finally, I note that all of the output sets are maximal under that assumption, although nothing in the problem statement hints at that.
So the real requirements seem to be
Given a list of strings, some of which may be anagrams of each other, output a list containing every maximal subset which doesn't contain two words which are anagrams of each other.
Other answers have already commented on is_anagram
, and I have nothing to add.
def random_set(input_value):
That's a misleading name: it strongly implies that the return value is a single set, whereas in fact it should be a list of sets.
"""returns the set of strings which are completely unique"""
No, it doesn't. If it did, the implementation would be just return set(input_value)
.
if len(input_value) <= 2:
output = input_value
I don't believe that Python style guides prohibit early returns, and it's easier to understand what an early return is doing than an assignment to a variable which then isn't used again for a long time.
Also, this is buggy. Consider the test case ["asda", "daas"]
, which should return [{"asda"}, {"daas"}]
.
In fact, it should be obvious that it's wrong because it doesn't return the same type as the else
case. One branch returns a list of strings, and the other a list of sets of strings.
else:
output = []
for i in range(len(input_value)):
for j in range(len(input_value)):
if not is_anagram(input_value[i], input_value[j]):
output.append( {input_value[i], input_value[j]})
You seem to have reverse engineered a very different spec to me. I'm pretty sure that there are inputs for which the subsets should have more than two elements.
If my understanding of the spec is correct, there should be a phase which gathers the input strings into equivalence classes and then another phase which calculates a Cartesian product of all of the equivalence classes.