Created
June 30, 2019 10:18
-
-
Save travishen/e10e4d602fd43e859e626e127054949c to your computer and use it in GitHub Desktop.
Cyclic iterator
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
{ | |
"cells": [ | |
{ | |
"cell_type": "code", | |
"execution_count": 1, | |
"metadata": {}, | |
"outputs": [], | |
"source": [ | |
"class CyclicIterator:\n", | |
" def __init__(self, iterable):\n", | |
" self.iterable = iterable\n", | |
" self.iterator = iter(self.iterable)\n", | |
" \n", | |
" def __iter__(self):\n", | |
" return self\n", | |
" \n", | |
" def __next__(self):\n", | |
" try:\n", | |
" return next(self.iterator)\n", | |
" except StopIteration:\n", | |
" self.iterator =iter(self.iterable)\n", | |
" return next(self.iterator)" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 2, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"a\n", | |
"b\n", | |
"c\n", | |
"d\n", | |
"e\n", | |
"a\n", | |
"b\n", | |
"c\n" | |
] | |
} | |
], | |
"source": [ | |
"alphabet = CyclicIterator('abcde')\n", | |
"for _ in range(8):\n", | |
" print(next(alphabet))" | |
] | |
}, | |
{ | |
"cell_type": "code", | |
"execution_count": 3, | |
"metadata": {}, | |
"outputs": [ | |
{ | |
"name": "stdout", | |
"output_type": "stream", | |
"text": [ | |
"a\n", | |
"b\n", | |
"c\n", | |
"d\n", | |
"e\n", | |
"a\n", | |
"b\n", | |
"c\n" | |
] | |
} | |
], | |
"source": [ | |
"import itertools\n", | |
"alphabet = itertools.cycle('abcde')\n", | |
"for _ in range(8):\n", | |
" print(next(alphabet))" | |
] | |
} | |
], | |
"metadata": { | |
"kernelspec": { | |
"display_name": "Python 3", | |
"language": "python", | |
"name": "python3" | |
}, | |
"language_info": { | |
"codemirror_mode": { | |
"name": "ipython", | |
"version": 3 | |
}, | |
"file_extension": ".py", | |
"mimetype": "text/x-python", | |
"name": "python", | |
"nbconvert_exporter": "python", | |
"pygments_lexer": "ipython3", | |
"version": "3.6.8" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment