Last active
March 11, 2018 21:41
-
-
Save brandonio21/fc3b780349684f069ae0949809112321 to your computer and use it in GitHub Desktop.
Convert simple python for loops to while loops
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
""" | |
Super simple script to convert for loops to while loops | |
Usage: | |
$ python f2w.py | |
for i in [1,2,3]: | |
print(i) | |
^D | |
__i = 0 | |
while __i < len([1,2,3]): | |
i = [1,2,3][__i] | |
print(i) | |
__i += 1 | |
""" | |
import re | |
import textwrap | |
import sys | |
FOR_REGEX = re.compile(r'^(\s*)for\s+(\w+)\s+in\s+(\w+):(.+)', | |
flags=re.DOTALL | re.MULTILINE) | |
for_stmt = sys.stdin.read() | |
print(FOR_REGEX.sub( | |
r"\1__i = 0\n\1while __i < len(\3):\n \2 = \3[__i]\4 __i += 1", | |
for_stmt | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment