Created
September 6, 2012 21:30
-
-
Save dgladkov/3660508 to your computer and use it in GitHub Desktop.
Generates string range, analog of Perl's `print "a".."azc"`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import product | |
def string_range(first, last): | |
""" | |
Generates string range, analog of Perl's `print "a".."azc"` | |
Usage: string_range('a', 'azc') | |
""" | |
def ascii_generator(letters): | |
""" | |
Iterates single letters in provided single or multiple letter range | |
like ab-zz, where 'ab' is an argument passed to the function. | |
""" | |
for l in letters: | |
i = ord(l) | |
while i <= ord('z'): | |
yield chr(i) | |
i = i + 1 | |
min_length = len(first) - 1 | |
for k in range(len(last)): | |
if k < min_length: | |
continue | |
for x in product(ascii_generator(first), repeat=k + 1): | |
result = ''.join(x) | |
yield result | |
if result == last: | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment