Skip to content

Instantly share code, notes, and snippets.

@jcamenisch
Created October 18, 2019 00:03
Show Gist options
  • Save jcamenisch/96db8240a1e4d69050a59e434c664f06 to your computer and use it in GitHub Desktop.
Save jcamenisch/96db8240a1e4d69050a59e434c664f06 to your computer and use it in GitHub Desktop.
Kwik Refactoring Drill
######################################################################
# INPUT MODULE
import line_storage
######################################################################
## CIRCULAR SHIFTER
#
# Make circ_index store something represetning all circular shifts
#
# Fact: For a line with K words, there are K circular shifts.
# As a result, the ith shift is the line containing the ith word in the file,
#
# Store shifts as (line, shift idx) pairs
circ_index = None
def cs_setup():
global circ_index
circ_index = []
for lineno in range(line_storage.line_count()):
line = line_storage.get_line(lineno)
for wordno in range(len(line)):
circ_index.append( (lineno, wordno) )
######################################################################
## ALPHABETIZING MODULE
alph_index = None
def alphabetize():
global alph_index, circ_index
def cmp_csline(shift1, shift2):
def csword(shift, wordno):
(lno, first_word_no) = shift
shift_idx = (first_word_no + wordno) % len(line_storage.get_line(lno))
return line_storage.get_line(lno)[shift_idx]
def cswords(shift):
return len(line_storage.get_line(shift[0]))
nwords1 = cswords(shift1)
nwords2 = cswords(shift2)
lasti = min(nwords1, nwords2)
for i in range(lasti+1):
cword1 = csword(shift1, i)
cword2 = csword(shift2, i)
if cword1 != cword2:
return cmp(cword1, cword2)
return cmp(nwords1, nwords2)
alph_index = sorted(circ_index, cmp=cmp_csline)
######################################################################
## OUTPUT MODULE
def print_all_alph_cs_lines():
global alph_index
def csline(shift):
(lno, first_word_no) = shift
wrd_cnt = len(line_storage.get_line(lno))
return [line_storage.get_line(lno)[(i+first_word_no) % wrd_cnt] for i in range(wrd_cnt)]
for shift in alph_index:
print (csline(shift))
## MASTER CONTROL
line_storage.putfile([["a", "b", "c", "d"],
["one"],
["hey", "this", "is", "different"],
["a", "b", "c", "d"]])
cs_setup()
alphabetize()
print_all_alph_cs_lines()
import copy
# List of list of words
line_store = None
def putfile(linelist):
global line_store
line_store = copy.copy(linelist)
def line_count():
return len(line_store)
def get_line(i):
return line_store[i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment