[Tutor] putting a short list of integers into a (specific) compactform

Raymond Hettinger python at rcn.com
Sun Oct 12 19:21:06 EDT 2003


[kevin parks]
> here's what i'd like to do (it is quite complex, but it have tried to
> present the recipe as
> clearly as possible):


It is not so bad if you break in down functionally and use generators.
* rule1() applies the inital step
* rotations() returns a generator for each ordering
* orderings() prepends three values corresponding to rules 2, 3, and 4
* min() selects the best ordering based on rule2, falling back to 3
  in a tie, and back to four for a final tie breaker
* [3] throws away the ordering info leaving on the best sequence
* optional() applies to final transpose rule


def rule1(s):
    "Apply mod12, eliminate duplicates, and sort"
    set = {}
    for elem in s:
        set[elem%12] = True
    nodups = set.keys()
    nodups.sort()
    return nodups

def rotations(s):
    "generate all rotations of a sequence"
    for i in xrange(len(s)):
        yield s
        s = s[1:] + s[0:1]

def ordering(rots):
    "rules for deciding which rotation comes first"
    for s in rots:
        rule2 = (s[-1] - s[0]) % 12
        rule3 = (s[-2] - s[0]) % 12
        rule4 = s[0]
        yield rule2, rule3, rule4, s

def optional(s):
    "transpose the answer so it starts with zero"
    return [(x - s[0])%12 for x in s]
        

start = [4, 12, 20, 9, 11, 0, 8, 4]
print optional(min(ordering(rotations(rule1(start))))[3])


Raymond Hettinger




More information about the Tutor mailing list