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?
CodePudding user response:
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'])]
