[Tutor] request for sugestions on fragement of code for generating truth-tables

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Apr 6 23:56:16 CEST 2006


> One way to get rid of the 'recursed' flag is to refactor slightly, and
> break out the sorting in another helper function, like this:
>
> ##################################################################
> def tva_dict_maker(atoms):
>     tvas = tiva_helper(atoms)
             ^^^^^^^^^^^
>     tvas.sort(key = lambda x: [x[y] for y in sorted(x)],
>               reverse=True)
>     return tvas
>
> def tva_helper(atoms):
>     tvas = [{atoms[0]:True}, {atoms[0]:False}]
>     if atoms[1:]:
>         temp = []
>         rest = recursive_tva_dict_maker(atoms[1:])
                 ^^^^^^^^^^^^^^^^^^^^^^^^
>         for r in rest:
>             for tva in tvas:
>                 new = tva.copy()
>                 new.update(r)
>                 temp.append(new)
>         tvas = temp
>     return tvas
> ##################################################################


Hi Brian,

Gaaa.  When I renamed 'recursive_tva_dict_maker' to tva_helper, I forgot
to rename the recursive call too, and I left a few misspellings in there
too!  My apologies: I must must test code before posting... *sigh*

The code above should have been:

########################################################
def tva_dict_maker(atoms):
    tvas = tva_helper(atoms)
    tvas.sort(key = lambda x: [x[y] for y in sorted(x)],
              reverse=True)
    return tvas

def tva_helper(atoms):
    tvas = [{atoms[0]:True}, {atoms[0]:False}]
    if atoms[1:]:
        temp = []
        rest = tva_helper(atoms[1:])
        for r in rest:
            for tva in tvas:
                new = tva.copy()
                new.update(r)
                temp.append(new)
        tvas = temp
    return tvas
########################################################



More information about the Tutor mailing list