> There's some playfulness here, with duck typing, in that the parameter > name suggests a set, yet we pass a string, then work with listifications. > This allows more types of input, yet the output should always be: a dict, > a mapping, a permutation. Running it now, I get: > > P1: {'1': '6', '0': '1', '3': '8', '2': '5', '5': '3', '4': '0', '7': > '2', '6': '4', '9': '9', '8': '7'} > P2: {'1': '0', '0': '5', '3': '6', '2': '4', '5': '8', '4': '3', '7': > '2', '6': '7', '9': '9', '8': '1'} > > So what's cyclic notation again? I hadn't gotten that far, as we needed > an easy way to get permutations. Thanks Python. > > Lets work on P1. You start a tuple going (1, 6, 4, 0). See what I did? > I started with 1, arbitrarily and found it maps to 6. Then I looked up 6 > and found it mapped to 4. I keep following that trail until I either get > back to where I started, meaning the last element is deemed to connect to > the first. It's a circle, a cycle. But maybe we're not done. 2 is not > mentioned so lets start there. 2 maps to 5 maps to 3 maps to 8 maps to 7 > maps to 2. Another circle: (2, 5, 3, 8, 7). Anyone missing? 9, where's > 9. 9 maps to itself, so (9,) -- using Python notation. And we're done: > P1 may be expressed as ((0, 1, 6, 4), (2, 5, 3, 8, 7), (9,)). I can start > with the lowest number in each cycle and sort the cycles by lowest > leftmost, if I want a canonical order. The above is canonical and unique > for P1. > > P1 = {'1': '6', '0': '1', '3': '8', '2': '5', '5': '3', '4': '0', '7': '2', '6': '4', '9': '9', '8': '7'} P2 = {'1': '0', '0': '5', '3': '6', '2': '4', '5': '8', '4': '3', '7': '2', '6': '7', '9': '9', '8': '1'}
def get_cyclic(codedict): """ Return Permutation dict as a tuple of cyclic tuples, e.g. (('A','R','C'),('D','Q')...) """ dictkeys = list(codedict.keys()) result = [] for i in list(dictkeys): # using copy of dictkeys newtuple = () if i in dictkeys: initval,nextval = i,i while True: newtuple += (nextval,) dictkeys.remove(nextval) nextval = codedict[nextval] if nextval==initval: # cycle complete break result.append(newtuple) return tuple(result) print(get_cyclic(P1)) print(get_cyclic(P2)) Running.... (('1', '6', '4', '0'), ('3', '8', '7', '2', '5'), ('9',)) (('1', '0', '5', '8'), ('3', '6', '7', '2', '4'), ('9',)) Process finished with exit code 0 Kirby
_______________________________________________ Edu-sig mailing list Edu-sig@python.org http://mail.python.org/mailman/listinfo/edu-sig