-2

I currently have the function

def ndfa_as_str(ndfa: {str: {str: {str}}}) -> str:
    ndfa_str = ""
    sortedfa = sorted(ndfa.keys(), key=lambda x: x.lower())
    for i in sortedfa:
        ndfa_str += ("  {} transitions: {}".format(i, list(sorted(ndfa[i].items()))) + "\n")
    return ndfa_str

ndfa = {
    'end': {},
    'start': {'1': {'start'}, '0': {'near', 'start'}},
    'near': {'1': {'end'}}}

my function returns:

"  end transitions: []\\n  near transitions: [(\'1\', {\'end\'})]\\n  start transitions: [(\'0\', {\'near\', \'start\'}), (\'1\', {\'start\'})]\\n"'

however I am looking to return:

"  end transitions: []\\n  near transitions: [(\'1\', [\'end\'])]\\n  start transitions: [(\'0\', [\'near\', \'start\']), (\'1\', [\'start\'])]\\n"'

where the sets are lists instead.

What's the simplest way I could do this?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Novius
  • 21
  • 4
  • 1
    Does this answer your question? [Get a list from a set in python](https://stackoverflow.com/q/6405512/4518341). If not, what have you already tried? For example, do you know how to do a list comprehension? – wjandrea Jan 18 '22 at 00:58

1 Answers1

0

I think this does what you want. It uses a recursive nested helper function which seems appropriate since the sets are nested. It converts any sets encountered using the built-in sorted() function.

from operator import itemgetter

def ndfa_as_str(ndfa):
    getkey = lambda x: itemgetter(0)(x).lower()

    def value_to_list(obj):
        if isinstance(obj, dict):
            return [(key, value_to_list(value))
                        for key, value in sorted(obj.items(), key=getkey)]
        elif isinstance(obj, set):
            return sorted(obj)
        else:
            return obj

    lines = [f'  {key} transitions: {value_to_list(value)}'
                for key, value in sorted(ndfa.items(), key=getkey)]
    return '\n'.join(lines)


ndfa = {
    'end': {},
    'start': {'1': {'start'}, '0': {'near', 'start'}},
    'near': {'1': {'end'}}}

print(ndfa_as_str(ndfa))

Result printed:

  end transitions: []
  near transitions: [('1', ['end'])]
  start transitions: [('0', ['near', 'start']), ('1', ['start'])]
martineau
  • 119,623
  • 25
  • 170
  • 301