Skip to content

Instantly share code, notes, and snippets.

@cpdean
Created December 24, 2019 23:50
Show Gist options
  • Save cpdean/290986b16c02f492b868af68591950fa to your computer and use it in GitHub Desktop.
Save cpdean/290986b16c02f492b868af68591950fa to your computer and use it in GitHub Desktop.
def fib(n):
if n in (0, 1):
return 1
return fib(n-1) + fib(n - 2)
def fib_better(n):
if n == 0:
return 0
return fib(n - 1) + fib_better(n - 1)
def get_depth(line):
count = 0
for i in line:
if i == " ":
count += 1
else:
break
return int(count / 4)
def strip_indent(line):
d = get_depth(line)
return line[d * 4:]
def parse_depths(code):
return [(get_depth(line), strip_indent(line)) for line in code.split("\n")]
def fibonacci_indent(code):
parsed = parse_depths(code)
re_indented = [" " * fib_better(d) + line for (d, line) in parsed]
return "\n".join(re_indented)
if __name__ == '__main__':
code = """
class Foo:
def __init__(self):
a = []
for i in range(100):
for j in range(10):
if j < i:
if j % 2 == 0:
something = 0
for s in range(i):
someting += j
for x in range(something):
1 + 1
if x > 100:
continue
else:
a.append(x)
else:
continue
a.append(i + j)
self.a = a
"""
print("\n" * 10)
print("normal 4-space indent ")
print(code)
print("fibonacci indented:")
print(fibonacci_indent(code))
for i in range(8):
previous = i - 1 if i != 0 else 0
print("{},{} ({})".format(
i,
fib_better(i),
fib_better(i) - fib_better(previous)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment