Skip to content

Instantly share code, notes, and snippets.

@chicolucio
Forked from henriquebastos/magic_indexes.py
Created November 1, 2019 12:07
Show Gist options
  • Save chicolucio/8df35cc5d224c12bf8459811a918301f to your computer and use it in GitHub Desktop.
Save chicolucio/8df35cc5d224c12bf8459811a918301f to your computer and use it in GitHub Desktop.
IPython Magic to show sequence's indexes
"""
IPython Magic to show sequence's indexes.
Useful to demonstrate how python indexes works with strings.
Example:
>>> %indexes henrique
0 1 2 3 4 5 6 7
h e n r i q u e
-8 -7 -6 -5 -4 -3 -2 -1
This file should be copies to:
.ipython/profile_default/startup/
"""
from IPython.core.magic import register_line_magic
def indexes_func(s):
if not s: return
l = len(s)
h = [str(n) for n in range(l)]
f = [str(n-l) for n in range(l)]
w = len(max(f, key=len))
r = lambda l: [c.rjust(w) for c in l]
return '\n'.join([' '.join(r(h)), ' '.join(r(s)), ' '.join(r(f))])
@register_line_magic
def indexes(iter):
'''Shows indexes of a sequence'''
print(indexes_func(iter))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment