fef-questionnaire/questionnaire/utils.py

56 lines
1.1 KiB
Python

#!/usr/bin/python
def split_numal(val):
"""Split, for example, '1a' into (1, 'a')
>>> split_numal("11a")
(11, 'a')
>>> split_numal("99")
(99, '')
>>> split_numal("a")
(0, 'a')
>>> split_numal("")
(0, '')
"""
if not val:
return 0, ''
for i in range(len(val)):
if not val[i].isdigit():
return int(val[0:i] or '0'), val[i:]
return int(val), ''
def numal_sort(a, b):
"""Sort a list numeric-alphabetically
>>> vals = "1a 1 10 10a 10b 11 2 2a z".split(" "); \\
... vals.sort(numal_sort); \\
... " ".join(vals)
'z 1 1a 2 2a 10 10a 10b 11'
"""
anum, astr = split_numal(a)
bnum, bstr = split_numal(b)
cmpnum = cmp(anum, bnum)
if(cmpnum == 0):
return cmp(astr, bstr)
return cmpnum
def numal0_sort(a, b):
"""
numal_sort on the first items in the list
"""
return numal_sort(a[0], b[0])
def calc_alignment(string):
l = 2 + len(string.strip()) // 6
if l <= 4:
return 4
if l <= 7:
return 7
if l < 10:
return 10
return l
if __name__ == "__main__":
import doctest
doctest.testmod()