読者です 読者をやめる 読者になる 読者になる

珠玉のプログラミングのお題を python で書いてみた : 3

python algorithm
#!/bin/env python

"""
2.3 the loop/combination of basic procedure(P16-18)
Problem B turning over : rotdist=3, "abcdefgh" -> "defghabc"
Solution 1
"""
# global
DATA = ['a','b','c','d','e','f','g','h']
ROTDIST = 3
LENGTH = len(DATA)

def main():
    
    print "input  : ", DATA
    convert_data, cnt = otedama(DATA, gcd(ROTDIST, LENGTH), LENGTH)
    if cnt != LENGTH:
        for x in xrange(1, ROTDIST):
            convert_data, cnt = otedama(DATA, x, LENGTH)
        
    print "output : ", convert_data

def otedama(d, p, l):
    i = p
    t = d[i]
    j = i
    c = 1
    while 1:
        k = j + ROTDIST
        if k >= l:
            k -= l
        if k == i:
            break
        d[j] = d[k]
        j = k
        c += 1
    d[j] = t
    return d, c

def gcd(i, j):
    while i != j:
        if i > j:
            i -= j
        else:
            j -= i
    return i

if __name__ == '__main__':
    main()
#!/bin/env python

"""
2.3 the loop/combination of basic procedure(P16-18)
Problem B turning over : rotdist=3, "abcdefgh" -> "defghabc"
Solution 2
"""
# global
DATA = ['a','b','c','d','e','f','g','h']
ROTDIST = 3

def main():
    
    print "input  : ", DATA
    
    length = len(DATA)
    reverse(0, ROTDIST)
    reverse(ROTDIST, length)
    reverse(0, length)
    
    print "output : ", DATA

def reverse(s, e):
    for i in DATA[s:e][::-1]:
        DATA[s] = i
        s += 1

if __name__ == '__main__':
    main()

実行結果。

input  :  ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
output :  ['d', 'e', 'f', 'g', 'h', 'a', 'b', 'c']