/divspl.py Secret
Last active
July 14, 2022 15:03
DIVSPL interpreter in Python 3
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
#!/usr/bin/env nix-shell | |
#! nix-shell -i python3 -p python3 | |
import sys | |
# This is a basic interpreter for DIVSPL, as described at | |
# https://www.promptworks.com/blog/the-fastest-fizzbuzz-in-the-west | |
def parseAssignment(line): | |
word, number = [w.strip() for w in line.rsplit("=", 1)] | |
return word, int(number) | |
def parse(lines): | |
# The first line must be the range. | |
start, stop = [int(n.strip()) for n in next(lines).split("...")] | |
assignments = [parseAssignment(line) for line in lines] | |
return start, stop, assignments | |
def run(start, stop, assignments): | |
for i in range(start, stop + 1): | |
s = [w for w, n in assignments if not i % n] | |
yield "".join(s) if s else str(i) | |
# NB: programs should already be split into lines | |
def main(program): | |
start, stop, assignments = parse(program) | |
for line in run(start, stop, assignments): | |
print(line) | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main(sys.stdin)) |
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
1...15 | |
fizz=3 | |
buzz=5 |
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
1...105 | |
fizz=3 | |
buzz=5 | |
fuzz=7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment