Damian Brunold

Counter Strings in Python

2011-11-29 11:51 Programmieren, Python, Testen

James Bach hat in seinem Blog die Counter Strings vorgestellt. Eine geniale Idee. Er erzeugt sie mit einem Perl-Programm (PerlClip). Ich habe nun den Teil der Counter-String-Erzeugung nach Python übersetzt:

#!/usr/bin/env python3

# counterstring adapted from the code in "perlclip" package (see e.g. james bach)

# The idea is to start at the end of the string. The end must be a *
# character (or whatever the indicator character is). So the preceding
# number is obviously the target length. Preceding to this number is a
# * again, whose position can be calculated in the same manner.
#
# Since this builds the counter string in reverse, the position
# strings have to be added reversed and the final result string is
# reversed also.

def generate_counter_string(target_length, char="*"):
    result = ""
    pos = target_length
    while True:
        if len(result) + len(str(pos)) + 1 > target_length:
            result += char * (target_length - len(result))
            break
        result += char + str(pos)[::-1]
        pos -= len(str(pos)) + 1
    return result[::-1]

if __name__ == "__main__":
    print(generate_counter_string(int(sys.argv[1])))

Und hier die ersten paar Strings:

>>> from counterstring import *
>>> for length in range(20):
...   print(generate_counter_string(length))
... 

*
2*
*3*
2*4*
*3*5*
2*4*6*
*3*5*7*
2*4*6*8*
*3*5*7*9*
*3*5*7*10*
2*4*6*8*11*
*3*5*7*9*12*
*3*5*7*10*13*
2*4*6*8*11*14*
*3*5*7*9*12*15*
*3*5*7*10*13*16*
2*4*6*8*11*14*17*
*3*5*7*9*12*15*18*
*3*5*7*10*13*16*19*