Evan Rosica
Evan Rosica

Reputation: 1242

Properly Formatting Set Output in Python

I'm writing a program who's input is a set of sets (or "collection") in python syntax. The output of the program should be the same collection in proper mathematical syntax. To do so, I've written a recursive function

collection = set([
            frozenset(["a,b,c"]),
            frozenset(),
            frozenset(["a"]),
            frozenset(["b"]),
            frozenset(["a,b"])
            ])

def format_set(given_set):
    # for each element of the set
    for i in given_set:
        #if the element is itself a set, begin recursion
        if type(i) == frozenset:
            format_set(i)
        else:
            return "{", i, "},",

calling format_set(collection) gives the output

{ a,b }, { a,b,c }, { b }, { a },

which is missing a pair of parenthesis, and has an extra comma at the end. The correct output would be

{{ a,b }, { a,b,c }, { b }, { a },{}}.

Thus, I would need to add "{" before the first recursion, and "}" after the last, as well as not adding the comma after the last recursion. Is there a way to find the final recursion?

I could always solve the extra parenthesis problem by defining:

def shortcut(x):
    print "{", frozen_set(x), "}"

However, I feel like that's somewhat inelegant, and still leaves the comma problem.

Upvotes: 0

Views: 473

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65811

It will be more straightforward if you check the type first and then do the iteration:

def format_set(given):
    if isinstance(given, (set, frozenset)):
        return '{' + ', '.join(format_set(i) for i in given) + '}'
    else:
        return str(given)

Output:

{{a,b}, {a,b,c}, {}, {b}, {a}}

Also, note that in your example input all sets are actually empty or have 1 element. If you change the input like this...

collection = set([
            frozenset(["a", "b", "c"]),
            frozenset(),
            frozenset(["a"]),
            frozenset(["b"]),
            frozenset(["a", "b"])
            ])

...you'll get this output:

{{a, c, b}, {}, {b}, {a}, {a, b}}

Upvotes: 4

Related Questions